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{ 109if(!refname) { 110/* 111 * FIXME: of course this is wrong in multi worktree 112 * setting. To be fixed real soon. 113 */ 114strbuf_addf(sb,"%s/logs", refs->gitcommondir); 115return; 116} 117 118switch(ref_type(refname)) { 119case REF_TYPE_PER_WORKTREE: 120case REF_TYPE_PSEUDOREF: 121strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 122break; 123case REF_TYPE_NORMAL: 124strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 125break; 126default: 127die("BUG: unknown ref type%dof ref%s", 128ref_type(refname), refname); 129} 130} 131 132static voidfiles_ref_path(struct files_ref_store *refs, 133struct strbuf *sb, 134const char*refname) 135{ 136switch(ref_type(refname)) { 137case REF_TYPE_PER_WORKTREE: 138case REF_TYPE_PSEUDOREF: 139strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 140break; 141case REF_TYPE_NORMAL: 142strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 143break; 144default: 145die("BUG: unknown ref type%dof ref%s", 146ref_type(refname), refname); 147} 148} 149 150/* 151 * Read the loose references from the namespace dirname into dir 152 * (without recursing). dirname must end with '/'. dir must be the 153 * directory entry corresponding to dirname. 154 */ 155static voidloose_fill_ref_dir(struct ref_store *ref_store, 156struct ref_dir *dir,const char*dirname) 157{ 158struct files_ref_store *refs = 159files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 160DIR*d; 161struct dirent *de; 162int dirnamelen =strlen(dirname); 163struct strbuf refname; 164struct strbuf path = STRBUF_INIT; 165size_t path_baselen; 166 167files_ref_path(refs, &path, dirname); 168 path_baselen = path.len; 169 170 d =opendir(path.buf); 171if(!d) { 172strbuf_release(&path); 173return; 174} 175 176strbuf_init(&refname, dirnamelen +257); 177strbuf_add(&refname, dirname, dirnamelen); 178 179while((de =readdir(d)) != NULL) { 180struct object_id oid; 181struct stat st; 182int flag; 183 184if(de->d_name[0] =='.') 185continue; 186if(ends_with(de->d_name,".lock")) 187continue; 188strbuf_addstr(&refname, de->d_name); 189strbuf_addstr(&path, de->d_name); 190if(stat(path.buf, &st) <0) { 191;/* silently ignore */ 192}else if(S_ISDIR(st.st_mode)) { 193strbuf_addch(&refname,'/'); 194add_entry_to_dir(dir, 195create_dir_entry(dir->cache, refname.buf, 196 refname.len,1)); 197}else{ 198if(!refs_resolve_ref_unsafe(&refs->base, 199 refname.buf, 200 RESOLVE_REF_READING, 201 oid.hash, &flag)) { 202oidclr(&oid); 203 flag |= REF_ISBROKEN; 204}else if(is_null_oid(&oid)) { 205/* 206 * It is so astronomically unlikely 207 * that NULL_SHA1 is the SHA-1 of an 208 * actual object that we consider its 209 * appearance in a loose reference 210 * file to be repo corruption 211 * (probably due to a software bug). 212 */ 213 flag |= REF_ISBROKEN; 214} 215 216if(check_refname_format(refname.buf, 217 REFNAME_ALLOW_ONELEVEL)) { 218if(!refname_is_safe(refname.buf)) 219die("loose refname is dangerous:%s", refname.buf); 220oidclr(&oid); 221 flag |= REF_BAD_NAME | REF_ISBROKEN; 222} 223add_entry_to_dir(dir, 224create_ref_entry(refname.buf, &oid, flag)); 225} 226strbuf_setlen(&refname, dirnamelen); 227strbuf_setlen(&path, path_baselen); 228} 229strbuf_release(&refname); 230strbuf_release(&path); 231closedir(d); 232 233/* 234 * Manually add refs/bisect, which, being per-worktree, might 235 * not appear in the directory listing for refs/ in the main 236 * repo. 237 */ 238if(!strcmp(dirname,"refs/")) { 239int pos =search_ref_dir(dir,"refs/bisect/",12); 240 241if(pos <0) { 242struct ref_entry *child_entry =create_dir_entry( 243 dir->cache,"refs/bisect/",12,1); 244add_entry_to_dir(dir, child_entry); 245} 246} 247} 248 249static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 250{ 251if(!refs->loose) { 252/* 253 * Mark the top-level directory complete because we 254 * are about to read the only subdirectory that can 255 * hold references: 256 */ 257 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 258 259/* We're going to fill the top level ourselves: */ 260 refs->loose->root->flag &= ~REF_INCOMPLETE; 261 262/* 263 * Add an incomplete entry for "refs/" (to be filled 264 * lazily): 265 */ 266add_entry_to_dir(get_ref_dir(refs->loose->root), 267create_dir_entry(refs->loose,"refs/",5,1)); 268} 269return refs->loose; 270} 271 272static intfiles_read_raw_ref(struct ref_store *ref_store, 273const char*refname,unsigned char*sha1, 274struct strbuf *referent,unsigned int*type) 275{ 276struct files_ref_store *refs = 277files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 278struct strbuf sb_contents = STRBUF_INIT; 279struct strbuf sb_path = STRBUF_INIT; 280const char*path; 281const char*buf; 282struct stat st; 283int fd; 284int ret = -1; 285int save_errno; 286int remaining_retries =3; 287 288*type =0; 289strbuf_reset(&sb_path); 290 291files_ref_path(refs, &sb_path, refname); 292 293 path = sb_path.buf; 294 295stat_ref: 296/* 297 * We might have to loop back here to avoid a race 298 * condition: first we lstat() the file, then we try 299 * to read it as a link or as a file. But if somebody 300 * changes the type of the file (file <-> directory 301 * <-> symlink) between the lstat() and reading, then 302 * we don't want to report that as an error but rather 303 * try again starting with the lstat(). 304 * 305 * We'll keep a count of the retries, though, just to avoid 306 * any confusing situation sending us into an infinite loop. 307 */ 308 309if(remaining_retries-- <=0) 310goto out; 311 312if(lstat(path, &st) <0) { 313if(errno != ENOENT) 314goto out; 315if(refs_read_raw_ref(refs->packed_ref_store, refname, 316 sha1, referent, type)) { 317 errno = ENOENT; 318goto out; 319} 320 ret =0; 321goto out; 322} 323 324/* Follow "normalized" - ie "refs/.." symlinks by hand */ 325if(S_ISLNK(st.st_mode)) { 326strbuf_reset(&sb_contents); 327if(strbuf_readlink(&sb_contents, path,0) <0) { 328if(errno == ENOENT || errno == EINVAL) 329/* inconsistent with lstat; retry */ 330goto stat_ref; 331else 332goto out; 333} 334if(starts_with(sb_contents.buf,"refs/") && 335!check_refname_format(sb_contents.buf,0)) { 336strbuf_swap(&sb_contents, referent); 337*type |= REF_ISSYMREF; 338 ret =0; 339goto out; 340} 341/* 342 * It doesn't look like a refname; fall through to just 343 * treating it like a non-symlink, and reading whatever it 344 * points to. 345 */ 346} 347 348/* Is it a directory? */ 349if(S_ISDIR(st.st_mode)) { 350/* 351 * Even though there is a directory where the loose 352 * ref is supposed to be, there could still be a 353 * packed ref: 354 */ 355if(refs_read_raw_ref(refs->packed_ref_store, refname, 356 sha1, referent, type)) { 357 errno = EISDIR; 358goto out; 359} 360 ret =0; 361goto out; 362} 363 364/* 365 * Anything else, just open it and try to use it as 366 * a ref 367 */ 368 fd =open(path, O_RDONLY); 369if(fd <0) { 370if(errno == ENOENT && !S_ISLNK(st.st_mode)) 371/* inconsistent with lstat; retry */ 372goto stat_ref; 373else 374goto out; 375} 376strbuf_reset(&sb_contents); 377if(strbuf_read(&sb_contents, fd,256) <0) { 378int save_errno = errno; 379close(fd); 380 errno = save_errno; 381goto out; 382} 383close(fd); 384strbuf_rtrim(&sb_contents); 385 buf = sb_contents.buf; 386if(starts_with(buf,"ref:")) { 387 buf +=4; 388while(isspace(*buf)) 389 buf++; 390 391strbuf_reset(referent); 392strbuf_addstr(referent, buf); 393*type |= REF_ISSYMREF; 394 ret =0; 395goto out; 396} 397 398/* 399 * Please note that FETCH_HEAD has additional 400 * data after the sha. 401 */ 402if(get_sha1_hex(buf, sha1) || 403(buf[40] !='\0'&& !isspace(buf[40]))) { 404*type |= REF_ISBROKEN; 405 errno = EINVAL; 406goto out; 407} 408 409 ret =0; 410 411out: 412 save_errno = errno; 413strbuf_release(&sb_path); 414strbuf_release(&sb_contents); 415 errno = save_errno; 416return ret; 417} 418 419static voidunlock_ref(struct ref_lock *lock) 420{ 421/* Do not free lock->lk -- atexit() still looks at them */ 422if(lock->lk) 423rollback_lock_file(lock->lk); 424free(lock->ref_name); 425free(lock); 426} 427 428/* 429 * Lock refname, without following symrefs, and set *lock_p to point 430 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 431 * and type similarly to read_raw_ref(). 432 * 433 * The caller must verify that refname is a "safe" reference name (in 434 * the sense of refname_is_safe()) before calling this function. 435 * 436 * If the reference doesn't already exist, verify that refname doesn't 437 * have a D/F conflict with any existing references. extras and skip 438 * are passed to refs_verify_refname_available() for this check. 439 * 440 * If mustexist is not set and the reference is not found or is 441 * broken, lock the reference anyway but clear sha1. 442 * 443 * Return 0 on success. On failure, write an error message to err and 444 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 445 * 446 * Implementation note: This function is basically 447 * 448 * lock reference 449 * read_raw_ref() 450 * 451 * but it includes a lot more code to 452 * - Deal with possible races with other processes 453 * - Avoid calling refs_verify_refname_available() when it can be 454 * avoided, namely if we were successfully able to read the ref 455 * - Generate informative error messages in the case of failure 456 */ 457static intlock_raw_ref(struct files_ref_store *refs, 458const char*refname,int mustexist, 459const struct string_list *extras, 460const struct string_list *skip, 461struct ref_lock **lock_p, 462struct strbuf *referent, 463unsigned int*type, 464struct strbuf *err) 465{ 466struct ref_lock *lock; 467struct strbuf ref_file = STRBUF_INIT; 468int attempts_remaining =3; 469int ret = TRANSACTION_GENERIC_ERROR; 470 471assert(err); 472files_assert_main_repository(refs,"lock_raw_ref"); 473 474*type =0; 475 476/* First lock the file so it can't change out from under us. */ 477 478*lock_p = lock =xcalloc(1,sizeof(*lock)); 479 480 lock->ref_name =xstrdup(refname); 481files_ref_path(refs, &ref_file, refname); 482 483retry: 484switch(safe_create_leading_directories(ref_file.buf)) { 485case SCLD_OK: 486break;/* success */ 487case SCLD_EXISTS: 488/* 489 * Suppose refname is "refs/foo/bar". We just failed 490 * to create the containing directory, "refs/foo", 491 * because there was a non-directory in the way. This 492 * indicates a D/F conflict, probably because of 493 * another reference such as "refs/foo". There is no 494 * reason to expect this error to be transitory. 495 */ 496if(refs_verify_refname_available(&refs->base, refname, 497 extras, skip, err)) { 498if(mustexist) { 499/* 500 * To the user the relevant error is 501 * that the "mustexist" reference is 502 * missing: 503 */ 504strbuf_reset(err); 505strbuf_addf(err,"unable to resolve reference '%s'", 506 refname); 507}else{ 508/* 509 * The error message set by 510 * refs_verify_refname_available() is 511 * OK. 512 */ 513 ret = TRANSACTION_NAME_CONFLICT; 514} 515}else{ 516/* 517 * The file that is in the way isn't a loose 518 * reference. Report it as a low-level 519 * failure. 520 */ 521strbuf_addf(err,"unable to create lock file%s.lock; " 522"non-directory in the way", 523 ref_file.buf); 524} 525goto error_return; 526case SCLD_VANISHED: 527/* Maybe another process was tidying up. Try again. */ 528if(--attempts_remaining >0) 529goto retry; 530/* fall through */ 531default: 532strbuf_addf(err,"unable to create directory for%s", 533 ref_file.buf); 534goto error_return; 535} 536 537if(!lock->lk) 538 lock->lk =xcalloc(1,sizeof(struct lock_file)); 539 540if(hold_lock_file_for_update_timeout( 541 lock->lk, ref_file.buf, LOCK_NO_DEREF, 542get_files_ref_lock_timeout_ms()) <0) { 543if(errno == ENOENT && --attempts_remaining >0) { 544/* 545 * Maybe somebody just deleted one of the 546 * directories leading to ref_file. Try 547 * again: 548 */ 549goto retry; 550}else{ 551unable_to_lock_message(ref_file.buf, errno, err); 552goto error_return; 553} 554} 555 556/* 557 * Now we hold the lock and can read the reference without 558 * fear that its value will change. 559 */ 560 561if(files_read_raw_ref(&refs->base, refname, 562 lock->old_oid.hash, referent, type)) { 563if(errno == ENOENT) { 564if(mustexist) { 565/* Garden variety missing reference. */ 566strbuf_addf(err,"unable to resolve reference '%s'", 567 refname); 568goto error_return; 569}else{ 570/* 571 * Reference is missing, but that's OK. We 572 * know that there is not a conflict with 573 * another loose reference because 574 * (supposing that we are trying to lock 575 * reference "refs/foo/bar"): 576 * 577 * - We were successfully able to create 578 * the lockfile refs/foo/bar.lock, so we 579 * know there cannot be a loose reference 580 * named "refs/foo". 581 * 582 * - We got ENOENT and not EISDIR, so we 583 * know that there cannot be a loose 584 * reference named "refs/foo/bar/baz". 585 */ 586} 587}else if(errno == EISDIR) { 588/* 589 * There is a directory in the way. It might have 590 * contained references that have been deleted. If 591 * we don't require that the reference already 592 * exists, try to remove the directory so that it 593 * doesn't cause trouble when we want to rename the 594 * lockfile into place later. 595 */ 596if(mustexist) { 597/* Garden variety missing reference. */ 598strbuf_addf(err,"unable to resolve reference '%s'", 599 refname); 600goto error_return; 601}else if(remove_dir_recursively(&ref_file, 602 REMOVE_DIR_EMPTY_ONLY)) { 603if(refs_verify_refname_available( 604&refs->base, refname, 605 extras, skip, err)) { 606/* 607 * The error message set by 608 * verify_refname_available() is OK. 609 */ 610 ret = TRANSACTION_NAME_CONFLICT; 611goto error_return; 612}else{ 613/* 614 * We can't delete the directory, 615 * but we also don't know of any 616 * references that it should 617 * contain. 618 */ 619strbuf_addf(err,"there is a non-empty directory '%s' " 620"blocking reference '%s'", 621 ref_file.buf, refname); 622goto error_return; 623} 624} 625}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 626strbuf_addf(err,"unable to resolve reference '%s': " 627"reference broken", refname); 628goto error_return; 629}else{ 630strbuf_addf(err,"unable to resolve reference '%s':%s", 631 refname,strerror(errno)); 632goto error_return; 633} 634 635/* 636 * If the ref did not exist and we are creating it, 637 * make sure there is no existing packed ref that 638 * conflicts with refname: 639 */ 640if(refs_verify_refname_available( 641 refs->packed_ref_store, refname, 642 extras, skip, err)) 643goto error_return; 644} 645 646 ret =0; 647goto out; 648 649error_return: 650unlock_ref(lock); 651*lock_p = NULL; 652 653out: 654strbuf_release(&ref_file); 655return ret; 656} 657 658struct files_ref_iterator { 659struct ref_iterator base; 660 661struct ref_iterator *iter0; 662unsigned int flags; 663}; 664 665static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 666{ 667struct files_ref_iterator *iter = 668(struct files_ref_iterator *)ref_iterator; 669int ok; 670 671while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 672if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 673ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 674continue; 675 676if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 677!ref_resolves_to_object(iter->iter0->refname, 678 iter->iter0->oid, 679 iter->iter0->flags)) 680continue; 681 682 iter->base.refname = iter->iter0->refname; 683 iter->base.oid = iter->iter0->oid; 684 iter->base.flags = iter->iter0->flags; 685return ITER_OK; 686} 687 688 iter->iter0 = NULL; 689if(ref_iterator_abort(ref_iterator) != ITER_DONE) 690 ok = ITER_ERROR; 691 692return ok; 693} 694 695static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 696struct object_id *peeled) 697{ 698struct files_ref_iterator *iter = 699(struct files_ref_iterator *)ref_iterator; 700 701returnref_iterator_peel(iter->iter0, peeled); 702} 703 704static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 705{ 706struct files_ref_iterator *iter = 707(struct files_ref_iterator *)ref_iterator; 708int ok = ITER_DONE; 709 710if(iter->iter0) 711 ok =ref_iterator_abort(iter->iter0); 712 713base_ref_iterator_free(ref_iterator); 714return ok; 715} 716 717static struct ref_iterator_vtable files_ref_iterator_vtable = { 718 files_ref_iterator_advance, 719 files_ref_iterator_peel, 720 files_ref_iterator_abort 721}; 722 723static struct ref_iterator *files_ref_iterator_begin( 724struct ref_store *ref_store, 725const char*prefix,unsigned int flags) 726{ 727struct files_ref_store *refs; 728struct ref_iterator *loose_iter, *packed_iter, *overlay_iter; 729struct files_ref_iterator *iter; 730struct ref_iterator *ref_iterator; 731unsigned int required_flags = REF_STORE_READ; 732 733if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 734 required_flags |= REF_STORE_ODB; 735 736 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 737 738/* 739 * We must make sure that all loose refs are read before 740 * accessing the packed-refs file; this avoids a race 741 * condition if loose refs are migrated to the packed-refs 742 * file by a simultaneous process, but our in-memory view is 743 * from before the migration. We ensure this as follows: 744 * First, we call start the loose refs iteration with its 745 * `prime_ref` argument set to true. This causes the loose 746 * references in the subtree to be pre-read into the cache. 747 * (If they've already been read, that's OK; we only need to 748 * guarantee that they're read before the packed refs, not 749 * *how much* before.) After that, we call 750 * packed_ref_iterator_begin(), which internally checks 751 * whether the packed-ref cache is up to date with what is on 752 * disk, and re-reads it if not. 753 */ 754 755 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 756 prefix,1); 757 758/* 759 * The packed-refs file might contain broken references, for 760 * example an old version of a reference that points at an 761 * object that has since been garbage-collected. This is OK as 762 * long as there is a corresponding loose reference that 763 * overrides it, and we don't want to emit an error message in 764 * this case. So ask the packed_ref_store for all of its 765 * references, and (if needed) do our own check for broken 766 * ones in files_ref_iterator_advance(), after we have merged 767 * the packed and loose references. 768 */ 769 packed_iter =refs_ref_iterator_begin( 770 refs->packed_ref_store, prefix,0, 771 DO_FOR_EACH_INCLUDE_BROKEN); 772 773 overlay_iter =overlay_ref_iterator_begin(loose_iter, packed_iter); 774 775 iter =xcalloc(1,sizeof(*iter)); 776 ref_iterator = &iter->base; 777base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable, 778 overlay_iter->ordered); 779 iter->iter0 = overlay_iter; 780 iter->flags = flags; 781 782return ref_iterator; 783} 784 785/* 786 * Verify that the reference locked by lock has the value old_sha1. 787 * Fail if the reference doesn't exist and mustexist is set. Return 0 788 * on success. On error, write an error message to err, set errno, and 789 * return a negative value. 790 */ 791static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 792const unsigned char*old_sha1,int mustexist, 793struct strbuf *err) 794{ 795assert(err); 796 797if(refs_read_ref_full(ref_store, lock->ref_name, 798 mustexist ? RESOLVE_REF_READING :0, 799 lock->old_oid.hash, NULL)) { 800if(old_sha1) { 801int save_errno = errno; 802strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 803 errno = save_errno; 804return-1; 805}else{ 806oidclr(&lock->old_oid); 807return0; 808} 809} 810if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 811strbuf_addf(err,"ref '%s' is at%sbut expected%s", 812 lock->ref_name, 813oid_to_hex(&lock->old_oid), 814sha1_to_hex(old_sha1)); 815 errno = EBUSY; 816return-1; 817} 818return0; 819} 820 821static intremove_empty_directories(struct strbuf *path) 822{ 823/* 824 * we want to create a file but there is a directory there; 825 * if that is an empty directory (or a directory that contains 826 * only empty directories), remove them. 827 */ 828returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 829} 830 831static intcreate_reflock(const char*path,void*cb) 832{ 833struct lock_file *lk = cb; 834 835returnhold_lock_file_for_update_timeout( 836 lk, path, LOCK_NO_DEREF, 837get_files_ref_lock_timeout_ms()) <0? -1:0; 838} 839 840/* 841 * Locks a ref returning the lock on success and NULL on failure. 842 * On failure errno is set to something meaningful. 843 */ 844static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 845const char*refname, 846const unsigned char*old_sha1, 847const struct string_list *extras, 848const struct string_list *skip, 849unsigned int flags,int*type, 850struct strbuf *err) 851{ 852struct strbuf ref_file = STRBUF_INIT; 853struct ref_lock *lock; 854int last_errno =0; 855int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 856int resolve_flags = RESOLVE_REF_NO_RECURSE; 857int resolved; 858 859files_assert_main_repository(refs,"lock_ref_sha1_basic"); 860assert(err); 861 862 lock =xcalloc(1,sizeof(struct ref_lock)); 863 864if(mustexist) 865 resolve_flags |= RESOLVE_REF_READING; 866if(flags & REF_DELETING) 867 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 868 869files_ref_path(refs, &ref_file, refname); 870 resolved = !!refs_resolve_ref_unsafe(&refs->base, 871 refname, resolve_flags, 872 lock->old_oid.hash, type); 873if(!resolved && errno == EISDIR) { 874/* 875 * we are trying to lock foo but we used to 876 * have foo/bar which now does not exist; 877 * it is normal for the empty directory 'foo' 878 * to remain. 879 */ 880if(remove_empty_directories(&ref_file)) { 881 last_errno = errno; 882if(!refs_verify_refname_available( 883&refs->base, 884 refname, extras, skip, err)) 885strbuf_addf(err,"there are still refs under '%s'", 886 refname); 887goto error_return; 888} 889 resolved = !!refs_resolve_ref_unsafe(&refs->base, 890 refname, resolve_flags, 891 lock->old_oid.hash, type); 892} 893if(!resolved) { 894 last_errno = errno; 895if(last_errno != ENOTDIR || 896!refs_verify_refname_available(&refs->base, refname, 897 extras, skip, err)) 898strbuf_addf(err,"unable to resolve reference '%s':%s", 899 refname,strerror(last_errno)); 900 901goto error_return; 902} 903 904/* 905 * If the ref did not exist and we are creating it, make sure 906 * there is no existing packed ref whose name begins with our 907 * refname, nor a packed ref whose name is a proper prefix of 908 * our refname. 909 */ 910if(is_null_oid(&lock->old_oid) && 911refs_verify_refname_available(refs->packed_ref_store, refname, 912 extras, skip, err)) { 913 last_errno = ENOTDIR; 914goto error_return; 915} 916 917 lock->lk =xcalloc(1,sizeof(struct lock_file)); 918 919 lock->ref_name =xstrdup(refname); 920 921if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 922 last_errno = errno; 923unable_to_lock_message(ref_file.buf, errno, err); 924goto error_return; 925} 926 927if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 928 last_errno = errno; 929goto error_return; 930} 931goto out; 932 933 error_return: 934unlock_ref(lock); 935 lock = NULL; 936 937 out: 938strbuf_release(&ref_file); 939 errno = last_errno; 940return lock; 941} 942 943struct ref_to_prune { 944struct ref_to_prune *next; 945unsigned char sha1[20]; 946char name[FLEX_ARRAY]; 947}; 948 949enum{ 950 REMOVE_EMPTY_PARENTS_REF =0x01, 951 REMOVE_EMPTY_PARENTS_REFLOG =0x02 952}; 953 954/* 955 * Remove empty parent directories associated with the specified 956 * reference and/or its reflog, but spare [logs/]refs/ and immediate 957 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 958 * REMOVE_EMPTY_PARENTS_REFLOG. 959 */ 960static voidtry_remove_empty_parents(struct files_ref_store *refs, 961const char*refname, 962unsigned int flags) 963{ 964struct strbuf buf = STRBUF_INIT; 965struct strbuf sb = STRBUF_INIT; 966char*p, *q; 967int i; 968 969strbuf_addstr(&buf, refname); 970 p = buf.buf; 971for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */ 972while(*p && *p !='/') 973 p++; 974/* tolerate duplicate slashes; see check_refname_format() */ 975while(*p =='/') 976 p++; 977} 978 q = buf.buf + buf.len; 979while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) { 980while(q > p && *q !='/') 981 q--; 982while(q > p && *(q-1) =='/') 983 q--; 984if(q == p) 985break; 986strbuf_setlen(&buf, q - buf.buf); 987 988strbuf_reset(&sb); 989files_ref_path(refs, &sb, buf.buf); 990if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf)) 991 flags &= ~REMOVE_EMPTY_PARENTS_REF; 992 993strbuf_reset(&sb); 994files_reflog_path(refs, &sb, buf.buf); 995if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf)) 996 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG; 997} 998strbuf_release(&buf); 999strbuf_release(&sb);1000}10011002/* make sure nobody touched the ref, and unlink */1003static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1004{1005struct ref_transaction *transaction;1006struct strbuf err = STRBUF_INIT;10071008if(check_refname_format(r->name,0))1009return;10101011 transaction =ref_store_transaction_begin(&refs->base, &err);1012if(!transaction ||1013ref_transaction_delete(transaction, r->name, r->sha1,1014 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1015ref_transaction_commit(transaction, &err)) {1016ref_transaction_free(transaction);1017error("%s", err.buf);1018strbuf_release(&err);1019return;1020}1021ref_transaction_free(transaction);1022strbuf_release(&err);1023}10241025/*1026 * Prune the loose versions of the references in the linked list1027 * `*refs_to_prune`, freeing the entries in the list as we go.1028 */1029static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune **refs_to_prune)1030{1031while(*refs_to_prune) {1032struct ref_to_prune *r = *refs_to_prune;1033*refs_to_prune = r->next;1034prune_ref(refs, r);1035free(r);1036}1037}10381039/*1040 * Return true if the specified reference should be packed.1041 */1042static intshould_pack_ref(const char*refname,1043const struct object_id *oid,unsigned int ref_flags,1044unsigned int pack_flags)1045{1046/* Do not pack per-worktree refs: */1047if(ref_type(refname) != REF_TYPE_NORMAL)1048return0;10491050/* Do not pack non-tags unless PACK_REFS_ALL is set: */1051if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1052return0;10531054/* Do not pack symbolic refs: */1055if(ref_flags & REF_ISSYMREF)1056return0;10571058/* Do not pack broken refs: */1059if(!ref_resolves_to_object(refname, oid, ref_flags))1060return0;10611062return1;1063}10641065static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1066{1067struct files_ref_store *refs =1068files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1069"pack_refs");1070struct ref_iterator *iter;1071int ok;1072struct ref_to_prune *refs_to_prune = NULL;1073struct strbuf err = STRBUF_INIT;1074struct ref_transaction *transaction;10751076 transaction =ref_store_transaction_begin(refs->packed_ref_store, &err);1077if(!transaction)1078return-1;10791080packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);10811082 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1083while((ok =ref_iterator_advance(iter)) == ITER_OK) {1084/*1085 * If the loose reference can be packed, add an entry1086 * in the packed ref cache. If the reference should be1087 * pruned, also add it to refs_to_prune.1088 */1089if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1090 flags))1091continue;10921093/*1094 * Add a reference creation for this reference to the1095 * packed-refs transaction:1096 */1097if(ref_transaction_update(transaction, iter->refname,1098 iter->oid->hash, NULL,1099 REF_NODEREF, NULL, &err))1100die("failure preparing to create packed reference%s:%s",1101 iter->refname, err.buf);11021103/* Schedule the loose reference for pruning if requested. */1104if((flags & PACK_REFS_PRUNE)) {1105struct ref_to_prune *n;1106FLEX_ALLOC_STR(n, name, iter->refname);1107hashcpy(n->sha1, iter->oid->hash);1108 n->next = refs_to_prune;1109 refs_to_prune = n;1110}1111}1112if(ok != ITER_DONE)1113die("error while iterating over references");11141115if(ref_transaction_commit(transaction, &err))1116die("unable to write new packed-refs:%s", err.buf);11171118ref_transaction_free(transaction);11191120packed_refs_unlock(refs->packed_ref_store);11211122prune_refs(refs, &refs_to_prune);1123strbuf_release(&err);1124return0;1125}11261127static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1128struct string_list *refnames,unsigned int flags)1129{1130struct files_ref_store *refs =1131files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1132struct strbuf err = STRBUF_INIT;1133int i, result =0;11341135if(!refnames->nr)1136return0;11371138if(packed_refs_lock(refs->packed_ref_store,0, &err))1139goto error;11401141if(refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {1142packed_refs_unlock(refs->packed_ref_store);1143goto error;1144}11451146packed_refs_unlock(refs->packed_ref_store);11471148for(i =0; i < refnames->nr; i++) {1149const char*refname = refnames->items[i].string;11501151if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1152 result |=error(_("could not remove reference%s"), refname);1153}11541155strbuf_release(&err);1156return result;11571158error:1159/*1160 * If we failed to rewrite the packed-refs file, then it is1161 * unsafe to try to remove loose refs, because doing so might1162 * expose an obsolete packed value for a reference that might1163 * even point at an object that has been garbage collected.1164 */1165if(refnames->nr ==1)1166error(_("could not delete reference%s:%s"),1167 refnames->items[0].string, err.buf);1168else1169error(_("could not delete references:%s"), err.buf);11701171strbuf_release(&err);1172return-1;1173}11741175/*1176 * People using contrib's git-new-workdir have .git/logs/refs ->1177 * /some/other/path/.git/logs/refs, and that may live on another device.1178 *1179 * IOW, to avoid cross device rename errors, the temporary renamed log must1180 * live into logs/refs.1181 */1182#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11831184struct rename_cb {1185const char*tmp_renamed_log;1186int true_errno;1187};11881189static intrename_tmp_log_callback(const char*path,void*cb_data)1190{1191struct rename_cb *cb = cb_data;11921193if(rename(cb->tmp_renamed_log, path)) {1194/*1195 * rename(a, b) when b is an existing directory ought1196 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1197 * Sheesh. Record the true errno for error reporting,1198 * but report EISDIR to raceproof_create_file() so1199 * that it knows to retry.1200 */1201 cb->true_errno = errno;1202if(errno == ENOTDIR)1203 errno = EISDIR;1204return-1;1205}else{1206return0;1207}1208}12091210static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1211{1212struct strbuf path = STRBUF_INIT;1213struct strbuf tmp = STRBUF_INIT;1214struct rename_cb cb;1215int ret;12161217files_reflog_path(refs, &path, newrefname);1218files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1219 cb.tmp_renamed_log = tmp.buf;1220 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1221if(ret) {1222if(errno == EISDIR)1223error("directory not empty:%s", path.buf);1224else1225error("unable to move logfile%sto%s:%s",1226 tmp.buf, path.buf,1227strerror(cb.true_errno));1228}12291230strbuf_release(&path);1231strbuf_release(&tmp);1232return ret;1233}12341235static intwrite_ref_to_lockfile(struct ref_lock *lock,1236const struct object_id *oid,struct strbuf *err);1237static intcommit_ref_update(struct files_ref_store *refs,1238struct ref_lock *lock,1239const struct object_id *oid,const char*logmsg,1240struct strbuf *err);12411242static intfiles_rename_ref(struct ref_store *ref_store,1243const char*oldrefname,const char*newrefname,1244const char*logmsg)1245{1246struct files_ref_store *refs =1247files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1248struct object_id oid, orig_oid;1249int flag =0, logmoved =0;1250struct ref_lock *lock;1251struct stat loginfo;1252struct strbuf sb_oldref = STRBUF_INIT;1253struct strbuf sb_newref = STRBUF_INIT;1254struct strbuf tmp_renamed_log = STRBUF_INIT;1255int log, ret;1256struct strbuf err = STRBUF_INIT;12571258files_reflog_path(refs, &sb_oldref, oldrefname);1259files_reflog_path(refs, &sb_newref, newrefname);1260files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12611262 log = !lstat(sb_oldref.buf, &loginfo);1263if(log &&S_ISLNK(loginfo.st_mode)) {1264 ret =error("reflog for%sis a symlink", oldrefname);1265goto out;1266}12671268if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1269 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1270 orig_oid.hash, &flag)) {1271 ret =error("refname%snot found", oldrefname);1272goto out;1273}12741275if(flag & REF_ISSYMREF) {1276 ret =error("refname%sis a symbolic ref, renaming it is not supported",1277 oldrefname);1278goto out;1279}1280if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1281 ret =1;1282goto out;1283}12841285if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1286 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1287 oldrefname,strerror(errno));1288goto out;1289}12901291if(refs_delete_ref(&refs->base, logmsg, oldrefname,1292 orig_oid.hash, REF_NODEREF)) {1293error("unable to delete old%s", oldrefname);1294goto rollback;1295}12961297/*1298 * Since we are doing a shallow lookup, oid is not the1299 * correct value to pass to delete_ref as old_oid. But that1300 * doesn't matter, because an old_oid check wouldn't add to1301 * the safety anyway; we want to delete the reference whatever1302 * its current value.1303 */1304if(!refs_read_ref_full(&refs->base, newrefname,1305 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1306 oid.hash, NULL) &&1307refs_delete_ref(&refs->base, NULL, newrefname,1308 NULL, REF_NODEREF)) {1309if(errno == EISDIR) {1310struct strbuf path = STRBUF_INIT;1311int result;13121313files_ref_path(refs, &path, newrefname);1314 result =remove_empty_directories(&path);1315strbuf_release(&path);13161317if(result) {1318error("Directory not empty:%s", newrefname);1319goto rollback;1320}1321}else{1322error("unable to delete existing%s", newrefname);1323goto rollback;1324}1325}13261327if(log &&rename_tmp_log(refs, newrefname))1328goto rollback;13291330 logmoved = log;13311332 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1333 REF_NODEREF, NULL, &err);1334if(!lock) {1335error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1336strbuf_release(&err);1337goto rollback;1338}1339oidcpy(&lock->old_oid, &orig_oid);13401341if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1342commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1343error("unable to write current sha1 into%s:%s", newrefname, err.buf);1344strbuf_release(&err);1345goto rollback;1346}13471348 ret =0;1349goto out;13501351 rollback:1352 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1353 REF_NODEREF, NULL, &err);1354if(!lock) {1355error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1356strbuf_release(&err);1357goto rollbacklog;1358}13591360 flag = log_all_ref_updates;1361 log_all_ref_updates = LOG_REFS_NONE;1362if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1363commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1364error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1365strbuf_release(&err);1366}1367 log_all_ref_updates = flag;13681369 rollbacklog:1370if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1371error("unable to restore logfile%sfrom%s:%s",1372 oldrefname, newrefname,strerror(errno));1373if(!logmoved && log &&1374rename(tmp_renamed_log.buf, sb_oldref.buf))1375error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1376 oldrefname,strerror(errno));1377 ret =1;1378 out:1379strbuf_release(&sb_newref);1380strbuf_release(&sb_oldref);1381strbuf_release(&tmp_renamed_log);13821383return ret;1384}13851386static intclose_ref(struct ref_lock *lock)1387{1388if(close_lock_file(lock->lk))1389return-1;1390return0;1391}13921393static intcommit_ref(struct ref_lock *lock)1394{1395char*path =get_locked_file_path(lock->lk);1396struct stat st;13971398if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1399/*1400 * There is a directory at the path we want to rename1401 * the lockfile to. Hopefully it is empty; try to1402 * delete it.1403 */1404size_t len =strlen(path);1405struct strbuf sb_path = STRBUF_INIT;14061407strbuf_attach(&sb_path, path, len, len);14081409/*1410 * If this fails, commit_lock_file() will also fail1411 * and will report the problem.1412 */1413remove_empty_directories(&sb_path);1414strbuf_release(&sb_path);1415}else{1416free(path);1417}14181419if(commit_lock_file(lock->lk))1420return-1;1421return0;1422}14231424static intopen_or_create_logfile(const char*path,void*cb)1425{1426int*fd = cb;14271428*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1429return(*fd <0) ? -1:0;1430}14311432/*1433 * Create a reflog for a ref. If force_create = 0, only create the1434 * reflog for certain refs (those for which should_autocreate_reflog1435 * returns non-zero). Otherwise, create it regardless of the reference1436 * name. If the logfile already existed or was created, return 0 and1437 * set *logfd to the file descriptor opened for appending to the file.1438 * If no logfile exists and we decided not to create one, return 0 and1439 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1440 * return -1.1441 */1442static intlog_ref_setup(struct files_ref_store *refs,1443const char*refname,int force_create,1444int*logfd,struct strbuf *err)1445{1446struct strbuf logfile_sb = STRBUF_INIT;1447char*logfile;14481449files_reflog_path(refs, &logfile_sb, refname);1450 logfile =strbuf_detach(&logfile_sb, NULL);14511452if(force_create ||should_autocreate_reflog(refname)) {1453if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1454if(errno == ENOENT)1455strbuf_addf(err,"unable to create directory for '%s': "1456"%s", logfile,strerror(errno));1457else if(errno == EISDIR)1458strbuf_addf(err,"there are still logs under '%s'",1459 logfile);1460else1461strbuf_addf(err,"unable to append to '%s':%s",1462 logfile,strerror(errno));14631464goto error;1465}1466}else{1467*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1468if(*logfd <0) {1469if(errno == ENOENT || errno == EISDIR) {1470/*1471 * The logfile doesn't already exist,1472 * but that is not an error; it only1473 * means that we won't write log1474 * entries to it.1475 */1476;1477}else{1478strbuf_addf(err,"unable to append to '%s':%s",1479 logfile,strerror(errno));1480goto error;1481}1482}1483}14841485if(*logfd >=0)1486adjust_shared_perm(logfile);14871488free(logfile);1489return0;14901491error:1492free(logfile);1493return-1;1494}14951496static intfiles_create_reflog(struct ref_store *ref_store,1497const char*refname,int force_create,1498struct strbuf *err)1499{1500struct files_ref_store *refs =1501files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1502int fd;15031504if(log_ref_setup(refs, refname, force_create, &fd, err))1505return-1;15061507if(fd >=0)1508close(fd);15091510return0;1511}15121513static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1514const struct object_id *new_oid,1515const char*committer,const char*msg)1516{1517int msglen, written;1518unsigned maxlen, len;1519char*logrec;15201521 msglen = msg ?strlen(msg) :0;1522 maxlen =strlen(committer) + msglen +100;1523 logrec =xmalloc(maxlen);1524 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1525oid_to_hex(old_oid),1526oid_to_hex(new_oid),1527 committer);1528if(msglen)1529 len +=copy_reflog_msg(logrec + len -1, msg) -1;15301531 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1532free(logrec);1533if(written != len)1534return-1;15351536return0;1537}15381539static intfiles_log_ref_write(struct files_ref_store *refs,1540const char*refname,const struct object_id *old_oid,1541const struct object_id *new_oid,const char*msg,1542int flags,struct strbuf *err)1543{1544int logfd, result;15451546if(log_all_ref_updates == LOG_REFS_UNSET)1547 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15481549 result =log_ref_setup(refs, refname,1550 flags & REF_FORCE_CREATE_REFLOG,1551&logfd, err);15521553if(result)1554return result;15551556if(logfd <0)1557return0;1558 result =log_ref_write_fd(logfd, old_oid, new_oid,1559git_committer_info(0), msg);1560if(result) {1561struct strbuf sb = STRBUF_INIT;1562int save_errno = errno;15631564files_reflog_path(refs, &sb, refname);1565strbuf_addf(err,"unable to append to '%s':%s",1566 sb.buf,strerror(save_errno));1567strbuf_release(&sb);1568close(logfd);1569return-1;1570}1571if(close(logfd)) {1572struct strbuf sb = STRBUF_INIT;1573int save_errno = errno;15741575files_reflog_path(refs, &sb, refname);1576strbuf_addf(err,"unable to append to '%s':%s",1577 sb.buf,strerror(save_errno));1578strbuf_release(&sb);1579return-1;1580}1581return0;1582}15831584/*1585 * Write sha1 into the open lockfile, then close the lockfile. On1586 * errors, rollback the lockfile, fill in *err and1587 * return -1.1588 */1589static intwrite_ref_to_lockfile(struct ref_lock *lock,1590const struct object_id *oid,struct strbuf *err)1591{1592static char term ='\n';1593struct object *o;1594int fd;15951596 o =parse_object(oid);1597if(!o) {1598strbuf_addf(err,1599"trying to write ref '%s' with nonexistent object%s",1600 lock->ref_name,oid_to_hex(oid));1601unlock_ref(lock);1602return-1;1603}1604if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1605strbuf_addf(err,1606"trying to write non-commit object%sto branch '%s'",1607oid_to_hex(oid), lock->ref_name);1608unlock_ref(lock);1609return-1;1610}1611 fd =get_lock_file_fd(lock->lk);1612if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1613write_in_full(fd, &term,1) !=1||1614close_ref(lock) <0) {1615strbuf_addf(err,1616"couldn't write '%s'",get_lock_file_path(lock->lk));1617unlock_ref(lock);1618return-1;1619}1620return0;1621}16221623/*1624 * Commit a change to a loose reference that has already been written1625 * to the loose reference lockfile. Also update the reflogs if1626 * necessary, using the specified lockmsg (which can be NULL).1627 */1628static intcommit_ref_update(struct files_ref_store *refs,1629struct ref_lock *lock,1630const struct object_id *oid,const char*logmsg,1631struct strbuf *err)1632{1633files_assert_main_repository(refs,"commit_ref_update");16341635clear_loose_ref_cache(refs);1636if(files_log_ref_write(refs, lock->ref_name,1637&lock->old_oid, oid,1638 logmsg,0, err)) {1639char*old_msg =strbuf_detach(err, NULL);1640strbuf_addf(err,"cannot update the ref '%s':%s",1641 lock->ref_name, old_msg);1642free(old_msg);1643unlock_ref(lock);1644return-1;1645}16461647if(strcmp(lock->ref_name,"HEAD") !=0) {1648/*1649 * Special hack: If a branch is updated directly and HEAD1650 * points to it (may happen on the remote side of a push1651 * for example) then logically the HEAD reflog should be1652 * updated too.1653 * A generic solution implies reverse symref information,1654 * but finding all symrefs pointing to the given branch1655 * would be rather costly for this rare event (the direct1656 * update of a branch) to be worth it. So let's cheat and1657 * check with HEAD only which should cover 99% of all usage1658 * scenarios (even 100% of the default ones).1659 */1660struct object_id head_oid;1661int head_flag;1662const char*head_ref;16631664 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1665 RESOLVE_REF_READING,1666 head_oid.hash, &head_flag);1667if(head_ref && (head_flag & REF_ISSYMREF) &&1668!strcmp(head_ref, lock->ref_name)) {1669struct strbuf log_err = STRBUF_INIT;1670if(files_log_ref_write(refs,"HEAD",1671&lock->old_oid, oid,1672 logmsg,0, &log_err)) {1673error("%s", log_err.buf);1674strbuf_release(&log_err);1675}1676}1677}16781679if(commit_ref(lock)) {1680strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1681unlock_ref(lock);1682return-1;1683}16841685unlock_ref(lock);1686return0;1687}16881689static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1690{1691int ret = -1;1692#ifndef NO_SYMLINK_HEAD1693char*ref_path =get_locked_file_path(lock->lk);1694unlink(ref_path);1695 ret =symlink(target, ref_path);1696free(ref_path);16971698if(ret)1699fprintf(stderr,"no symlink - falling back to symbolic ref\n");1700#endif1701return ret;1702}17031704static voidupdate_symref_reflog(struct files_ref_store *refs,1705struct ref_lock *lock,const char*refname,1706const char*target,const char*logmsg)1707{1708struct strbuf err = STRBUF_INIT;1709struct object_id new_oid;1710if(logmsg &&1711!refs_read_ref_full(&refs->base, target,1712 RESOLVE_REF_READING, new_oid.hash, NULL) &&1713files_log_ref_write(refs, refname, &lock->old_oid,1714&new_oid, logmsg,0, &err)) {1715error("%s", err.buf);1716strbuf_release(&err);1717}1718}17191720static intcreate_symref_locked(struct files_ref_store *refs,1721struct ref_lock *lock,const char*refname,1722const char*target,const char*logmsg)1723{1724if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1725update_symref_reflog(refs, lock, refname, target, logmsg);1726return0;1727}17281729if(!fdopen_lock_file(lock->lk,"w"))1730returnerror("unable to fdopen%s:%s",1731 lock->lk->tempfile.filename.buf,strerror(errno));17321733update_symref_reflog(refs, lock, refname, target, logmsg);17341735/* no error check; commit_ref will check ferror */1736fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1737if(commit_ref(lock) <0)1738returnerror("unable to write symref for%s:%s", refname,1739strerror(errno));1740return0;1741}17421743static intfiles_create_symref(struct ref_store *ref_store,1744const char*refname,const char*target,1745const char*logmsg)1746{1747struct files_ref_store *refs =1748files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1749struct strbuf err = STRBUF_INIT;1750struct ref_lock *lock;1751int ret;17521753 lock =lock_ref_sha1_basic(refs, refname, NULL,1754 NULL, NULL, REF_NODEREF, NULL,1755&err);1756if(!lock) {1757error("%s", err.buf);1758strbuf_release(&err);1759return-1;1760}17611762 ret =create_symref_locked(refs, lock, refname, target, logmsg);1763unlock_ref(lock);1764return ret;1765}17661767static intfiles_reflog_exists(struct ref_store *ref_store,1768const char*refname)1769{1770struct files_ref_store *refs =1771files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1772struct strbuf sb = STRBUF_INIT;1773struct stat st;1774int ret;17751776files_reflog_path(refs, &sb, refname);1777 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1778strbuf_release(&sb);1779return ret;1780}17811782static intfiles_delete_reflog(struct ref_store *ref_store,1783const char*refname)1784{1785struct files_ref_store *refs =1786files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1787struct strbuf sb = STRBUF_INIT;1788int ret;17891790files_reflog_path(refs, &sb, refname);1791 ret =remove_path(sb.buf);1792strbuf_release(&sb);1793return ret;1794}17951796static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1797{1798struct object_id ooid, noid;1799char*email_end, *message;1800 timestamp_t timestamp;1801int tz;1802const char*p = sb->buf;18031804/* old SP new SP name <email> SP time TAB msg LF */1805if(!sb->len || sb->buf[sb->len -1] !='\n'||1806parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1807parse_oid_hex(p, &noid, &p) || *p++ !=' '||1808!(email_end =strchr(p,'>')) ||1809 email_end[1] !=' '||1810!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1811!message || message[0] !=' '||1812(message[1] !='+'&& message[1] !='-') ||1813!isdigit(message[2]) || !isdigit(message[3]) ||1814!isdigit(message[4]) || !isdigit(message[5]))1815return0;/* corrupt? */1816 email_end[1] ='\0';1817 tz =strtol(message +1, NULL,10);1818if(message[6] !='\t')1819 message +=6;1820else1821 message +=7;1822returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1823}18241825static char*find_beginning_of_line(char*bob,char*scan)1826{1827while(bob < scan && *(--scan) !='\n')1828;/* keep scanning backwards */1829/*1830 * Return either beginning of the buffer, or LF at the end of1831 * the previous line.1832 */1833return scan;1834}18351836static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1837const char*refname,1838 each_reflog_ent_fn fn,1839void*cb_data)1840{1841struct files_ref_store *refs =1842files_downcast(ref_store, REF_STORE_READ,1843"for_each_reflog_ent_reverse");1844struct strbuf sb = STRBUF_INIT;1845FILE*logfp;1846long pos;1847int ret =0, at_tail =1;18481849files_reflog_path(refs, &sb, refname);1850 logfp =fopen(sb.buf,"r");1851strbuf_release(&sb);1852if(!logfp)1853return-1;18541855/* Jump to the end */1856if(fseek(logfp,0, SEEK_END) <0)1857 ret =error("cannot seek back reflog for%s:%s",1858 refname,strerror(errno));1859 pos =ftell(logfp);1860while(!ret &&0< pos) {1861int cnt;1862size_t nread;1863char buf[BUFSIZ];1864char*endp, *scanp;18651866/* Fill next block from the end */1867 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1868if(fseek(logfp, pos - cnt, SEEK_SET)) {1869 ret =error("cannot seek back reflog for%s:%s",1870 refname,strerror(errno));1871break;1872}1873 nread =fread(buf, cnt,1, logfp);1874if(nread !=1) {1875 ret =error("cannot read%dbytes from reflog for%s:%s",1876 cnt, refname,strerror(errno));1877break;1878}1879 pos -= cnt;18801881 scanp = endp = buf + cnt;1882if(at_tail && scanp[-1] =='\n')1883/* Looking at the final LF at the end of the file */1884 scanp--;1885 at_tail =0;18861887while(buf < scanp) {1888/*1889 * terminating LF of the previous line, or the beginning1890 * of the buffer.1891 */1892char*bp;18931894 bp =find_beginning_of_line(buf, scanp);18951896if(*bp =='\n') {1897/*1898 * The newline is the end of the previous line,1899 * so we know we have complete line starting1900 * at (bp + 1). Prefix it onto any prior data1901 * we collected for the line and process it.1902 */1903strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1904 scanp = bp;1905 endp = bp +1;1906 ret =show_one_reflog_ent(&sb, fn, cb_data);1907strbuf_reset(&sb);1908if(ret)1909break;1910}else if(!pos) {1911/*1912 * We are at the start of the buffer, and the1913 * start of the file; there is no previous1914 * line, and we have everything for this one.1915 * Process it, and we can end the loop.1916 */1917strbuf_splice(&sb,0,0, buf, endp - buf);1918 ret =show_one_reflog_ent(&sb, fn, cb_data);1919strbuf_reset(&sb);1920break;1921}19221923if(bp == buf) {1924/*1925 * We are at the start of the buffer, and there1926 * is more file to read backwards. Which means1927 * we are in the middle of a line. Note that we1928 * may get here even if *bp was a newline; that1929 * just means we are at the exact end of the1930 * previous line, rather than some spot in the1931 * middle.1932 *1933 * Save away what we have to be combined with1934 * the data from the next read.1935 */1936strbuf_splice(&sb,0,0, buf, endp - buf);1937break;1938}1939}19401941}1942if(!ret && sb.len)1943die("BUG: reverse reflog parser had leftover data");19441945fclose(logfp);1946strbuf_release(&sb);1947return ret;1948}19491950static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1951const char*refname,1952 each_reflog_ent_fn fn,void*cb_data)1953{1954struct files_ref_store *refs =1955files_downcast(ref_store, REF_STORE_READ,1956"for_each_reflog_ent");1957FILE*logfp;1958struct strbuf sb = STRBUF_INIT;1959int ret =0;19601961files_reflog_path(refs, &sb, refname);1962 logfp =fopen(sb.buf,"r");1963strbuf_release(&sb);1964if(!logfp)1965return-1;19661967while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1968 ret =show_one_reflog_ent(&sb, fn, cb_data);1969fclose(logfp);1970strbuf_release(&sb);1971return ret;1972}19731974struct files_reflog_iterator {1975struct ref_iterator base;19761977struct ref_store *ref_store;1978struct dir_iterator *dir_iterator;1979struct object_id oid;1980};19811982static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1983{1984struct files_reflog_iterator *iter =1985(struct files_reflog_iterator *)ref_iterator;1986struct dir_iterator *diter = iter->dir_iterator;1987int ok;19881989while((ok =dir_iterator_advance(diter)) == ITER_OK) {1990int flags;19911992if(!S_ISREG(diter->st.st_mode))1993continue;1994if(diter->basename[0] =='.')1995continue;1996if(ends_with(diter->basename,".lock"))1997continue;19981999if(refs_read_ref_full(iter->ref_store,2000 diter->relative_path,0,2001 iter->oid.hash, &flags)) {2002error("bad ref for%s", diter->path.buf);2003continue;2004}20052006 iter->base.refname = diter->relative_path;2007 iter->base.oid = &iter->oid;2008 iter->base.flags = flags;2009return ITER_OK;2010}20112012 iter->dir_iterator = NULL;2013if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2014 ok = ITER_ERROR;2015return ok;2016}20172018static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2019struct object_id *peeled)2020{2021die("BUG: ref_iterator_peel() called for reflog_iterator");2022}20232024static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2025{2026struct files_reflog_iterator *iter =2027(struct files_reflog_iterator *)ref_iterator;2028int ok = ITER_DONE;20292030if(iter->dir_iterator)2031 ok =dir_iterator_abort(iter->dir_iterator);20322033base_ref_iterator_free(ref_iterator);2034return ok;2035}20362037static struct ref_iterator_vtable files_reflog_iterator_vtable = {2038 files_reflog_iterator_advance,2039 files_reflog_iterator_peel,2040 files_reflog_iterator_abort2041};20422043static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2044{2045struct files_ref_store *refs =2046files_downcast(ref_store, REF_STORE_READ,2047"reflog_iterator_begin");2048struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2049struct ref_iterator *ref_iterator = &iter->base;2050struct strbuf sb = STRBUF_INIT;20512052base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable,0);2053files_reflog_path(refs, &sb, NULL);2054 iter->dir_iterator =dir_iterator_begin(sb.buf);2055 iter->ref_store = ref_store;2056strbuf_release(&sb);2057return ref_iterator;2058}20592060/*2061 * If update is a direct update of head_ref (the reference pointed to2062 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2063 */2064static intsplit_head_update(struct ref_update *update,2065struct ref_transaction *transaction,2066const char*head_ref,2067struct string_list *affected_refnames,2068struct strbuf *err)2069{2070struct string_list_item *item;2071struct ref_update *new_update;20722073if((update->flags & REF_LOG_ONLY) ||2074(update->flags & REF_ISPRUNING) ||2075(update->flags & REF_UPDATE_VIA_HEAD))2076return0;20772078if(strcmp(update->refname, head_ref))2079return0;20802081/*2082 * First make sure that HEAD is not already in the2083 * transaction. This insertion is O(N) in the transaction2084 * size, but it happens at most once per transaction.2085 */2086 item =string_list_insert(affected_refnames,"HEAD");2087if(item->util) {2088/* An entry already existed */2089strbuf_addf(err,2090"multiple updates for 'HEAD' (including one "2091"via its referent '%s') are not allowed",2092 update->refname);2093return TRANSACTION_NAME_CONFLICT;2094}20952096 new_update =ref_transaction_add_update(2097 transaction,"HEAD",2098 update->flags | REF_LOG_ONLY | REF_NODEREF,2099 update->new_oid.hash, update->old_oid.hash,2100 update->msg);21012102 item->util = new_update;21032104return0;2105}21062107/*2108 * update is for a symref that points at referent and doesn't have2109 * REF_NODEREF set. Split it into two updates:2110 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2111 * - A new, separate update for the referent reference2112 * Note that the new update will itself be subject to splitting when2113 * the iteration gets to it.2114 */2115static intsplit_symref_update(struct files_ref_store *refs,2116struct ref_update *update,2117const char*referent,2118struct ref_transaction *transaction,2119struct string_list *affected_refnames,2120struct strbuf *err)2121{2122struct string_list_item *item;2123struct ref_update *new_update;2124unsigned int new_flags;21252126/*2127 * First make sure that referent is not already in the2128 * transaction. This insertion is O(N) in the transaction2129 * size, but it happens at most once per symref in a2130 * transaction.2131 */2132 item =string_list_insert(affected_refnames, referent);2133if(item->util) {2134/* An entry already existed */2135strbuf_addf(err,2136"multiple updates for '%s' (including one "2137"via symref '%s') are not allowed",2138 referent, update->refname);2139return TRANSACTION_NAME_CONFLICT;2140}21412142 new_flags = update->flags;2143if(!strcmp(update->refname,"HEAD")) {2144/*2145 * Record that the new update came via HEAD, so that2146 * when we process it, split_head_update() doesn't try2147 * to add another reflog update for HEAD. Note that2148 * this bit will be propagated if the new_update2149 * itself needs to be split.2150 */2151 new_flags |= REF_UPDATE_VIA_HEAD;2152}21532154 new_update =ref_transaction_add_update(2155 transaction, referent, new_flags,2156 update->new_oid.hash, update->old_oid.hash,2157 update->msg);21582159 new_update->parent_update = update;21602161/*2162 * Change the symbolic ref update to log only. Also, it2163 * doesn't need to check its old SHA-1 value, as that will be2164 * done when new_update is processed.2165 */2166 update->flags |= REF_LOG_ONLY | REF_NODEREF;2167 update->flags &= ~REF_HAVE_OLD;21682169 item->util = new_update;21702171return0;2172}21732174/*2175 * Return the refname under which update was originally requested.2176 */2177static const char*original_update_refname(struct ref_update *update)2178{2179while(update->parent_update)2180 update = update->parent_update;21812182return update->refname;2183}21842185/*2186 * Check whether the REF_HAVE_OLD and old_oid values stored in update2187 * are consistent with oid, which is the reference's current value. If2188 * everything is OK, return 0; otherwise, write an error message to2189 * err and return -1.2190 */2191static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2192struct strbuf *err)2193{2194if(!(update->flags & REF_HAVE_OLD) ||2195!oidcmp(oid, &update->old_oid))2196return0;21972198if(is_null_oid(&update->old_oid))2199strbuf_addf(err,"cannot lock ref '%s': "2200"reference already exists",2201original_update_refname(update));2202else if(is_null_oid(oid))2203strbuf_addf(err,"cannot lock ref '%s': "2204"reference is missing but expected%s",2205original_update_refname(update),2206oid_to_hex(&update->old_oid));2207else2208strbuf_addf(err,"cannot lock ref '%s': "2209"is at%sbut expected%s",2210original_update_refname(update),2211oid_to_hex(oid),2212oid_to_hex(&update->old_oid));22132214return-1;2215}22162217/*2218 * Prepare for carrying out update:2219 * - Lock the reference referred to by update.2220 * - Read the reference under lock.2221 * - Check that its old SHA-1 value (if specified) is correct, and in2222 * any case record it in update->lock->old_oid for later use when2223 * writing the reflog.2224 * - If it is a symref update without REF_NODEREF, split it up into a2225 * REF_LOG_ONLY update of the symref and add a separate update for2226 * the referent to transaction.2227 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2228 * update of HEAD.2229 */2230static intlock_ref_for_update(struct files_ref_store *refs,2231struct ref_update *update,2232struct ref_transaction *transaction,2233const char*head_ref,2234struct string_list *affected_refnames,2235struct strbuf *err)2236{2237struct strbuf referent = STRBUF_INIT;2238int mustexist = (update->flags & REF_HAVE_OLD) &&2239!is_null_oid(&update->old_oid);2240int ret;2241struct ref_lock *lock;22422243files_assert_main_repository(refs,"lock_ref_for_update");22442245if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2246 update->flags |= REF_DELETING;22472248if(head_ref) {2249 ret =split_head_update(update, transaction, head_ref,2250 affected_refnames, err);2251if(ret)2252return ret;2253}22542255 ret =lock_raw_ref(refs, update->refname, mustexist,2256 affected_refnames, NULL,2257&lock, &referent,2258&update->type, err);2259if(ret) {2260char*reason;22612262 reason =strbuf_detach(err, NULL);2263strbuf_addf(err,"cannot lock ref '%s':%s",2264original_update_refname(update), reason);2265free(reason);2266return ret;2267}22682269 update->backend_data = lock;22702271if(update->type & REF_ISSYMREF) {2272if(update->flags & REF_NODEREF) {2273/*2274 * We won't be reading the referent as part of2275 * the transaction, so we have to read it here2276 * to record and possibly check old_sha1:2277 */2278if(refs_read_ref_full(&refs->base,2279 referent.buf,0,2280 lock->old_oid.hash, NULL)) {2281if(update->flags & REF_HAVE_OLD) {2282strbuf_addf(err,"cannot lock ref '%s': "2283"error reading reference",2284original_update_refname(update));2285return-1;2286}2287}else if(check_old_oid(update, &lock->old_oid, err)) {2288return TRANSACTION_GENERIC_ERROR;2289}2290}else{2291/*2292 * Create a new update for the reference this2293 * symref is pointing at. Also, we will record2294 * and verify old_sha1 for this update as part2295 * of processing the split-off update, so we2296 * don't have to do it here.2297 */2298 ret =split_symref_update(refs, update,2299 referent.buf, transaction,2300 affected_refnames, err);2301if(ret)2302return ret;2303}2304}else{2305struct ref_update *parent_update;23062307if(check_old_oid(update, &lock->old_oid, err))2308return TRANSACTION_GENERIC_ERROR;23092310/*2311 * If this update is happening indirectly because of a2312 * symref update, record the old SHA-1 in the parent2313 * update:2314 */2315for(parent_update = update->parent_update;2316 parent_update;2317 parent_update = parent_update->parent_update) {2318struct ref_lock *parent_lock = parent_update->backend_data;2319oidcpy(&parent_lock->old_oid, &lock->old_oid);2320}2321}23222323if((update->flags & REF_HAVE_NEW) &&2324!(update->flags & REF_DELETING) &&2325!(update->flags & REF_LOG_ONLY)) {2326if(!(update->type & REF_ISSYMREF) &&2327!oidcmp(&lock->old_oid, &update->new_oid)) {2328/*2329 * The reference already has the desired2330 * value, so we don't need to write it.2331 */2332}else if(write_ref_to_lockfile(lock, &update->new_oid,2333 err)) {2334char*write_err =strbuf_detach(err, NULL);23352336/*2337 * The lock was freed upon failure of2338 * write_ref_to_lockfile():2339 */2340 update->backend_data = NULL;2341strbuf_addf(err,2342"cannot update ref '%s':%s",2343 update->refname, write_err);2344free(write_err);2345return TRANSACTION_GENERIC_ERROR;2346}else{2347 update->flags |= REF_NEEDS_COMMIT;2348}2349}2350if(!(update->flags & REF_NEEDS_COMMIT)) {2351/*2352 * We didn't call write_ref_to_lockfile(), so2353 * the lockfile is still open. Close it to2354 * free up the file descriptor:2355 */2356if(close_ref(lock)) {2357strbuf_addf(err,"couldn't close '%s.lock'",2358 update->refname);2359return TRANSACTION_GENERIC_ERROR;2360}2361}2362return0;2363}23642365struct files_transaction_backend_data {2366struct ref_transaction *packed_transaction;2367int packed_refs_locked;2368};23692370/*2371 * Unlock any references in `transaction` that are still locked, and2372 * mark the transaction closed.2373 */2374static voidfiles_transaction_cleanup(struct files_ref_store *refs,2375struct ref_transaction *transaction)2376{2377size_t i;2378struct files_transaction_backend_data *backend_data =2379 transaction->backend_data;2380struct strbuf err = STRBUF_INIT;23812382for(i =0; i < transaction->nr; i++) {2383struct ref_update *update = transaction->updates[i];2384struct ref_lock *lock = update->backend_data;23852386if(lock) {2387unlock_ref(lock);2388 update->backend_data = NULL;2389}2390}23912392if(backend_data->packed_transaction &&2393ref_transaction_abort(backend_data->packed_transaction, &err)) {2394error("error aborting transaction:%s", err.buf);2395strbuf_release(&err);2396}23972398if(backend_data->packed_refs_locked)2399packed_refs_unlock(refs->packed_ref_store);24002401free(backend_data);24022403 transaction->state = REF_TRANSACTION_CLOSED;2404}24052406static intfiles_transaction_prepare(struct ref_store *ref_store,2407struct ref_transaction *transaction,2408struct strbuf *err)2409{2410struct files_ref_store *refs =2411files_downcast(ref_store, REF_STORE_WRITE,2412"ref_transaction_prepare");2413size_t i;2414int ret =0;2415struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2416char*head_ref = NULL;2417int head_type;2418struct object_id head_oid;2419struct files_transaction_backend_data *backend_data;2420struct ref_transaction *packed_transaction = NULL;24212422assert(err);24232424if(!transaction->nr)2425goto cleanup;24262427 backend_data =xcalloc(1,sizeof(*backend_data));2428 transaction->backend_data = backend_data;24292430/*2431 * Fail if a refname appears more than once in the2432 * transaction. (If we end up splitting up any updates using2433 * split_symref_update() or split_head_update(), those2434 * functions will check that the new updates don't have the2435 * same refname as any existing ones.)2436 */2437for(i =0; i < transaction->nr; i++) {2438struct ref_update *update = transaction->updates[i];2439struct string_list_item *item =2440string_list_append(&affected_refnames, update->refname);24412442/*2443 * We store a pointer to update in item->util, but at2444 * the moment we never use the value of this field2445 * except to check whether it is non-NULL.2446 */2447 item->util = update;2448}2449string_list_sort(&affected_refnames);2450if(ref_update_reject_duplicates(&affected_refnames, err)) {2451 ret = TRANSACTION_GENERIC_ERROR;2452goto cleanup;2453}24542455/*2456 * Special hack: If a branch is updated directly and HEAD2457 * points to it (may happen on the remote side of a push2458 * for example) then logically the HEAD reflog should be2459 * updated too.2460 *2461 * A generic solution would require reverse symref lookups,2462 * but finding all symrefs pointing to a given branch would be2463 * rather costly for this rare event (the direct update of a2464 * branch) to be worth it. So let's cheat and check with HEAD2465 * only, which should cover 99% of all usage scenarios (even2466 * 100% of the default ones).2467 *2468 * So if HEAD is a symbolic reference, then record the name of2469 * the reference that it points to. If we see an update of2470 * head_ref within the transaction, then split_head_update()2471 * arranges for the reflog of HEAD to be updated, too.2472 */2473 head_ref =refs_resolve_refdup(ref_store,"HEAD",2474 RESOLVE_REF_NO_RECURSE,2475 head_oid.hash, &head_type);24762477if(head_ref && !(head_type & REF_ISSYMREF)) {2478FREE_AND_NULL(head_ref);2479}24802481/*2482 * Acquire all locks, verify old values if provided, check2483 * that new values are valid, and write new values to the2484 * lockfiles, ready to be activated. Only keep one lockfile2485 * open at a time to avoid running out of file descriptors.2486 * Note that lock_ref_for_update() might append more updates2487 * to the transaction.2488 */2489for(i =0; i < transaction->nr; i++) {2490struct ref_update *update = transaction->updates[i];24912492 ret =lock_ref_for_update(refs, update, transaction,2493 head_ref, &affected_refnames, err);2494if(ret)2495break;24962497if(update->flags & REF_DELETING &&2498!(update->flags & REF_LOG_ONLY) &&2499!(update->flags & REF_ISPRUNING)) {2500/*2501 * This reference has to be deleted from2502 * packed-refs if it exists there.2503 */2504if(!packed_transaction) {2505 packed_transaction =ref_store_transaction_begin(2506 refs->packed_ref_store, err);2507if(!packed_transaction) {2508 ret = TRANSACTION_GENERIC_ERROR;2509goto cleanup;2510}25112512 backend_data->packed_transaction =2513 packed_transaction;2514}25152516ref_transaction_add_update(2517 packed_transaction, update->refname,2518 update->flags & ~REF_HAVE_OLD,2519 update->new_oid.hash, update->old_oid.hash,2520 NULL);2521}2522}25232524if(packed_transaction) {2525if(packed_refs_lock(refs->packed_ref_store,0, err)) {2526 ret = TRANSACTION_GENERIC_ERROR;2527goto cleanup;2528}2529 backend_data->packed_refs_locked =1;2530 ret =ref_transaction_prepare(packed_transaction, err);2531}25322533cleanup:2534free(head_ref);2535string_list_clear(&affected_refnames,0);25362537if(ret)2538files_transaction_cleanup(refs, transaction);2539else2540 transaction->state = REF_TRANSACTION_PREPARED;25412542return ret;2543}25442545static intfiles_transaction_finish(struct ref_store *ref_store,2546struct ref_transaction *transaction,2547struct strbuf *err)2548{2549struct files_ref_store *refs =2550files_downcast(ref_store,0,"ref_transaction_finish");2551size_t i;2552int ret =0;2553struct strbuf sb = STRBUF_INIT;2554struct files_transaction_backend_data *backend_data;2555struct ref_transaction *packed_transaction;255625572558assert(err);25592560if(!transaction->nr) {2561 transaction->state = REF_TRANSACTION_CLOSED;2562return0;2563}25642565 backend_data = transaction->backend_data;2566 packed_transaction = backend_data->packed_transaction;25672568/* Perform updates first so live commits remain referenced */2569for(i =0; i < transaction->nr; i++) {2570struct ref_update *update = transaction->updates[i];2571struct ref_lock *lock = update->backend_data;25722573if(update->flags & REF_NEEDS_COMMIT ||2574 update->flags & REF_LOG_ONLY) {2575if(files_log_ref_write(refs,2576 lock->ref_name,2577&lock->old_oid,2578&update->new_oid,2579 update->msg, update->flags,2580 err)) {2581char*old_msg =strbuf_detach(err, NULL);25822583strbuf_addf(err,"cannot update the ref '%s':%s",2584 lock->ref_name, old_msg);2585free(old_msg);2586unlock_ref(lock);2587 update->backend_data = NULL;2588 ret = TRANSACTION_GENERIC_ERROR;2589goto cleanup;2590}2591}2592if(update->flags & REF_NEEDS_COMMIT) {2593clear_loose_ref_cache(refs);2594if(commit_ref(lock)) {2595strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2596unlock_ref(lock);2597 update->backend_data = NULL;2598 ret = TRANSACTION_GENERIC_ERROR;2599goto cleanup;2600}2601}2602}26032604/*2605 * Now that updates are safely completed, we can perform2606 * deletes. First delete the reflogs of any references that2607 * will be deleted, since (in the unexpected event of an2608 * error) leaving a reference without a reflog is less bad2609 * than leaving a reflog without a reference (the latter is a2610 * mildly invalid repository state):2611 */2612for(i =0; i < transaction->nr; i++) {2613struct ref_update *update = transaction->updates[i];2614if(update->flags & REF_DELETING &&2615!(update->flags & REF_LOG_ONLY) &&2616!(update->flags & REF_ISPRUNING)) {2617strbuf_reset(&sb);2618files_reflog_path(refs, &sb, update->refname);2619if(!unlink_or_warn(sb.buf))2620try_remove_empty_parents(refs, update->refname,2621 REMOVE_EMPTY_PARENTS_REFLOG);2622}2623}26242625/*2626 * Perform deletes now that updates are safely completed.2627 *2628 * First delete any packed versions of the references, while2629 * retaining the packed-refs lock:2630 */2631if(packed_transaction) {2632 ret =ref_transaction_commit(packed_transaction, err);2633ref_transaction_free(packed_transaction);2634 packed_transaction = NULL;2635 backend_data->packed_transaction = NULL;2636if(ret)2637goto cleanup;2638}26392640/* Now delete the loose versions of the references: */2641for(i =0; i < transaction->nr; i++) {2642struct ref_update *update = transaction->updates[i];2643struct ref_lock *lock = update->backend_data;26442645if(update->flags & REF_DELETING &&2646!(update->flags & REF_LOG_ONLY)) {2647if(!(update->type & REF_ISPACKED) ||2648 update->type & REF_ISSYMREF) {2649/* It is a loose reference. */2650strbuf_reset(&sb);2651files_ref_path(refs, &sb, lock->ref_name);2652if(unlink_or_msg(sb.buf, err)) {2653 ret = TRANSACTION_GENERIC_ERROR;2654goto cleanup;2655}2656 update->flags |= REF_DELETED_LOOSE;2657}2658}2659}26602661clear_loose_ref_cache(refs);26622663cleanup:2664files_transaction_cleanup(refs, transaction);26652666for(i =0; i < transaction->nr; i++) {2667struct ref_update *update = transaction->updates[i];26682669if(update->flags & REF_DELETED_LOOSE) {2670/*2671 * The loose reference was deleted. Delete any2672 * empty parent directories. (Note that this2673 * can only work because we have already2674 * removed the lockfile.)2675 */2676try_remove_empty_parents(refs, update->refname,2677 REMOVE_EMPTY_PARENTS_REF);2678}2679}26802681strbuf_release(&sb);2682return ret;2683}26842685static intfiles_transaction_abort(struct ref_store *ref_store,2686struct ref_transaction *transaction,2687struct strbuf *err)2688{2689struct files_ref_store *refs =2690files_downcast(ref_store,0,"ref_transaction_abort");26912692files_transaction_cleanup(refs, transaction);2693return0;2694}26952696static intref_present(const char*refname,2697const struct object_id *oid,int flags,void*cb_data)2698{2699struct string_list *affected_refnames = cb_data;27002701returnstring_list_has_string(affected_refnames, refname);2702}27032704static intfiles_initial_transaction_commit(struct ref_store *ref_store,2705struct ref_transaction *transaction,2706struct strbuf *err)2707{2708struct files_ref_store *refs =2709files_downcast(ref_store, REF_STORE_WRITE,2710"initial_ref_transaction_commit");2711size_t i;2712int ret =0;2713struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2714struct ref_transaction *packed_transaction = NULL;27152716assert(err);27172718if(transaction->state != REF_TRANSACTION_OPEN)2719die("BUG: commit called for transaction that is not open");27202721/* Fail if a refname appears more than once in the transaction: */2722for(i =0; i < transaction->nr; i++)2723string_list_append(&affected_refnames,2724 transaction->updates[i]->refname);2725string_list_sort(&affected_refnames);2726if(ref_update_reject_duplicates(&affected_refnames, err)) {2727 ret = TRANSACTION_GENERIC_ERROR;2728goto cleanup;2729}27302731/*2732 * It's really undefined to call this function in an active2733 * repository or when there are existing references: we are2734 * only locking and changing packed-refs, so (1) any2735 * simultaneous processes might try to change a reference at2736 * the same time we do, and (2) any existing loose versions of2737 * the references that we are setting would have precedence2738 * over our values. But some remote helpers create the remote2739 * "HEAD" and "master" branches before calling this function,2740 * so here we really only check that none of the references2741 * that we are creating already exists.2742 */2743if(refs_for_each_rawref(&refs->base, ref_present,2744&affected_refnames))2745die("BUG: initial ref transaction called with existing refs");27462747 packed_transaction =ref_store_transaction_begin(refs->packed_ref_store, err);2748if(!packed_transaction) {2749 ret = TRANSACTION_GENERIC_ERROR;2750goto cleanup;2751}27522753for(i =0; i < transaction->nr; i++) {2754struct ref_update *update = transaction->updates[i];27552756if((update->flags & REF_HAVE_OLD) &&2757!is_null_oid(&update->old_oid))2758die("BUG: initial ref transaction with old_sha1 set");2759if(refs_verify_refname_available(&refs->base, update->refname,2760&affected_refnames, NULL,2761 err)) {2762 ret = TRANSACTION_NAME_CONFLICT;2763goto cleanup;2764}27652766/*2767 * Add a reference creation for this reference to the2768 * packed-refs transaction:2769 */2770ref_transaction_add_update(packed_transaction, update->refname,2771 update->flags & ~REF_HAVE_OLD,2772 update->new_oid.hash, update->old_oid.hash,2773 NULL);2774}27752776if(packed_refs_lock(refs->packed_ref_store,0, err)) {2777 ret = TRANSACTION_GENERIC_ERROR;2778goto cleanup;2779}27802781if(initial_ref_transaction_commit(packed_transaction, err)) {2782 ret = TRANSACTION_GENERIC_ERROR;2783goto cleanup;2784}27852786cleanup:2787if(packed_transaction)2788ref_transaction_free(packed_transaction);2789packed_refs_unlock(refs->packed_ref_store);2790 transaction->state = REF_TRANSACTION_CLOSED;2791string_list_clear(&affected_refnames,0);2792return ret;2793}27942795struct expire_reflog_cb {2796unsigned int flags;2797 reflog_expiry_should_prune_fn *should_prune_fn;2798void*policy_cb;2799FILE*newlog;2800struct object_id last_kept_oid;2801};28022803static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2804const char*email, timestamp_t timestamp,int tz,2805const char*message,void*cb_data)2806{2807struct expire_reflog_cb *cb = cb_data;2808struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;28092810if(cb->flags & EXPIRE_REFLOGS_REWRITE)2811 ooid = &cb->last_kept_oid;28122813if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2814 message, policy_cb)) {2815if(!cb->newlog)2816printf("would prune%s", message);2817else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2818printf("prune%s", message);2819}else{2820if(cb->newlog) {2821fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2822oid_to_hex(ooid),oid_to_hex(noid),2823 email, timestamp, tz, message);2824oidcpy(&cb->last_kept_oid, noid);2825}2826if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2827printf("keep%s", message);2828}2829return0;2830}28312832static intfiles_reflog_expire(struct ref_store *ref_store,2833const char*refname,const unsigned char*sha1,2834unsigned int flags,2835 reflog_expiry_prepare_fn prepare_fn,2836 reflog_expiry_should_prune_fn should_prune_fn,2837 reflog_expiry_cleanup_fn cleanup_fn,2838void*policy_cb_data)2839{2840struct files_ref_store *refs =2841files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2842static struct lock_file reflog_lock;2843struct expire_reflog_cb cb;2844struct ref_lock *lock;2845struct strbuf log_file_sb = STRBUF_INIT;2846char*log_file;2847int status =0;2848int type;2849struct strbuf err = STRBUF_INIT;2850struct object_id oid;28512852memset(&cb,0,sizeof(cb));2853 cb.flags = flags;2854 cb.policy_cb = policy_cb_data;2855 cb.should_prune_fn = should_prune_fn;28562857/*2858 * The reflog file is locked by holding the lock on the2859 * reference itself, plus we might need to update the2860 * reference if --updateref was specified:2861 */2862 lock =lock_ref_sha1_basic(refs, refname, sha1,2863 NULL, NULL, REF_NODEREF,2864&type, &err);2865if(!lock) {2866error("cannot lock ref '%s':%s", refname, err.buf);2867strbuf_release(&err);2868return-1;2869}2870if(!refs_reflog_exists(ref_store, refname)) {2871unlock_ref(lock);2872return0;2873}28742875files_reflog_path(refs, &log_file_sb, refname);2876 log_file =strbuf_detach(&log_file_sb, NULL);2877if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2878/*2879 * Even though holding $GIT_DIR/logs/$reflog.lock has2880 * no locking implications, we use the lock_file2881 * machinery here anyway because it does a lot of the2882 * work we need, including cleaning up if the program2883 * exits unexpectedly.2884 */2885if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2886struct strbuf err = STRBUF_INIT;2887unable_to_lock_message(log_file, errno, &err);2888error("%s", err.buf);2889strbuf_release(&err);2890goto failure;2891}2892 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2893if(!cb.newlog) {2894error("cannot fdopen%s(%s)",2895get_lock_file_path(&reflog_lock),strerror(errno));2896goto failure;2897}2898}28992900hashcpy(oid.hash, sha1);29012902(*prepare_fn)(refname, &oid, cb.policy_cb);2903refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2904(*cleanup_fn)(cb.policy_cb);29052906if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2907/*2908 * It doesn't make sense to adjust a reference pointed2909 * to by a symbolic ref based on expiring entries in2910 * the symbolic reference's reflog. Nor can we update2911 * a reference if there are no remaining reflog2912 * entries.2913 */2914int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2915!(type & REF_ISSYMREF) &&2916!is_null_oid(&cb.last_kept_oid);29172918if(close_lock_file(&reflog_lock)) {2919 status |=error("couldn't write%s:%s", log_file,2920strerror(errno));2921}else if(update &&2922(write_in_full(get_lock_file_fd(lock->lk),2923oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2924write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2925close_ref(lock) <0)) {2926 status |=error("couldn't write%s",2927get_lock_file_path(lock->lk));2928rollback_lock_file(&reflog_lock);2929}else if(commit_lock_file(&reflog_lock)) {2930 status |=error("unable to write reflog '%s' (%s)",2931 log_file,strerror(errno));2932}else if(update &&commit_ref(lock)) {2933 status |=error("couldn't set%s", lock->ref_name);2934}2935}2936free(log_file);2937unlock_ref(lock);2938return status;29392940 failure:2941rollback_lock_file(&reflog_lock);2942free(log_file);2943unlock_ref(lock);2944return-1;2945}29462947static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2948{2949struct files_ref_store *refs =2950files_downcast(ref_store, REF_STORE_WRITE,"init_db");2951struct strbuf sb = STRBUF_INIT;29522953/*2954 * Create .git/refs/{heads,tags}2955 */2956files_ref_path(refs, &sb,"refs/heads");2957safe_create_dir(sb.buf,1);29582959strbuf_reset(&sb);2960files_ref_path(refs, &sb,"refs/tags");2961safe_create_dir(sb.buf,1);29622963strbuf_release(&sb);2964return0;2965}29662967struct ref_storage_be refs_be_files = {2968 NULL,2969"files",2970 files_ref_store_create,2971 files_init_db,2972 files_transaction_prepare,2973 files_transaction_finish,2974 files_transaction_abort,2975 files_initial_transaction_commit,29762977 files_pack_refs,2978 files_create_symref,2979 files_delete_refs,2980 files_rename_ref,29812982 files_ref_iterator_begin,2983 files_read_raw_ref,29842985 files_reflog_iterator_begin,2986 files_for_each_reflog_ent,2987 files_for_each_reflog_ent_reverse,2988 files_reflog_exists,2989 files_create_reflog,2990 files_delete_reflog,2991 files_reflog_expire2992};