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{ 421rollback_lock_file(&lock->lk); 422free(lock->ref_name); 423free(lock); 424} 425 426/* 427 * Lock refname, without following symrefs, and set *lock_p to point 428 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 429 * and type similarly to read_raw_ref(). 430 * 431 * The caller must verify that refname is a "safe" reference name (in 432 * the sense of refname_is_safe()) before calling this function. 433 * 434 * If the reference doesn't already exist, verify that refname doesn't 435 * have a D/F conflict with any existing references. extras and skip 436 * are passed to refs_verify_refname_available() for this check. 437 * 438 * If mustexist is not set and the reference is not found or is 439 * broken, lock the reference anyway but clear sha1. 440 * 441 * Return 0 on success. On failure, write an error message to err and 442 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 443 * 444 * Implementation note: This function is basically 445 * 446 * lock reference 447 * read_raw_ref() 448 * 449 * but it includes a lot more code to 450 * - Deal with possible races with other processes 451 * - Avoid calling refs_verify_refname_available() when it can be 452 * avoided, namely if we were successfully able to read the ref 453 * - Generate informative error messages in the case of failure 454 */ 455static intlock_raw_ref(struct files_ref_store *refs, 456const char*refname,int mustexist, 457const struct string_list *extras, 458const struct string_list *skip, 459struct ref_lock **lock_p, 460struct strbuf *referent, 461unsigned int*type, 462struct strbuf *err) 463{ 464struct ref_lock *lock; 465struct strbuf ref_file = STRBUF_INIT; 466int attempts_remaining =3; 467int ret = TRANSACTION_GENERIC_ERROR; 468 469assert(err); 470files_assert_main_repository(refs,"lock_raw_ref"); 471 472*type =0; 473 474/* First lock the file so it can't change out from under us. */ 475 476*lock_p = lock =xcalloc(1,sizeof(*lock)); 477 478 lock->ref_name =xstrdup(refname); 479files_ref_path(refs, &ref_file, refname); 480 481retry: 482switch(safe_create_leading_directories(ref_file.buf)) { 483case SCLD_OK: 484break;/* success */ 485case SCLD_EXISTS: 486/* 487 * Suppose refname is "refs/foo/bar". We just failed 488 * to create the containing directory, "refs/foo", 489 * because there was a non-directory in the way. This 490 * indicates a D/F conflict, probably because of 491 * another reference such as "refs/foo". There is no 492 * reason to expect this error to be transitory. 493 */ 494if(refs_verify_refname_available(&refs->base, refname, 495 extras, skip, err)) { 496if(mustexist) { 497/* 498 * To the user the relevant error is 499 * that the "mustexist" reference is 500 * missing: 501 */ 502strbuf_reset(err); 503strbuf_addf(err,"unable to resolve reference '%s'", 504 refname); 505}else{ 506/* 507 * The error message set by 508 * refs_verify_refname_available() is 509 * OK. 510 */ 511 ret = TRANSACTION_NAME_CONFLICT; 512} 513}else{ 514/* 515 * The file that is in the way isn't a loose 516 * reference. Report it as a low-level 517 * failure. 518 */ 519strbuf_addf(err,"unable to create lock file%s.lock; " 520"non-directory in the way", 521 ref_file.buf); 522} 523goto error_return; 524case SCLD_VANISHED: 525/* Maybe another process was tidying up. Try again. */ 526if(--attempts_remaining >0) 527goto retry; 528/* fall through */ 529default: 530strbuf_addf(err,"unable to create directory for%s", 531 ref_file.buf); 532goto error_return; 533} 534 535if(hold_lock_file_for_update_timeout( 536&lock->lk, ref_file.buf, LOCK_NO_DEREF, 537get_files_ref_lock_timeout_ms()) <0) { 538if(errno == ENOENT && --attempts_remaining >0) { 539/* 540 * Maybe somebody just deleted one of the 541 * directories leading to ref_file. Try 542 * again: 543 */ 544goto retry; 545}else{ 546unable_to_lock_message(ref_file.buf, errno, err); 547goto error_return; 548} 549} 550 551/* 552 * Now we hold the lock and can read the reference without 553 * fear that its value will change. 554 */ 555 556if(files_read_raw_ref(&refs->base, refname, 557 lock->old_oid.hash, referent, type)) { 558if(errno == ENOENT) { 559if(mustexist) { 560/* Garden variety missing reference. */ 561strbuf_addf(err,"unable to resolve reference '%s'", 562 refname); 563goto error_return; 564}else{ 565/* 566 * Reference is missing, but that's OK. We 567 * know that there is not a conflict with 568 * another loose reference because 569 * (supposing that we are trying to lock 570 * reference "refs/foo/bar"): 571 * 572 * - We were successfully able to create 573 * the lockfile refs/foo/bar.lock, so we 574 * know there cannot be a loose reference 575 * named "refs/foo". 576 * 577 * - We got ENOENT and not EISDIR, so we 578 * know that there cannot be a loose 579 * reference named "refs/foo/bar/baz". 580 */ 581} 582}else if(errno == EISDIR) { 583/* 584 * There is a directory in the way. It might have 585 * contained references that have been deleted. If 586 * we don't require that the reference already 587 * exists, try to remove the directory so that it 588 * doesn't cause trouble when we want to rename the 589 * lockfile into place later. 590 */ 591if(mustexist) { 592/* Garden variety missing reference. */ 593strbuf_addf(err,"unable to resolve reference '%s'", 594 refname); 595goto error_return; 596}else if(remove_dir_recursively(&ref_file, 597 REMOVE_DIR_EMPTY_ONLY)) { 598if(refs_verify_refname_available( 599&refs->base, refname, 600 extras, skip, err)) { 601/* 602 * The error message set by 603 * verify_refname_available() is OK. 604 */ 605 ret = TRANSACTION_NAME_CONFLICT; 606goto error_return; 607}else{ 608/* 609 * We can't delete the directory, 610 * but we also don't know of any 611 * references that it should 612 * contain. 613 */ 614strbuf_addf(err,"there is a non-empty directory '%s' " 615"blocking reference '%s'", 616 ref_file.buf, refname); 617goto error_return; 618} 619} 620}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 621strbuf_addf(err,"unable to resolve reference '%s': " 622"reference broken", refname); 623goto error_return; 624}else{ 625strbuf_addf(err,"unable to resolve reference '%s':%s", 626 refname,strerror(errno)); 627goto error_return; 628} 629 630/* 631 * If the ref did not exist and we are creating it, 632 * make sure there is no existing packed ref that 633 * conflicts with refname: 634 */ 635if(refs_verify_refname_available( 636 refs->packed_ref_store, refname, 637 extras, skip, err)) 638goto error_return; 639} 640 641 ret =0; 642goto out; 643 644error_return: 645unlock_ref(lock); 646*lock_p = NULL; 647 648out: 649strbuf_release(&ref_file); 650return ret; 651} 652 653static intfiles_peel_ref(struct ref_store *ref_store, 654const char*refname,unsigned char*sha1) 655{ 656struct files_ref_store *refs = 657files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 658"peel_ref"); 659int flag; 660unsigned char base[20]; 661 662if(current_ref_iter && current_ref_iter->refname == refname) { 663struct object_id peeled; 664 665if(ref_iterator_peel(current_ref_iter, &peeled)) 666return-1; 667hashcpy(sha1, peeled.hash); 668return0; 669} 670 671if(refs_read_ref_full(ref_store, refname, 672 RESOLVE_REF_READING, base, &flag)) 673return-1; 674 675/* 676 * If the reference is packed, read its ref_entry from the 677 * cache in the hope that we already know its peeled value. 678 * We only try this optimization on packed references because 679 * (a) forcing the filling of the loose reference cache could 680 * be expensive and (b) loose references anyway usually do not 681 * have REF_KNOWS_PEELED. 682 */ 683if(flag & REF_ISPACKED && 684!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 685return0; 686 687returnpeel_object(base, sha1); 688} 689 690struct files_ref_iterator { 691struct ref_iterator base; 692 693struct ref_iterator *iter0; 694unsigned int flags; 695}; 696 697static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 698{ 699struct files_ref_iterator *iter = 700(struct files_ref_iterator *)ref_iterator; 701int ok; 702 703while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 704if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 705ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 706continue; 707 708if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 709!ref_resolves_to_object(iter->iter0->refname, 710 iter->iter0->oid, 711 iter->iter0->flags)) 712continue; 713 714 iter->base.refname = iter->iter0->refname; 715 iter->base.oid = iter->iter0->oid; 716 iter->base.flags = iter->iter0->flags; 717return ITER_OK; 718} 719 720 iter->iter0 = NULL; 721if(ref_iterator_abort(ref_iterator) != ITER_DONE) 722 ok = ITER_ERROR; 723 724return ok; 725} 726 727static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 728struct object_id *peeled) 729{ 730struct files_ref_iterator *iter = 731(struct files_ref_iterator *)ref_iterator; 732 733returnref_iterator_peel(iter->iter0, peeled); 734} 735 736static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 737{ 738struct files_ref_iterator *iter = 739(struct files_ref_iterator *)ref_iterator; 740int ok = ITER_DONE; 741 742if(iter->iter0) 743 ok =ref_iterator_abort(iter->iter0); 744 745base_ref_iterator_free(ref_iterator); 746return ok; 747} 748 749static struct ref_iterator_vtable files_ref_iterator_vtable = { 750 files_ref_iterator_advance, 751 files_ref_iterator_peel, 752 files_ref_iterator_abort 753}; 754 755static struct ref_iterator *files_ref_iterator_begin( 756struct ref_store *ref_store, 757const char*prefix,unsigned int flags) 758{ 759struct files_ref_store *refs; 760struct ref_iterator *loose_iter, *packed_iter; 761struct files_ref_iterator *iter; 762struct ref_iterator *ref_iterator; 763unsigned int required_flags = REF_STORE_READ; 764 765if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 766 required_flags |= REF_STORE_ODB; 767 768 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 769 770 iter =xcalloc(1,sizeof(*iter)); 771 ref_iterator = &iter->base; 772base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 773 774/* 775 * We must make sure that all loose refs are read before 776 * accessing the packed-refs file; this avoids a race 777 * condition if loose refs are migrated to the packed-refs 778 * file by a simultaneous process, but our in-memory view is 779 * from before the migration. We ensure this as follows: 780 * First, we call start the loose refs iteration with its 781 * `prime_ref` argument set to true. This causes the loose 782 * references in the subtree to be pre-read into the cache. 783 * (If they've already been read, that's OK; we only need to 784 * guarantee that they're read before the packed refs, not 785 * *how much* before.) After that, we call 786 * packed_ref_iterator_begin(), which internally checks 787 * whether the packed-ref cache is up to date with what is on 788 * disk, and re-reads it if not. 789 */ 790 791 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 792 prefix,1); 793 794/* 795 * The packed-refs file might contain broken references, for 796 * example an old version of a reference that points at an 797 * object that has since been garbage-collected. This is OK as 798 * long as there is a corresponding loose reference that 799 * overrides it, and we don't want to emit an error message in 800 * this case. So ask the packed_ref_store for all of its 801 * references, and (if needed) do our own check for broken 802 * ones in files_ref_iterator_advance(), after we have merged 803 * the packed and loose references. 804 */ 805 packed_iter =refs_ref_iterator_begin( 806 refs->packed_ref_store, prefix,0, 807 DO_FOR_EACH_INCLUDE_BROKEN); 808 809 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 810 iter->flags = flags; 811 812return ref_iterator; 813} 814 815/* 816 * Verify that the reference locked by lock has the value old_sha1. 817 * Fail if the reference doesn't exist and mustexist is set. Return 0 818 * on success. On error, write an error message to err, set errno, and 819 * return a negative value. 820 */ 821static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 822const unsigned char*old_sha1,int mustexist, 823struct strbuf *err) 824{ 825assert(err); 826 827if(refs_read_ref_full(ref_store, lock->ref_name, 828 mustexist ? RESOLVE_REF_READING :0, 829 lock->old_oid.hash, NULL)) { 830if(old_sha1) { 831int save_errno = errno; 832strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 833 errno = save_errno; 834return-1; 835}else{ 836oidclr(&lock->old_oid); 837return0; 838} 839} 840if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 841strbuf_addf(err,"ref '%s' is at%sbut expected%s", 842 lock->ref_name, 843oid_to_hex(&lock->old_oid), 844sha1_to_hex(old_sha1)); 845 errno = EBUSY; 846return-1; 847} 848return0; 849} 850 851static intremove_empty_directories(struct strbuf *path) 852{ 853/* 854 * we want to create a file but there is a directory there; 855 * if that is an empty directory (or a directory that contains 856 * only empty directories), remove them. 857 */ 858returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 859} 860 861static intcreate_reflock(const char*path,void*cb) 862{ 863struct lock_file *lk = cb; 864 865returnhold_lock_file_for_update_timeout( 866 lk, path, LOCK_NO_DEREF, 867get_files_ref_lock_timeout_ms()) <0? -1:0; 868} 869 870/* 871 * Locks a ref returning the lock on success and NULL on failure. 872 * On failure errno is set to something meaningful. 873 */ 874static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 875const char*refname, 876const unsigned char*old_sha1, 877const struct string_list *extras, 878const struct string_list *skip, 879unsigned int flags,int*type, 880struct strbuf *err) 881{ 882struct strbuf ref_file = STRBUF_INIT; 883struct ref_lock *lock; 884int last_errno =0; 885int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 886int resolve_flags = RESOLVE_REF_NO_RECURSE; 887int resolved; 888 889files_assert_main_repository(refs,"lock_ref_sha1_basic"); 890assert(err); 891 892 lock =xcalloc(1,sizeof(struct ref_lock)); 893 894if(mustexist) 895 resolve_flags |= RESOLVE_REF_READING; 896if(flags & REF_DELETING) 897 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 898 899files_ref_path(refs, &ref_file, refname); 900 resolved = !!refs_resolve_ref_unsafe(&refs->base, 901 refname, resolve_flags, 902 lock->old_oid.hash, type); 903if(!resolved && errno == EISDIR) { 904/* 905 * we are trying to lock foo but we used to 906 * have foo/bar which now does not exist; 907 * it is normal for the empty directory 'foo' 908 * to remain. 909 */ 910if(remove_empty_directories(&ref_file)) { 911 last_errno = errno; 912if(!refs_verify_refname_available( 913&refs->base, 914 refname, extras, skip, err)) 915strbuf_addf(err,"there are still refs under '%s'", 916 refname); 917goto error_return; 918} 919 resolved = !!refs_resolve_ref_unsafe(&refs->base, 920 refname, resolve_flags, 921 lock->old_oid.hash, type); 922} 923if(!resolved) { 924 last_errno = errno; 925if(last_errno != ENOTDIR || 926!refs_verify_refname_available(&refs->base, refname, 927 extras, skip, err)) 928strbuf_addf(err,"unable to resolve reference '%s':%s", 929 refname,strerror(last_errno)); 930 931goto error_return; 932} 933 934/* 935 * If the ref did not exist and we are creating it, make sure 936 * there is no existing packed ref whose name begins with our 937 * refname, nor a packed ref whose name is a proper prefix of 938 * our refname. 939 */ 940if(is_null_oid(&lock->old_oid) && 941refs_verify_refname_available(refs->packed_ref_store, refname, 942 extras, skip, err)) { 943 last_errno = ENOTDIR; 944goto error_return; 945} 946 947 lock->ref_name =xstrdup(refname); 948 949if(raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) { 950 last_errno = errno; 951unable_to_lock_message(ref_file.buf, errno, err); 952goto error_return; 953} 954 955if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 956 last_errno = errno; 957goto error_return; 958} 959goto out; 960 961 error_return: 962unlock_ref(lock); 963 lock = NULL; 964 965 out: 966strbuf_release(&ref_file); 967 errno = last_errno; 968return lock; 969} 970 971struct ref_to_prune { 972struct ref_to_prune *next; 973unsigned char sha1[20]; 974char name[FLEX_ARRAY]; 975}; 976 977enum{ 978 REMOVE_EMPTY_PARENTS_REF =0x01, 979 REMOVE_EMPTY_PARENTS_REFLOG =0x02 980}; 981 982/* 983 * Remove empty parent directories associated with the specified 984 * reference and/or its reflog, but spare [logs/]refs/ and immediate 985 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 986 * REMOVE_EMPTY_PARENTS_REFLOG. 987 */ 988static voidtry_remove_empty_parents(struct files_ref_store *refs, 989const char*refname, 990unsigned int flags) 991{ 992struct strbuf buf = STRBUF_INIT; 993struct strbuf sb = STRBUF_INIT; 994char*p, *q; 995int i; 996 997strbuf_addstr(&buf, refname); 998 p = buf.buf; 999for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1000while(*p && *p !='/')1001 p++;1002/* tolerate duplicate slashes; see check_refname_format() */1003while(*p =='/')1004 p++;1005}1006 q = buf.buf + buf.len;1007while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1008while(q > p && *q !='/')1009 q--;1010while(q > p && *(q-1) =='/')1011 q--;1012if(q == p)1013break;1014strbuf_setlen(&buf, q - buf.buf);10151016strbuf_reset(&sb);1017files_ref_path(refs, &sb, buf.buf);1018if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1019 flags &= ~REMOVE_EMPTY_PARENTS_REF;10201021strbuf_reset(&sb);1022files_reflog_path(refs, &sb, buf.buf);1023if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1024 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1025}1026strbuf_release(&buf);1027strbuf_release(&sb);1028}10291030/* make sure nobody touched the ref, and unlink */1031static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1032{1033struct ref_transaction *transaction;1034struct strbuf err = STRBUF_INIT;10351036if(check_refname_format(r->name,0))1037return;10381039 transaction =ref_store_transaction_begin(&refs->base, &err);1040if(!transaction ||1041ref_transaction_delete(transaction, r->name, r->sha1,1042 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1043ref_transaction_commit(transaction, &err)) {1044ref_transaction_free(transaction);1045error("%s", err.buf);1046strbuf_release(&err);1047return;1048}1049ref_transaction_free(transaction);1050strbuf_release(&err);1051}10521053static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1054{1055while(r) {1056prune_ref(refs, r);1057 r = r->next;1058}1059}10601061/*1062 * Return true if the specified reference should be packed.1063 */1064static intshould_pack_ref(const char*refname,1065const struct object_id *oid,unsigned int ref_flags,1066unsigned int pack_flags)1067{1068/* Do not pack per-worktree refs: */1069if(ref_type(refname) != REF_TYPE_NORMAL)1070return0;10711072/* Do not pack non-tags unless PACK_REFS_ALL is set: */1073if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1074return0;10751076/* Do not pack symbolic refs: */1077if(ref_flags & REF_ISSYMREF)1078return0;10791080/* Do not pack broken refs: */1081if(!ref_resolves_to_object(refname, oid, ref_flags))1082return0;10831084return1;1085}10861087static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1088{1089struct files_ref_store *refs =1090files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1091"pack_refs");1092struct ref_iterator *iter;1093int ok;1094struct ref_to_prune *refs_to_prune = NULL;1095struct strbuf err = STRBUF_INIT;10961097packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);10981099 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1100while((ok =ref_iterator_advance(iter)) == ITER_OK) {1101/*1102 * If the loose reference can be packed, add an entry1103 * in the packed ref cache. If the reference should be1104 * pruned, also add it to refs_to_prune.1105 */1106if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1107 flags))1108continue;11091110/*1111 * Create an entry in the packed-refs cache equivalent1112 * to the one from the loose ref cache, except that1113 * we don't copy the peeled status, because we want it1114 * to be re-peeled.1115 */1116add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11171118/* Schedule the loose reference for pruning if requested. */1119if((flags & PACK_REFS_PRUNE)) {1120struct ref_to_prune *n;1121FLEX_ALLOC_STR(n, name, iter->refname);1122hashcpy(n->sha1, iter->oid->hash);1123 n->next = refs_to_prune;1124 refs_to_prune = n;1125}1126}1127if(ok != ITER_DONE)1128die("error while iterating over references");11291130if(commit_packed_refs(refs->packed_ref_store, &err))1131die("unable to overwrite old ref-pack file:%s", err.buf);1132packed_refs_unlock(refs->packed_ref_store);11331134prune_refs(refs, refs_to_prune);1135strbuf_release(&err);1136return0;1137}11381139static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1140struct string_list *refnames,unsigned int flags)1141{1142struct files_ref_store *refs =1143files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1144struct strbuf err = STRBUF_INIT;1145int i, result =0;11461147if(!refnames->nr)1148return0;11491150if(packed_refs_lock(refs->packed_ref_store,0, &err))1151goto error;11521153if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1154packed_refs_unlock(refs->packed_ref_store);1155goto error;1156}11571158packed_refs_unlock(refs->packed_ref_store);11591160for(i =0; i < refnames->nr; i++) {1161const char*refname = refnames->items[i].string;11621163if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1164 result |=error(_("could not remove reference%s"), refname);1165}11661167strbuf_release(&err);1168return result;11691170error:1171/*1172 * If we failed to rewrite the packed-refs file, then it is1173 * unsafe to try to remove loose refs, because doing so might1174 * expose an obsolete packed value for a reference that might1175 * even point at an object that has been garbage collected.1176 */1177if(refnames->nr ==1)1178error(_("could not delete reference%s:%s"),1179 refnames->items[0].string, err.buf);1180else1181error(_("could not delete references:%s"), err.buf);11821183strbuf_release(&err);1184return-1;1185}11861187/*1188 * People using contrib's git-new-workdir have .git/logs/refs ->1189 * /some/other/path/.git/logs/refs, and that may live on another device.1190 *1191 * IOW, to avoid cross device rename errors, the temporary renamed log must1192 * live into logs/refs.1193 */1194#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11951196struct rename_cb {1197const char*tmp_renamed_log;1198int true_errno;1199};12001201static intrename_tmp_log_callback(const char*path,void*cb_data)1202{1203struct rename_cb *cb = cb_data;12041205if(rename(cb->tmp_renamed_log, path)) {1206/*1207 * rename(a, b) when b is an existing directory ought1208 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1209 * Sheesh. Record the true errno for error reporting,1210 * but report EISDIR to raceproof_create_file() so1211 * that it knows to retry.1212 */1213 cb->true_errno = errno;1214if(errno == ENOTDIR)1215 errno = EISDIR;1216return-1;1217}else{1218return0;1219}1220}12211222static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1223{1224struct strbuf path = STRBUF_INIT;1225struct strbuf tmp = STRBUF_INIT;1226struct rename_cb cb;1227int ret;12281229files_reflog_path(refs, &path, newrefname);1230files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1231 cb.tmp_renamed_log = tmp.buf;1232 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1233if(ret) {1234if(errno == EISDIR)1235error("directory not empty:%s", path.buf);1236else1237error("unable to move logfile%sto%s:%s",1238 tmp.buf, path.buf,1239strerror(cb.true_errno));1240}12411242strbuf_release(&path);1243strbuf_release(&tmp);1244return ret;1245}12461247static intwrite_ref_to_lockfile(struct ref_lock *lock,1248const struct object_id *oid,struct strbuf *err);1249static intcommit_ref_update(struct files_ref_store *refs,1250struct ref_lock *lock,1251const struct object_id *oid,const char*logmsg,1252struct strbuf *err);12531254static intfiles_rename_ref(struct ref_store *ref_store,1255const char*oldrefname,const char*newrefname,1256const char*logmsg)1257{1258struct files_ref_store *refs =1259files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1260struct object_id oid, orig_oid;1261int flag =0, logmoved =0;1262struct ref_lock *lock;1263struct stat loginfo;1264struct strbuf sb_oldref = STRBUF_INIT;1265struct strbuf sb_newref = STRBUF_INIT;1266struct strbuf tmp_renamed_log = STRBUF_INIT;1267int log, ret;1268struct strbuf err = STRBUF_INIT;12691270files_reflog_path(refs, &sb_oldref, oldrefname);1271files_reflog_path(refs, &sb_newref, newrefname);1272files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12731274 log = !lstat(sb_oldref.buf, &loginfo);1275if(log &&S_ISLNK(loginfo.st_mode)) {1276 ret =error("reflog for%sis a symlink", oldrefname);1277goto out;1278}12791280if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1281 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1282 orig_oid.hash, &flag)) {1283 ret =error("refname%snot found", oldrefname);1284goto out;1285}12861287if(flag & REF_ISSYMREF) {1288 ret =error("refname%sis a symbolic ref, renaming it is not supported",1289 oldrefname);1290goto out;1291}1292if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1293 ret =1;1294goto out;1295}12961297if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1298 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1299 oldrefname,strerror(errno));1300goto out;1301}13021303if(refs_delete_ref(&refs->base, logmsg, oldrefname,1304 orig_oid.hash, REF_NODEREF)) {1305error("unable to delete old%s", oldrefname);1306goto rollback;1307}13081309/*1310 * Since we are doing a shallow lookup, oid is not the1311 * correct value to pass to delete_ref as old_oid. But that1312 * doesn't matter, because an old_oid check wouldn't add to1313 * the safety anyway; we want to delete the reference whatever1314 * its current value.1315 */1316if(!refs_read_ref_full(&refs->base, newrefname,1317 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1318 oid.hash, NULL) &&1319refs_delete_ref(&refs->base, NULL, newrefname,1320 NULL, REF_NODEREF)) {1321if(errno == EISDIR) {1322struct strbuf path = STRBUF_INIT;1323int result;13241325files_ref_path(refs, &path, newrefname);1326 result =remove_empty_directories(&path);1327strbuf_release(&path);13281329if(result) {1330error("Directory not empty:%s", newrefname);1331goto rollback;1332}1333}else{1334error("unable to delete existing%s", newrefname);1335goto rollback;1336}1337}13381339if(log &&rename_tmp_log(refs, newrefname))1340goto rollback;13411342 logmoved = log;13431344 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1345 REF_NODEREF, NULL, &err);1346if(!lock) {1347error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1348strbuf_release(&err);1349goto rollback;1350}1351oidcpy(&lock->old_oid, &orig_oid);13521353if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1354commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1355error("unable to write current sha1 into%s:%s", newrefname, err.buf);1356strbuf_release(&err);1357goto rollback;1358}13591360 ret =0;1361goto out;13621363 rollback:1364 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1365 REF_NODEREF, NULL, &err);1366if(!lock) {1367error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1368strbuf_release(&err);1369goto rollbacklog;1370}13711372 flag = log_all_ref_updates;1373 log_all_ref_updates = LOG_REFS_NONE;1374if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1375commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1376error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1377strbuf_release(&err);1378}1379 log_all_ref_updates = flag;13801381 rollbacklog:1382if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1383error("unable to restore logfile%sfrom%s:%s",1384 oldrefname, newrefname,strerror(errno));1385if(!logmoved && log &&1386rename(tmp_renamed_log.buf, sb_oldref.buf))1387error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1388 oldrefname,strerror(errno));1389 ret =1;1390 out:1391strbuf_release(&sb_newref);1392strbuf_release(&sb_oldref);1393strbuf_release(&tmp_renamed_log);13941395return ret;1396}13971398static intclose_ref_gently(struct ref_lock *lock)1399{1400if(close_lock_file_gently(&lock->lk))1401return-1;1402return0;1403}14041405static intcommit_ref(struct ref_lock *lock)1406{1407char*path =get_locked_file_path(&lock->lk);1408struct stat st;14091410if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1411/*1412 * There is a directory at the path we want to rename1413 * the lockfile to. Hopefully it is empty; try to1414 * delete it.1415 */1416size_t len =strlen(path);1417struct strbuf sb_path = STRBUF_INIT;14181419strbuf_attach(&sb_path, path, len, len);14201421/*1422 * If this fails, commit_lock_file() will also fail1423 * and will report the problem.1424 */1425remove_empty_directories(&sb_path);1426strbuf_release(&sb_path);1427}else{1428free(path);1429}14301431if(commit_lock_file(&lock->lk))1432return-1;1433return0;1434}14351436static intopen_or_create_logfile(const char*path,void*cb)1437{1438int*fd = cb;14391440*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1441return(*fd <0) ? -1:0;1442}14431444/*1445 * Create a reflog for a ref. If force_create = 0, only create the1446 * reflog for certain refs (those for which should_autocreate_reflog1447 * returns non-zero). Otherwise, create it regardless of the reference1448 * name. If the logfile already existed or was created, return 0 and1449 * set *logfd to the file descriptor opened for appending to the file.1450 * If no logfile exists and we decided not to create one, return 0 and1451 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1452 * return -1.1453 */1454static intlog_ref_setup(struct files_ref_store *refs,1455const char*refname,int force_create,1456int*logfd,struct strbuf *err)1457{1458struct strbuf logfile_sb = STRBUF_INIT;1459char*logfile;14601461files_reflog_path(refs, &logfile_sb, refname);1462 logfile =strbuf_detach(&logfile_sb, NULL);14631464if(force_create ||should_autocreate_reflog(refname)) {1465if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1466if(errno == ENOENT)1467strbuf_addf(err,"unable to create directory for '%s': "1468"%s", logfile,strerror(errno));1469else if(errno == EISDIR)1470strbuf_addf(err,"there are still logs under '%s'",1471 logfile);1472else1473strbuf_addf(err,"unable to append to '%s':%s",1474 logfile,strerror(errno));14751476goto error;1477}1478}else{1479*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1480if(*logfd <0) {1481if(errno == ENOENT || errno == EISDIR) {1482/*1483 * The logfile doesn't already exist,1484 * but that is not an error; it only1485 * means that we won't write log1486 * entries to it.1487 */1488;1489}else{1490strbuf_addf(err,"unable to append to '%s':%s",1491 logfile,strerror(errno));1492goto error;1493}1494}1495}14961497if(*logfd >=0)1498adjust_shared_perm(logfile);14991500free(logfile);1501return0;15021503error:1504free(logfile);1505return-1;1506}15071508static intfiles_create_reflog(struct ref_store *ref_store,1509const char*refname,int force_create,1510struct strbuf *err)1511{1512struct files_ref_store *refs =1513files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1514int fd;15151516if(log_ref_setup(refs, refname, force_create, &fd, err))1517return-1;15181519if(fd >=0)1520close(fd);15211522return0;1523}15241525static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1526const struct object_id *new_oid,1527const char*committer,const char*msg)1528{1529int msglen, written;1530unsigned maxlen, len;1531char*logrec;15321533 msglen = msg ?strlen(msg) :0;1534 maxlen =strlen(committer) + msglen +100;1535 logrec =xmalloc(maxlen);1536 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1537oid_to_hex(old_oid),1538oid_to_hex(new_oid),1539 committer);1540if(msglen)1541 len +=copy_reflog_msg(logrec + len -1, msg) -1;15421543 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1544free(logrec);1545if(written != len)1546return-1;15471548return0;1549}15501551static intfiles_log_ref_write(struct files_ref_store *refs,1552const char*refname,const struct object_id *old_oid,1553const struct object_id *new_oid,const char*msg,1554int flags,struct strbuf *err)1555{1556int logfd, result;15571558if(log_all_ref_updates == LOG_REFS_UNSET)1559 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15601561 result =log_ref_setup(refs, refname,1562 flags & REF_FORCE_CREATE_REFLOG,1563&logfd, err);15641565if(result)1566return result;15671568if(logfd <0)1569return0;1570 result =log_ref_write_fd(logfd, old_oid, new_oid,1571git_committer_info(0), msg);1572if(result) {1573struct strbuf sb = STRBUF_INIT;1574int save_errno = errno;15751576files_reflog_path(refs, &sb, refname);1577strbuf_addf(err,"unable to append to '%s':%s",1578 sb.buf,strerror(save_errno));1579strbuf_release(&sb);1580close(logfd);1581return-1;1582}1583if(close(logfd)) {1584struct strbuf sb = STRBUF_INIT;1585int save_errno = errno;15861587files_reflog_path(refs, &sb, refname);1588strbuf_addf(err,"unable to append to '%s':%s",1589 sb.buf,strerror(save_errno));1590strbuf_release(&sb);1591return-1;1592}1593return0;1594}15951596/*1597 * Write sha1 into the open lockfile, then close the lockfile. On1598 * errors, rollback the lockfile, fill in *err and1599 * return -1.1600 */1601static intwrite_ref_to_lockfile(struct ref_lock *lock,1602const struct object_id *oid,struct strbuf *err)1603{1604static char term ='\n';1605struct object *o;1606int fd;16071608 o =parse_object(oid);1609if(!o) {1610strbuf_addf(err,1611"trying to write ref '%s' with nonexistent object%s",1612 lock->ref_name,oid_to_hex(oid));1613unlock_ref(lock);1614return-1;1615}1616if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1617strbuf_addf(err,1618"trying to write non-commit object%sto branch '%s'",1619oid_to_hex(oid), lock->ref_name);1620unlock_ref(lock);1621return-1;1622}1623 fd =get_lock_file_fd(&lock->lk);1624if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1625write_in_full(fd, &term,1) !=1||1626close_ref_gently(lock) <0) {1627strbuf_addf(err,1628"couldn't write '%s'",get_lock_file_path(&lock->lk));1629unlock_ref(lock);1630return-1;1631}1632return0;1633}16341635/*1636 * Commit a change to a loose reference that has already been written1637 * to the loose reference lockfile. Also update the reflogs if1638 * necessary, using the specified lockmsg (which can be NULL).1639 */1640static intcommit_ref_update(struct files_ref_store *refs,1641struct ref_lock *lock,1642const struct object_id *oid,const char*logmsg,1643struct strbuf *err)1644{1645files_assert_main_repository(refs,"commit_ref_update");16461647clear_loose_ref_cache(refs);1648if(files_log_ref_write(refs, lock->ref_name,1649&lock->old_oid, oid,1650 logmsg,0, err)) {1651char*old_msg =strbuf_detach(err, NULL);1652strbuf_addf(err,"cannot update the ref '%s':%s",1653 lock->ref_name, old_msg);1654free(old_msg);1655unlock_ref(lock);1656return-1;1657}16581659if(strcmp(lock->ref_name,"HEAD") !=0) {1660/*1661 * Special hack: If a branch is updated directly and HEAD1662 * points to it (may happen on the remote side of a push1663 * for example) then logically the HEAD reflog should be1664 * updated too.1665 * A generic solution implies reverse symref information,1666 * but finding all symrefs pointing to the given branch1667 * would be rather costly for this rare event (the direct1668 * update of a branch) to be worth it. So let's cheat and1669 * check with HEAD only which should cover 99% of all usage1670 * scenarios (even 100% of the default ones).1671 */1672struct object_id head_oid;1673int head_flag;1674const char*head_ref;16751676 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1677 RESOLVE_REF_READING,1678 head_oid.hash, &head_flag);1679if(head_ref && (head_flag & REF_ISSYMREF) &&1680!strcmp(head_ref, lock->ref_name)) {1681struct strbuf log_err = STRBUF_INIT;1682if(files_log_ref_write(refs,"HEAD",1683&lock->old_oid, oid,1684 logmsg,0, &log_err)) {1685error("%s", log_err.buf);1686strbuf_release(&log_err);1687}1688}1689}16901691if(commit_ref(lock)) {1692strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1693unlock_ref(lock);1694return-1;1695}16961697unlock_ref(lock);1698return0;1699}17001701static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1702{1703int ret = -1;1704#ifndef NO_SYMLINK_HEAD1705char*ref_path =get_locked_file_path(&lock->lk);1706unlink(ref_path);1707 ret =symlink(target, ref_path);1708free(ref_path);17091710if(ret)1711fprintf(stderr,"no symlink - falling back to symbolic ref\n");1712#endif1713return ret;1714}17151716static voidupdate_symref_reflog(struct files_ref_store *refs,1717struct ref_lock *lock,const char*refname,1718const char*target,const char*logmsg)1719{1720struct strbuf err = STRBUF_INIT;1721struct object_id new_oid;1722if(logmsg &&1723!refs_read_ref_full(&refs->base, target,1724 RESOLVE_REF_READING, new_oid.hash, NULL) &&1725files_log_ref_write(refs, refname, &lock->old_oid,1726&new_oid, logmsg,0, &err)) {1727error("%s", err.buf);1728strbuf_release(&err);1729}1730}17311732static intcreate_symref_locked(struct files_ref_store *refs,1733struct ref_lock *lock,const char*refname,1734const char*target,const char*logmsg)1735{1736if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1737update_symref_reflog(refs, lock, refname, target, logmsg);1738return0;1739}17401741if(!fdopen_lock_file(&lock->lk,"w"))1742returnerror("unable to fdopen%s:%s",1743 lock->lk.tempfile->filename.buf,strerror(errno));17441745update_symref_reflog(refs, lock, refname, target, logmsg);17461747/* no error check; commit_ref will check ferror */1748fprintf(lock->lk.tempfile->fp,"ref:%s\n", target);1749if(commit_ref(lock) <0)1750returnerror("unable to write symref for%s:%s", refname,1751strerror(errno));1752return0;1753}17541755static intfiles_create_symref(struct ref_store *ref_store,1756const char*refname,const char*target,1757const char*logmsg)1758{1759struct files_ref_store *refs =1760files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1761struct strbuf err = STRBUF_INIT;1762struct ref_lock *lock;1763int ret;17641765 lock =lock_ref_sha1_basic(refs, refname, NULL,1766 NULL, NULL, REF_NODEREF, NULL,1767&err);1768if(!lock) {1769error("%s", err.buf);1770strbuf_release(&err);1771return-1;1772}17731774 ret =create_symref_locked(refs, lock, refname, target, logmsg);1775unlock_ref(lock);1776return ret;1777}17781779static intfiles_reflog_exists(struct ref_store *ref_store,1780const char*refname)1781{1782struct files_ref_store *refs =1783files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1784struct strbuf sb = STRBUF_INIT;1785struct stat st;1786int ret;17871788files_reflog_path(refs, &sb, refname);1789 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1790strbuf_release(&sb);1791return ret;1792}17931794static intfiles_delete_reflog(struct ref_store *ref_store,1795const char*refname)1796{1797struct files_ref_store *refs =1798files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1799struct strbuf sb = STRBUF_INIT;1800int ret;18011802files_reflog_path(refs, &sb, refname);1803 ret =remove_path(sb.buf);1804strbuf_release(&sb);1805return ret;1806}18071808static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1809{1810struct object_id ooid, noid;1811char*email_end, *message;1812 timestamp_t timestamp;1813int tz;1814const char*p = sb->buf;18151816/* old SP new SP name <email> SP time TAB msg LF */1817if(!sb->len || sb->buf[sb->len -1] !='\n'||1818parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1819parse_oid_hex(p, &noid, &p) || *p++ !=' '||1820!(email_end =strchr(p,'>')) ||1821 email_end[1] !=' '||1822!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1823!message || message[0] !=' '||1824(message[1] !='+'&& message[1] !='-') ||1825!isdigit(message[2]) || !isdigit(message[3]) ||1826!isdigit(message[4]) || !isdigit(message[5]))1827return0;/* corrupt? */1828 email_end[1] ='\0';1829 tz =strtol(message +1, NULL,10);1830if(message[6] !='\t')1831 message +=6;1832else1833 message +=7;1834returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1835}18361837static char*find_beginning_of_line(char*bob,char*scan)1838{1839while(bob < scan && *(--scan) !='\n')1840;/* keep scanning backwards */1841/*1842 * Return either beginning of the buffer, or LF at the end of1843 * the previous line.1844 */1845return scan;1846}18471848static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1849const char*refname,1850 each_reflog_ent_fn fn,1851void*cb_data)1852{1853struct files_ref_store *refs =1854files_downcast(ref_store, REF_STORE_READ,1855"for_each_reflog_ent_reverse");1856struct strbuf sb = STRBUF_INIT;1857FILE*logfp;1858long pos;1859int ret =0, at_tail =1;18601861files_reflog_path(refs, &sb, refname);1862 logfp =fopen(sb.buf,"r");1863strbuf_release(&sb);1864if(!logfp)1865return-1;18661867/* Jump to the end */1868if(fseek(logfp,0, SEEK_END) <0)1869 ret =error("cannot seek back reflog for%s:%s",1870 refname,strerror(errno));1871 pos =ftell(logfp);1872while(!ret &&0< pos) {1873int cnt;1874size_t nread;1875char buf[BUFSIZ];1876char*endp, *scanp;18771878/* Fill next block from the end */1879 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1880if(fseek(logfp, pos - cnt, SEEK_SET)) {1881 ret =error("cannot seek back reflog for%s:%s",1882 refname,strerror(errno));1883break;1884}1885 nread =fread(buf, cnt,1, logfp);1886if(nread !=1) {1887 ret =error("cannot read%dbytes from reflog for%s:%s",1888 cnt, refname,strerror(errno));1889break;1890}1891 pos -= cnt;18921893 scanp = endp = buf + cnt;1894if(at_tail && scanp[-1] =='\n')1895/* Looking at the final LF at the end of the file */1896 scanp--;1897 at_tail =0;18981899while(buf < scanp) {1900/*1901 * terminating LF of the previous line, or the beginning1902 * of the buffer.1903 */1904char*bp;19051906 bp =find_beginning_of_line(buf, scanp);19071908if(*bp =='\n') {1909/*1910 * The newline is the end of the previous line,1911 * so we know we have complete line starting1912 * at (bp + 1). Prefix it onto any prior data1913 * we collected for the line and process it.1914 */1915strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1916 scanp = bp;1917 endp = bp +1;1918 ret =show_one_reflog_ent(&sb, fn, cb_data);1919strbuf_reset(&sb);1920if(ret)1921break;1922}else if(!pos) {1923/*1924 * We are at the start of the buffer, and the1925 * start of the file; there is no previous1926 * line, and we have everything for this one.1927 * Process it, and we can end the loop.1928 */1929strbuf_splice(&sb,0,0, buf, endp - buf);1930 ret =show_one_reflog_ent(&sb, fn, cb_data);1931strbuf_reset(&sb);1932break;1933}19341935if(bp == buf) {1936/*1937 * We are at the start of the buffer, and there1938 * is more file to read backwards. Which means1939 * we are in the middle of a line. Note that we1940 * may get here even if *bp was a newline; that1941 * just means we are at the exact end of the1942 * previous line, rather than some spot in the1943 * middle.1944 *1945 * Save away what we have to be combined with1946 * the data from the next read.1947 */1948strbuf_splice(&sb,0,0, buf, endp - buf);1949break;1950}1951}19521953}1954if(!ret && sb.len)1955die("BUG: reverse reflog parser had leftover data");19561957fclose(logfp);1958strbuf_release(&sb);1959return ret;1960}19611962static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1963const char*refname,1964 each_reflog_ent_fn fn,void*cb_data)1965{1966struct files_ref_store *refs =1967files_downcast(ref_store, REF_STORE_READ,1968"for_each_reflog_ent");1969FILE*logfp;1970struct strbuf sb = STRBUF_INIT;1971int ret =0;19721973files_reflog_path(refs, &sb, refname);1974 logfp =fopen(sb.buf,"r");1975strbuf_release(&sb);1976if(!logfp)1977return-1;19781979while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1980 ret =show_one_reflog_ent(&sb, fn, cb_data);1981fclose(logfp);1982strbuf_release(&sb);1983return ret;1984}19851986struct files_reflog_iterator {1987struct ref_iterator base;19881989struct ref_store *ref_store;1990struct dir_iterator *dir_iterator;1991struct object_id oid;1992};19931994static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1995{1996struct files_reflog_iterator *iter =1997(struct files_reflog_iterator *)ref_iterator;1998struct dir_iterator *diter = iter->dir_iterator;1999int ok;20002001while((ok =dir_iterator_advance(diter)) == ITER_OK) {2002int flags;20032004if(!S_ISREG(diter->st.st_mode))2005continue;2006if(diter->basename[0] =='.')2007continue;2008if(ends_with(diter->basename,".lock"))2009continue;20102011if(refs_read_ref_full(iter->ref_store,2012 diter->relative_path,0,2013 iter->oid.hash, &flags)) {2014error("bad ref for%s", diter->path.buf);2015continue;2016}20172018 iter->base.refname = diter->relative_path;2019 iter->base.oid = &iter->oid;2020 iter->base.flags = flags;2021return ITER_OK;2022}20232024 iter->dir_iterator = NULL;2025if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2026 ok = ITER_ERROR;2027return ok;2028}20292030static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2031struct object_id *peeled)2032{2033die("BUG: ref_iterator_peel() called for reflog_iterator");2034}20352036static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2037{2038struct files_reflog_iterator *iter =2039(struct files_reflog_iterator *)ref_iterator;2040int ok = ITER_DONE;20412042if(iter->dir_iterator)2043 ok =dir_iterator_abort(iter->dir_iterator);20442045base_ref_iterator_free(ref_iterator);2046return ok;2047}20482049static struct ref_iterator_vtable files_reflog_iterator_vtable = {2050 files_reflog_iterator_advance,2051 files_reflog_iterator_peel,2052 files_reflog_iterator_abort2053};20542055static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2056{2057struct files_ref_store *refs =2058files_downcast(ref_store, REF_STORE_READ,2059"reflog_iterator_begin");2060struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2061struct ref_iterator *ref_iterator = &iter->base;2062struct strbuf sb = STRBUF_INIT;20632064base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2065files_reflog_path(refs, &sb, NULL);2066 iter->dir_iterator =dir_iterator_begin(sb.buf);2067 iter->ref_store = ref_store;2068strbuf_release(&sb);2069return ref_iterator;2070}20712072/*2073 * If update is a direct update of head_ref (the reference pointed to2074 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2075 */2076static intsplit_head_update(struct ref_update *update,2077struct ref_transaction *transaction,2078const char*head_ref,2079struct string_list *affected_refnames,2080struct strbuf *err)2081{2082struct string_list_item *item;2083struct ref_update *new_update;20842085if((update->flags & REF_LOG_ONLY) ||2086(update->flags & REF_ISPRUNING) ||2087(update->flags & REF_UPDATE_VIA_HEAD))2088return0;20892090if(strcmp(update->refname, head_ref))2091return0;20922093/*2094 * First make sure that HEAD is not already in the2095 * transaction. This insertion is O(N) in the transaction2096 * size, but it happens at most once per transaction.2097 */2098 item =string_list_insert(affected_refnames,"HEAD");2099if(item->util) {2100/* An entry already existed */2101strbuf_addf(err,2102"multiple updates for 'HEAD' (including one "2103"via its referent '%s') are not allowed",2104 update->refname);2105return TRANSACTION_NAME_CONFLICT;2106}21072108 new_update =ref_transaction_add_update(2109 transaction,"HEAD",2110 update->flags | REF_LOG_ONLY | REF_NODEREF,2111 update->new_oid.hash, update->old_oid.hash,2112 update->msg);21132114 item->util = new_update;21152116return0;2117}21182119/*2120 * update is for a symref that points at referent and doesn't have2121 * REF_NODEREF set. Split it into two updates:2122 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2123 * - A new, separate update for the referent reference2124 * Note that the new update will itself be subject to splitting when2125 * the iteration gets to it.2126 */2127static intsplit_symref_update(struct files_ref_store *refs,2128struct ref_update *update,2129const char*referent,2130struct ref_transaction *transaction,2131struct string_list *affected_refnames,2132struct strbuf *err)2133{2134struct string_list_item *item;2135struct ref_update *new_update;2136unsigned int new_flags;21372138/*2139 * First make sure that referent is not already in the2140 * transaction. This insertion is O(N) in the transaction2141 * size, but it happens at most once per symref in a2142 * transaction.2143 */2144 item =string_list_insert(affected_refnames, referent);2145if(item->util) {2146/* An entry already existed */2147strbuf_addf(err,2148"multiple updates for '%s' (including one "2149"via symref '%s') are not allowed",2150 referent, update->refname);2151return TRANSACTION_NAME_CONFLICT;2152}21532154 new_flags = update->flags;2155if(!strcmp(update->refname,"HEAD")) {2156/*2157 * Record that the new update came via HEAD, so that2158 * when we process it, split_head_update() doesn't try2159 * to add another reflog update for HEAD. Note that2160 * this bit will be propagated if the new_update2161 * itself needs to be split.2162 */2163 new_flags |= REF_UPDATE_VIA_HEAD;2164}21652166 new_update =ref_transaction_add_update(2167 transaction, referent, new_flags,2168 update->new_oid.hash, update->old_oid.hash,2169 update->msg);21702171 new_update->parent_update = update;21722173/*2174 * Change the symbolic ref update to log only. Also, it2175 * doesn't need to check its old SHA-1 value, as that will be2176 * done when new_update is processed.2177 */2178 update->flags |= REF_LOG_ONLY | REF_NODEREF;2179 update->flags &= ~REF_HAVE_OLD;21802181 item->util = new_update;21822183return0;2184}21852186/*2187 * Return the refname under which update was originally requested.2188 */2189static const char*original_update_refname(struct ref_update *update)2190{2191while(update->parent_update)2192 update = update->parent_update;21932194return update->refname;2195}21962197/*2198 * Check whether the REF_HAVE_OLD and old_oid values stored in update2199 * are consistent with oid, which is the reference's current value. If2200 * everything is OK, return 0; otherwise, write an error message to2201 * err and return -1.2202 */2203static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2204struct strbuf *err)2205{2206if(!(update->flags & REF_HAVE_OLD) ||2207!oidcmp(oid, &update->old_oid))2208return0;22092210if(is_null_oid(&update->old_oid))2211strbuf_addf(err,"cannot lock ref '%s': "2212"reference already exists",2213original_update_refname(update));2214else if(is_null_oid(oid))2215strbuf_addf(err,"cannot lock ref '%s': "2216"reference is missing but expected%s",2217original_update_refname(update),2218oid_to_hex(&update->old_oid));2219else2220strbuf_addf(err,"cannot lock ref '%s': "2221"is at%sbut expected%s",2222original_update_refname(update),2223oid_to_hex(oid),2224oid_to_hex(&update->old_oid));22252226return-1;2227}22282229/*2230 * Prepare for carrying out update:2231 * - Lock the reference referred to by update.2232 * - Read the reference under lock.2233 * - Check that its old SHA-1 value (if specified) is correct, and in2234 * any case record it in update->lock->old_oid for later use when2235 * writing the reflog.2236 * - If it is a symref update without REF_NODEREF, split it up into a2237 * REF_LOG_ONLY update of the symref and add a separate update for2238 * the referent to transaction.2239 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2240 * update of HEAD.2241 */2242static intlock_ref_for_update(struct files_ref_store *refs,2243struct ref_update *update,2244struct ref_transaction *transaction,2245const char*head_ref,2246struct string_list *affected_refnames,2247struct strbuf *err)2248{2249struct strbuf referent = STRBUF_INIT;2250int mustexist = (update->flags & REF_HAVE_OLD) &&2251!is_null_oid(&update->old_oid);2252int ret;2253struct ref_lock *lock;22542255files_assert_main_repository(refs,"lock_ref_for_update");22562257if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2258 update->flags |= REF_DELETING;22592260if(head_ref) {2261 ret =split_head_update(update, transaction, head_ref,2262 affected_refnames, err);2263if(ret)2264return ret;2265}22662267 ret =lock_raw_ref(refs, update->refname, mustexist,2268 affected_refnames, NULL,2269&lock, &referent,2270&update->type, err);2271if(ret) {2272char*reason;22732274 reason =strbuf_detach(err, NULL);2275strbuf_addf(err,"cannot lock ref '%s':%s",2276original_update_refname(update), reason);2277free(reason);2278return ret;2279}22802281 update->backend_data = lock;22822283if(update->type & REF_ISSYMREF) {2284if(update->flags & REF_NODEREF) {2285/*2286 * We won't be reading the referent as part of2287 * the transaction, so we have to read it here2288 * to record and possibly check old_sha1:2289 */2290if(refs_read_ref_full(&refs->base,2291 referent.buf,0,2292 lock->old_oid.hash, NULL)) {2293if(update->flags & REF_HAVE_OLD) {2294strbuf_addf(err,"cannot lock ref '%s': "2295"error reading reference",2296original_update_refname(update));2297return-1;2298}2299}else if(check_old_oid(update, &lock->old_oid, err)) {2300return TRANSACTION_GENERIC_ERROR;2301}2302}else{2303/*2304 * Create a new update for the reference this2305 * symref is pointing at. Also, we will record2306 * and verify old_sha1 for this update as part2307 * of processing the split-off update, so we2308 * don't have to do it here.2309 */2310 ret =split_symref_update(refs, update,2311 referent.buf, transaction,2312 affected_refnames, err);2313if(ret)2314return ret;2315}2316}else{2317struct ref_update *parent_update;23182319if(check_old_oid(update, &lock->old_oid, err))2320return TRANSACTION_GENERIC_ERROR;23212322/*2323 * If this update is happening indirectly because of a2324 * symref update, record the old SHA-1 in the parent2325 * update:2326 */2327for(parent_update = update->parent_update;2328 parent_update;2329 parent_update = parent_update->parent_update) {2330struct ref_lock *parent_lock = parent_update->backend_data;2331oidcpy(&parent_lock->old_oid, &lock->old_oid);2332}2333}23342335if((update->flags & REF_HAVE_NEW) &&2336!(update->flags & REF_DELETING) &&2337!(update->flags & REF_LOG_ONLY)) {2338if(!(update->type & REF_ISSYMREF) &&2339!oidcmp(&lock->old_oid, &update->new_oid)) {2340/*2341 * The reference already has the desired2342 * value, so we don't need to write it.2343 */2344}else if(write_ref_to_lockfile(lock, &update->new_oid,2345 err)) {2346char*write_err =strbuf_detach(err, NULL);23472348/*2349 * The lock was freed upon failure of2350 * write_ref_to_lockfile():2351 */2352 update->backend_data = NULL;2353strbuf_addf(err,2354"cannot update ref '%s':%s",2355 update->refname, write_err);2356free(write_err);2357return TRANSACTION_GENERIC_ERROR;2358}else{2359 update->flags |= REF_NEEDS_COMMIT;2360}2361}2362if(!(update->flags & REF_NEEDS_COMMIT)) {2363/*2364 * We didn't call write_ref_to_lockfile(), so2365 * the lockfile is still open. Close it to2366 * free up the file descriptor:2367 */2368if(close_ref_gently(lock)) {2369strbuf_addf(err,"couldn't close '%s.lock'",2370 update->refname);2371return TRANSACTION_GENERIC_ERROR;2372}2373}2374return0;2375}23762377/*2378 * Unlock any references in `transaction` that are still locked, and2379 * mark the transaction closed.2380 */2381static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2382{2383size_t i;23842385for(i =0; i < transaction->nr; i++) {2386struct ref_update *update = transaction->updates[i];2387struct ref_lock *lock = update->backend_data;23882389if(lock) {2390unlock_ref(lock);2391 update->backend_data = NULL;2392}2393}23942395 transaction->state = REF_TRANSACTION_CLOSED;2396}23972398static intfiles_transaction_prepare(struct ref_store *ref_store,2399struct ref_transaction *transaction,2400struct strbuf *err)2401{2402struct files_ref_store *refs =2403files_downcast(ref_store, REF_STORE_WRITE,2404"ref_transaction_prepare");2405size_t i;2406int ret =0;2407struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2408char*head_ref = NULL;2409int head_type;2410struct object_id head_oid;24112412assert(err);24132414if(!transaction->nr)2415goto cleanup;24162417/*2418 * Fail if a refname appears more than once in the2419 * transaction. (If we end up splitting up any updates using2420 * split_symref_update() or split_head_update(), those2421 * functions will check that the new updates don't have the2422 * same refname as any existing ones.)2423 */2424for(i =0; i < transaction->nr; i++) {2425struct ref_update *update = transaction->updates[i];2426struct string_list_item *item =2427string_list_append(&affected_refnames, update->refname);24282429/*2430 * We store a pointer to update in item->util, but at2431 * the moment we never use the value of this field2432 * except to check whether it is non-NULL.2433 */2434 item->util = update;2435}2436string_list_sort(&affected_refnames);2437if(ref_update_reject_duplicates(&affected_refnames, err)) {2438 ret = TRANSACTION_GENERIC_ERROR;2439goto cleanup;2440}24412442/*2443 * Special hack: If a branch is updated directly and HEAD2444 * points to it (may happen on the remote side of a push2445 * for example) then logically the HEAD reflog should be2446 * updated too.2447 *2448 * A generic solution would require reverse symref lookups,2449 * but finding all symrefs pointing to a given branch would be2450 * rather costly for this rare event (the direct update of a2451 * branch) to be worth it. So let's cheat and check with HEAD2452 * only, which should cover 99% of all usage scenarios (even2453 * 100% of the default ones).2454 *2455 * So if HEAD is a symbolic reference, then record the name of2456 * the reference that it points to. If we see an update of2457 * head_ref within the transaction, then split_head_update()2458 * arranges for the reflog of HEAD to be updated, too.2459 */2460 head_ref =refs_resolve_refdup(ref_store,"HEAD",2461 RESOLVE_REF_NO_RECURSE,2462 head_oid.hash, &head_type);24632464if(head_ref && !(head_type & REF_ISSYMREF)) {2465FREE_AND_NULL(head_ref);2466}24672468/*2469 * Acquire all locks, verify old values if provided, check2470 * that new values are valid, and write new values to the2471 * lockfiles, ready to be activated. Only keep one lockfile2472 * open at a time to avoid running out of file descriptors.2473 * Note that lock_ref_for_update() might append more updates2474 * to the transaction.2475 */2476for(i =0; i < transaction->nr; i++) {2477struct ref_update *update = transaction->updates[i];24782479 ret =lock_ref_for_update(refs, update, transaction,2480 head_ref, &affected_refnames, err);2481if(ret)2482break;2483}24842485cleanup:2486free(head_ref);2487string_list_clear(&affected_refnames,0);24882489if(ret)2490files_transaction_cleanup(transaction);2491else2492 transaction->state = REF_TRANSACTION_PREPARED;24932494return ret;2495}24962497static intfiles_transaction_finish(struct ref_store *ref_store,2498struct ref_transaction *transaction,2499struct strbuf *err)2500{2501struct files_ref_store *refs =2502files_downcast(ref_store,0,"ref_transaction_finish");2503size_t i;2504int ret =0;2505struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2506struct string_list_item *ref_to_delete;2507struct strbuf sb = STRBUF_INIT;25082509assert(err);25102511if(!transaction->nr) {2512 transaction->state = REF_TRANSACTION_CLOSED;2513return0;2514}25152516/* Perform updates first so live commits remain referenced */2517for(i =0; i < transaction->nr; i++) {2518struct ref_update *update = transaction->updates[i];2519struct ref_lock *lock = update->backend_data;25202521if(update->flags & REF_NEEDS_COMMIT ||2522 update->flags & REF_LOG_ONLY) {2523if(files_log_ref_write(refs,2524 lock->ref_name,2525&lock->old_oid,2526&update->new_oid,2527 update->msg, update->flags,2528 err)) {2529char*old_msg =strbuf_detach(err, NULL);25302531strbuf_addf(err,"cannot update the ref '%s':%s",2532 lock->ref_name, old_msg);2533free(old_msg);2534unlock_ref(lock);2535 update->backend_data = NULL;2536 ret = TRANSACTION_GENERIC_ERROR;2537goto cleanup;2538}2539}2540if(update->flags & REF_NEEDS_COMMIT) {2541clear_loose_ref_cache(refs);2542if(commit_ref(lock)) {2543strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2544unlock_ref(lock);2545 update->backend_data = NULL;2546 ret = TRANSACTION_GENERIC_ERROR;2547goto cleanup;2548}2549}2550}2551/* Perform deletes now that updates are safely completed */2552for(i =0; i < transaction->nr; i++) {2553struct ref_update *update = transaction->updates[i];2554struct ref_lock *lock = update->backend_data;25552556if(update->flags & REF_DELETING &&2557!(update->flags & REF_LOG_ONLY)) {2558if(!(update->type & REF_ISPACKED) ||2559 update->type & REF_ISSYMREF) {2560/* It is a loose reference. */2561strbuf_reset(&sb);2562files_ref_path(refs, &sb, lock->ref_name);2563if(unlink_or_msg(sb.buf, err)) {2564 ret = TRANSACTION_GENERIC_ERROR;2565goto cleanup;2566}2567 update->flags |= REF_DELETED_LOOSE;2568}25692570if(!(update->flags & REF_ISPRUNING))2571string_list_append(&refs_to_delete,2572 lock->ref_name);2573}2574}25752576if(packed_refs_lock(refs->packed_ref_store,0, err)) {2577 ret = TRANSACTION_GENERIC_ERROR;2578goto cleanup;2579}25802581if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2582 ret = TRANSACTION_GENERIC_ERROR;2583packed_refs_unlock(refs->packed_ref_store);2584goto cleanup;2585}25862587packed_refs_unlock(refs->packed_ref_store);25882589/* Delete the reflogs of any references that were deleted: */2590for_each_string_list_item(ref_to_delete, &refs_to_delete) {2591strbuf_reset(&sb);2592files_reflog_path(refs, &sb, ref_to_delete->string);2593if(!unlink_or_warn(sb.buf))2594try_remove_empty_parents(refs, ref_to_delete->string,2595 REMOVE_EMPTY_PARENTS_REFLOG);2596}25972598clear_loose_ref_cache(refs);25992600cleanup:2601files_transaction_cleanup(transaction);26022603for(i =0; i < transaction->nr; i++) {2604struct ref_update *update = transaction->updates[i];26052606if(update->flags & REF_DELETED_LOOSE) {2607/*2608 * The loose reference was deleted. Delete any2609 * empty parent directories. (Note that this2610 * can only work because we have already2611 * removed the lockfile.)2612 */2613try_remove_empty_parents(refs, update->refname,2614 REMOVE_EMPTY_PARENTS_REF);2615}2616}26172618strbuf_release(&sb);2619string_list_clear(&refs_to_delete,0);2620return ret;2621}26222623static intfiles_transaction_abort(struct ref_store *ref_store,2624struct ref_transaction *transaction,2625struct strbuf *err)2626{2627files_transaction_cleanup(transaction);2628return0;2629}26302631static intref_present(const char*refname,2632const struct object_id *oid,int flags,void*cb_data)2633{2634struct string_list *affected_refnames = cb_data;26352636returnstring_list_has_string(affected_refnames, refname);2637}26382639static intfiles_initial_transaction_commit(struct ref_store *ref_store,2640struct ref_transaction *transaction,2641struct strbuf *err)2642{2643struct files_ref_store *refs =2644files_downcast(ref_store, REF_STORE_WRITE,2645"initial_ref_transaction_commit");2646size_t i;2647int ret =0;2648struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26492650assert(err);26512652if(transaction->state != REF_TRANSACTION_OPEN)2653die("BUG: commit called for transaction that is not open");26542655/* Fail if a refname appears more than once in the transaction: */2656for(i =0; i < transaction->nr; i++)2657string_list_append(&affected_refnames,2658 transaction->updates[i]->refname);2659string_list_sort(&affected_refnames);2660if(ref_update_reject_duplicates(&affected_refnames, err)) {2661 ret = TRANSACTION_GENERIC_ERROR;2662goto cleanup;2663}26642665/*2666 * It's really undefined to call this function in an active2667 * repository or when there are existing references: we are2668 * only locking and changing packed-refs, so (1) any2669 * simultaneous processes might try to change a reference at2670 * the same time we do, and (2) any existing loose versions of2671 * the references that we are setting would have precedence2672 * over our values. But some remote helpers create the remote2673 * "HEAD" and "master" branches before calling this function,2674 * so here we really only check that none of the references2675 * that we are creating already exists.2676 */2677if(refs_for_each_rawref(&refs->base, ref_present,2678&affected_refnames))2679die("BUG: initial ref transaction called with existing refs");26802681for(i =0; i < transaction->nr; i++) {2682struct ref_update *update = transaction->updates[i];26832684if((update->flags & REF_HAVE_OLD) &&2685!is_null_oid(&update->old_oid))2686die("BUG: initial ref transaction with old_sha1 set");2687if(refs_verify_refname_available(&refs->base, update->refname,2688&affected_refnames, NULL,2689 err)) {2690 ret = TRANSACTION_NAME_CONFLICT;2691goto cleanup;2692}2693}26942695if(packed_refs_lock(refs->packed_ref_store,0, err)) {2696 ret = TRANSACTION_GENERIC_ERROR;2697goto cleanup;2698}26992700for(i =0; i < transaction->nr; i++) {2701struct ref_update *update = transaction->updates[i];27022703if((update->flags & REF_HAVE_NEW) &&2704!is_null_oid(&update->new_oid))2705add_packed_ref(refs->packed_ref_store, update->refname,2706&update->new_oid);2707}27082709if(commit_packed_refs(refs->packed_ref_store, err)) {2710 ret = TRANSACTION_GENERIC_ERROR;2711goto cleanup;2712}27132714cleanup:2715packed_refs_unlock(refs->packed_ref_store);2716 transaction->state = REF_TRANSACTION_CLOSED;2717string_list_clear(&affected_refnames,0);2718return ret;2719}27202721struct expire_reflog_cb {2722unsigned int flags;2723 reflog_expiry_should_prune_fn *should_prune_fn;2724void*policy_cb;2725FILE*newlog;2726struct object_id last_kept_oid;2727};27282729static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2730const char*email, timestamp_t timestamp,int tz,2731const char*message,void*cb_data)2732{2733struct expire_reflog_cb *cb = cb_data;2734struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27352736if(cb->flags & EXPIRE_REFLOGS_REWRITE)2737 ooid = &cb->last_kept_oid;27382739if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2740 message, policy_cb)) {2741if(!cb->newlog)2742printf("would prune%s", message);2743else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2744printf("prune%s", message);2745}else{2746if(cb->newlog) {2747fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2748oid_to_hex(ooid),oid_to_hex(noid),2749 email, timestamp, tz, message);2750oidcpy(&cb->last_kept_oid, noid);2751}2752if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2753printf("keep%s", message);2754}2755return0;2756}27572758static intfiles_reflog_expire(struct ref_store *ref_store,2759const char*refname,const unsigned char*sha1,2760unsigned int flags,2761 reflog_expiry_prepare_fn prepare_fn,2762 reflog_expiry_should_prune_fn should_prune_fn,2763 reflog_expiry_cleanup_fn cleanup_fn,2764void*policy_cb_data)2765{2766struct files_ref_store *refs =2767files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2768static struct lock_file reflog_lock;2769struct expire_reflog_cb cb;2770struct ref_lock *lock;2771struct strbuf log_file_sb = STRBUF_INIT;2772char*log_file;2773int status =0;2774int type;2775struct strbuf err = STRBUF_INIT;2776struct object_id oid;27772778memset(&cb,0,sizeof(cb));2779 cb.flags = flags;2780 cb.policy_cb = policy_cb_data;2781 cb.should_prune_fn = should_prune_fn;27822783/*2784 * The reflog file is locked by holding the lock on the2785 * reference itself, plus we might need to update the2786 * reference if --updateref was specified:2787 */2788 lock =lock_ref_sha1_basic(refs, refname, sha1,2789 NULL, NULL, REF_NODEREF,2790&type, &err);2791if(!lock) {2792error("cannot lock ref '%s':%s", refname, err.buf);2793strbuf_release(&err);2794return-1;2795}2796if(!refs_reflog_exists(ref_store, refname)) {2797unlock_ref(lock);2798return0;2799}28002801files_reflog_path(refs, &log_file_sb, refname);2802 log_file =strbuf_detach(&log_file_sb, NULL);2803if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2804/*2805 * Even though holding $GIT_DIR/logs/$reflog.lock has2806 * no locking implications, we use the lock_file2807 * machinery here anyway because it does a lot of the2808 * work we need, including cleaning up if the program2809 * exits unexpectedly.2810 */2811if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2812struct strbuf err = STRBUF_INIT;2813unable_to_lock_message(log_file, errno, &err);2814error("%s", err.buf);2815strbuf_release(&err);2816goto failure;2817}2818 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2819if(!cb.newlog) {2820error("cannot fdopen%s(%s)",2821get_lock_file_path(&reflog_lock),strerror(errno));2822goto failure;2823}2824}28252826hashcpy(oid.hash, sha1);28272828(*prepare_fn)(refname, &oid, cb.policy_cb);2829refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2830(*cleanup_fn)(cb.policy_cb);28312832if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2833/*2834 * It doesn't make sense to adjust a reference pointed2835 * to by a symbolic ref based on expiring entries in2836 * the symbolic reference's reflog. Nor can we update2837 * a reference if there are no remaining reflog2838 * entries.2839 */2840int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2841!(type & REF_ISSYMREF) &&2842!is_null_oid(&cb.last_kept_oid);28432844if(close_lock_file_gently(&reflog_lock)) {2845 status |=error("couldn't write%s:%s", log_file,2846strerror(errno));2847rollback_lock_file(&reflog_lock);2848}else if(update &&2849(write_in_full(get_lock_file_fd(&lock->lk),2850oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2851write_str_in_full(get_lock_file_fd(&lock->lk),"\n") !=1||2852close_ref_gently(lock) <0)) {2853 status |=error("couldn't write%s",2854get_lock_file_path(&lock->lk));2855rollback_lock_file(&reflog_lock);2856}else if(commit_lock_file(&reflog_lock)) {2857 status |=error("unable to write reflog '%s' (%s)",2858 log_file,strerror(errno));2859}else if(update &&commit_ref(lock)) {2860 status |=error("couldn't set%s", lock->ref_name);2861}2862}2863free(log_file);2864unlock_ref(lock);2865return status;28662867 failure:2868rollback_lock_file(&reflog_lock);2869free(log_file);2870unlock_ref(lock);2871return-1;2872}28732874static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2875{2876struct files_ref_store *refs =2877files_downcast(ref_store, REF_STORE_WRITE,"init_db");2878struct strbuf sb = STRBUF_INIT;28792880/*2881 * Create .git/refs/{heads,tags}2882 */2883files_ref_path(refs, &sb,"refs/heads");2884safe_create_dir(sb.buf,1);28852886strbuf_reset(&sb);2887files_ref_path(refs, &sb,"refs/tags");2888safe_create_dir(sb.buf,1);28892890strbuf_release(&sb);2891return0;2892}28932894struct ref_storage_be refs_be_files = {2895 NULL,2896"files",2897 files_ref_store_create,2898 files_init_db,2899 files_transaction_prepare,2900 files_transaction_finish,2901 files_transaction_abort,2902 files_initial_transaction_commit,29032904 files_pack_refs,2905 files_peel_ref,2906 files_create_symref,2907 files_delete_refs,2908 files_rename_ref,29092910 files_ref_iterator_begin,2911 files_read_raw_ref,29122913 files_reflog_iterator_begin,2914 files_for_each_reflog_ent,2915 files_for_each_reflog_ent_reverse,2916 files_reflog_exists,2917 files_create_reflog,2918 files_delete_reflog,2919 files_reflog_expire2920};