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(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 541if(errno == ENOENT && --attempts_remaining >0) { 542/* 543 * Maybe somebody just deleted one of the 544 * directories leading to ref_file. Try 545 * again: 546 */ 547goto retry; 548}else{ 549unable_to_lock_message(ref_file.buf, errno, err); 550goto error_return; 551} 552} 553 554/* 555 * Now we hold the lock and can read the reference without 556 * fear that its value will change. 557 */ 558 559if(files_read_raw_ref(&refs->base, refname, 560 lock->old_oid.hash, referent, type)) { 561if(errno == ENOENT) { 562if(mustexist) { 563/* Garden variety missing reference. */ 564strbuf_addf(err,"unable to resolve reference '%s'", 565 refname); 566goto error_return; 567}else{ 568/* 569 * Reference is missing, but that's OK. We 570 * know that there is not a conflict with 571 * another loose reference because 572 * (supposing that we are trying to lock 573 * reference "refs/foo/bar"): 574 * 575 * - We were successfully able to create 576 * the lockfile refs/foo/bar.lock, so we 577 * know there cannot be a loose reference 578 * named "refs/foo". 579 * 580 * - We got ENOENT and not EISDIR, so we 581 * know that there cannot be a loose 582 * reference named "refs/foo/bar/baz". 583 */ 584} 585}else if(errno == EISDIR) { 586/* 587 * There is a directory in the way. It might have 588 * contained references that have been deleted. If 589 * we don't require that the reference already 590 * exists, try to remove the directory so that it 591 * doesn't cause trouble when we want to rename the 592 * lockfile into place later. 593 */ 594if(mustexist) { 595/* Garden variety missing reference. */ 596strbuf_addf(err,"unable to resolve reference '%s'", 597 refname); 598goto error_return; 599}else if(remove_dir_recursively(&ref_file, 600 REMOVE_DIR_EMPTY_ONLY)) { 601if(refs_verify_refname_available( 602&refs->base, refname, 603 extras, skip, err)) { 604/* 605 * The error message set by 606 * verify_refname_available() is OK. 607 */ 608 ret = TRANSACTION_NAME_CONFLICT; 609goto error_return; 610}else{ 611/* 612 * We can't delete the directory, 613 * but we also don't know of any 614 * references that it should 615 * contain. 616 */ 617strbuf_addf(err,"there is a non-empty directory '%s' " 618"blocking reference '%s'", 619 ref_file.buf, refname); 620goto error_return; 621} 622} 623}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 624strbuf_addf(err,"unable to resolve reference '%s': " 625"reference broken", refname); 626goto error_return; 627}else{ 628strbuf_addf(err,"unable to resolve reference '%s':%s", 629 refname,strerror(errno)); 630goto error_return; 631} 632 633/* 634 * If the ref did not exist and we are creating it, 635 * make sure there is no existing packed ref that 636 * conflicts with refname: 637 */ 638if(refs_verify_refname_available( 639 refs->packed_ref_store, refname, 640 extras, skip, err)) 641goto error_return; 642} 643 644 ret =0; 645goto out; 646 647error_return: 648unlock_ref(lock); 649*lock_p = NULL; 650 651out: 652strbuf_release(&ref_file); 653return ret; 654} 655 656static intfiles_peel_ref(struct ref_store *ref_store, 657const char*refname,unsigned char*sha1) 658{ 659struct files_ref_store *refs = 660files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 661"peel_ref"); 662int flag; 663unsigned char base[20]; 664 665if(current_ref_iter && current_ref_iter->refname == refname) { 666struct object_id peeled; 667 668if(ref_iterator_peel(current_ref_iter, &peeled)) 669return-1; 670hashcpy(sha1, peeled.hash); 671return0; 672} 673 674if(refs_read_ref_full(ref_store, refname, 675 RESOLVE_REF_READING, base, &flag)) 676return-1; 677 678/* 679 * If the reference is packed, read its ref_entry from the 680 * cache in the hope that we already know its peeled value. 681 * We only try this optimization on packed references because 682 * (a) forcing the filling of the loose reference cache could 683 * be expensive and (b) loose references anyway usually do not 684 * have REF_KNOWS_PEELED. 685 */ 686if(flag & REF_ISPACKED && 687!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 688return0; 689 690returnpeel_object(base, sha1); 691} 692 693struct files_ref_iterator { 694struct ref_iterator base; 695 696struct ref_iterator *iter0; 697unsigned int flags; 698}; 699 700static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 701{ 702struct files_ref_iterator *iter = 703(struct files_ref_iterator *)ref_iterator; 704int ok; 705 706while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 707if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 708ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 709continue; 710 711if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 712!ref_resolves_to_object(iter->iter0->refname, 713 iter->iter0->oid, 714 iter->iter0->flags)) 715continue; 716 717 iter->base.refname = iter->iter0->refname; 718 iter->base.oid = iter->iter0->oid; 719 iter->base.flags = iter->iter0->flags; 720return ITER_OK; 721} 722 723 iter->iter0 = NULL; 724if(ref_iterator_abort(ref_iterator) != ITER_DONE) 725 ok = ITER_ERROR; 726 727return ok; 728} 729 730static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 731struct object_id *peeled) 732{ 733struct files_ref_iterator *iter = 734(struct files_ref_iterator *)ref_iterator; 735 736returnref_iterator_peel(iter->iter0, peeled); 737} 738 739static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 740{ 741struct files_ref_iterator *iter = 742(struct files_ref_iterator *)ref_iterator; 743int ok = ITER_DONE; 744 745if(iter->iter0) 746 ok =ref_iterator_abort(iter->iter0); 747 748base_ref_iterator_free(ref_iterator); 749return ok; 750} 751 752static struct ref_iterator_vtable files_ref_iterator_vtable = { 753 files_ref_iterator_advance, 754 files_ref_iterator_peel, 755 files_ref_iterator_abort 756}; 757 758static struct ref_iterator *files_ref_iterator_begin( 759struct ref_store *ref_store, 760const char*prefix,unsigned int flags) 761{ 762struct files_ref_store *refs; 763struct ref_iterator *loose_iter, *packed_iter; 764struct files_ref_iterator *iter; 765struct ref_iterator *ref_iterator; 766unsigned int required_flags = REF_STORE_READ; 767 768if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 769 required_flags |= REF_STORE_ODB; 770 771 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 772 773 iter =xcalloc(1,sizeof(*iter)); 774 ref_iterator = &iter->base; 775base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 776 777/* 778 * We must make sure that all loose refs are read before 779 * accessing the packed-refs file; this avoids a race 780 * condition if loose refs are migrated to the packed-refs 781 * file by a simultaneous process, but our in-memory view is 782 * from before the migration. We ensure this as follows: 783 * First, we call start the loose refs iteration with its 784 * `prime_ref` argument set to true. This causes the loose 785 * references in the subtree to be pre-read into the cache. 786 * (If they've already been read, that's OK; we only need to 787 * guarantee that they're read before the packed refs, not 788 * *how much* before.) After that, we call 789 * packed_ref_iterator_begin(), which internally checks 790 * whether the packed-ref cache is up to date with what is on 791 * disk, and re-reads it if not. 792 */ 793 794 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 795 prefix,1); 796 797/* 798 * The packed-refs file might contain broken references, for 799 * example an old version of a reference that points at an 800 * object that has since been garbage-collected. This is OK as 801 * long as there is a corresponding loose reference that 802 * overrides it, and we don't want to emit an error message in 803 * this case. So ask the packed_ref_store for all of its 804 * references, and (if needed) do our own check for broken 805 * ones in files_ref_iterator_advance(), after we have merged 806 * the packed and loose references. 807 */ 808 packed_iter =refs_ref_iterator_begin( 809 refs->packed_ref_store, prefix,0, 810 DO_FOR_EACH_INCLUDE_BROKEN); 811 812 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 813 iter->flags = flags; 814 815return ref_iterator; 816} 817 818/* 819 * Verify that the reference locked by lock has the value old_sha1. 820 * Fail if the reference doesn't exist and mustexist is set. Return 0 821 * on success. On error, write an error message to err, set errno, and 822 * return a negative value. 823 */ 824static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 825const unsigned char*old_sha1,int mustexist, 826struct strbuf *err) 827{ 828assert(err); 829 830if(refs_read_ref_full(ref_store, lock->ref_name, 831 mustexist ? RESOLVE_REF_READING :0, 832 lock->old_oid.hash, NULL)) { 833if(old_sha1) { 834int save_errno = errno; 835strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 836 errno = save_errno; 837return-1; 838}else{ 839oidclr(&lock->old_oid); 840return0; 841} 842} 843if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 844strbuf_addf(err,"ref '%s' is at%sbut expected%s", 845 lock->ref_name, 846oid_to_hex(&lock->old_oid), 847sha1_to_hex(old_sha1)); 848 errno = EBUSY; 849return-1; 850} 851return0; 852} 853 854static intremove_empty_directories(struct strbuf *path) 855{ 856/* 857 * we want to create a file but there is a directory there; 858 * if that is an empty directory (or a directory that contains 859 * only empty directories), remove them. 860 */ 861returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 862} 863 864static intcreate_reflock(const char*path,void*cb) 865{ 866struct lock_file *lk = cb; 867 868returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0; 869} 870 871/* 872 * Locks a ref returning the lock on success and NULL on failure. 873 * On failure errno is set to something meaningful. 874 */ 875static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 876const char*refname, 877const unsigned char*old_sha1, 878const struct string_list *extras, 879const struct string_list *skip, 880unsigned int flags,int*type, 881struct strbuf *err) 882{ 883struct strbuf ref_file = STRBUF_INIT; 884struct ref_lock *lock; 885int last_errno =0; 886int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 887int resolve_flags = RESOLVE_REF_NO_RECURSE; 888int resolved; 889 890files_assert_main_repository(refs,"lock_ref_sha1_basic"); 891assert(err); 892 893 lock =xcalloc(1,sizeof(struct ref_lock)); 894 895if(mustexist) 896 resolve_flags |= RESOLVE_REF_READING; 897if(flags & REF_DELETING) 898 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 899 900files_ref_path(refs, &ref_file, refname); 901 resolved = !!refs_resolve_ref_unsafe(&refs->base, 902 refname, resolve_flags, 903 lock->old_oid.hash, type); 904if(!resolved && errno == EISDIR) { 905/* 906 * we are trying to lock foo but we used to 907 * have foo/bar which now does not exist; 908 * it is normal for the empty directory 'foo' 909 * to remain. 910 */ 911if(remove_empty_directories(&ref_file)) { 912 last_errno = errno; 913if(!refs_verify_refname_available( 914&refs->base, 915 refname, extras, skip, err)) 916strbuf_addf(err,"there are still refs under '%s'", 917 refname); 918goto error_return; 919} 920 resolved = !!refs_resolve_ref_unsafe(&refs->base, 921 refname, resolve_flags, 922 lock->old_oid.hash, type); 923} 924if(!resolved) { 925 last_errno = errno; 926if(last_errno != ENOTDIR || 927!refs_verify_refname_available(&refs->base, refname, 928 extras, skip, err)) 929strbuf_addf(err,"unable to resolve reference '%s':%s", 930 refname,strerror(last_errno)); 931 932goto error_return; 933} 934 935/* 936 * If the ref did not exist and we are creating it, make sure 937 * there is no existing packed ref whose name begins with our 938 * refname, nor a packed ref whose name is a proper prefix of 939 * our refname. 940 */ 941if(is_null_oid(&lock->old_oid) && 942refs_verify_refname_available(refs->packed_ref_store, refname, 943 extras, skip, err)) { 944 last_errno = ENOTDIR; 945goto error_return; 946} 947 948 lock->lk =xcalloc(1,sizeof(struct lock_file)); 949 950 lock->ref_name =xstrdup(refname); 951 952if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 953 last_errno = errno; 954unable_to_lock_message(ref_file.buf, errno, err); 955goto error_return; 956} 957 958if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 959 last_errno = errno; 960goto error_return; 961} 962goto out; 963 964 error_return: 965unlock_ref(lock); 966 lock = NULL; 967 968 out: 969strbuf_release(&ref_file); 970 errno = last_errno; 971return lock; 972} 973 974struct ref_to_prune { 975struct ref_to_prune *next; 976unsigned char sha1[20]; 977char name[FLEX_ARRAY]; 978}; 979 980enum{ 981 REMOVE_EMPTY_PARENTS_REF =0x01, 982 REMOVE_EMPTY_PARENTS_REFLOG =0x02 983}; 984 985/* 986 * Remove empty parent directories associated with the specified 987 * reference and/or its reflog, but spare [logs/]refs/ and immediate 988 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 989 * REMOVE_EMPTY_PARENTS_REFLOG. 990 */ 991static voidtry_remove_empty_parents(struct files_ref_store *refs, 992const char*refname, 993unsigned int flags) 994{ 995struct strbuf buf = STRBUF_INIT; 996struct strbuf sb = STRBUF_INIT; 997char*p, *q; 998int i; 9991000strbuf_addstr(&buf, refname);1001 p = buf.buf;1002for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1003while(*p && *p !='/')1004 p++;1005/* tolerate duplicate slashes; see check_refname_format() */1006while(*p =='/')1007 p++;1008}1009 q = buf.buf + buf.len;1010while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1011while(q > p && *q !='/')1012 q--;1013while(q > p && *(q-1) =='/')1014 q--;1015if(q == p)1016break;1017strbuf_setlen(&buf, q - buf.buf);10181019strbuf_reset(&sb);1020files_ref_path(refs, &sb, buf.buf);1021if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1022 flags &= ~REMOVE_EMPTY_PARENTS_REF;10231024strbuf_reset(&sb);1025files_reflog_path(refs, &sb, buf.buf);1026if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1027 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1028}1029strbuf_release(&buf);1030strbuf_release(&sb);1031}10321033/* make sure nobody touched the ref, and unlink */1034static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1035{1036struct ref_transaction *transaction;1037struct strbuf err = STRBUF_INIT;10381039if(check_refname_format(r->name,0))1040return;10411042 transaction =ref_store_transaction_begin(&refs->base, &err);1043if(!transaction ||1044ref_transaction_delete(transaction, r->name, r->sha1,1045 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1046ref_transaction_commit(transaction, &err)) {1047ref_transaction_free(transaction);1048error("%s", err.buf);1049strbuf_release(&err);1050return;1051}1052ref_transaction_free(transaction);1053strbuf_release(&err);1054}10551056static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1057{1058while(r) {1059prune_ref(refs, r);1060 r = r->next;1061}1062}10631064/*1065 * Return true if the specified reference should be packed.1066 */1067static intshould_pack_ref(const char*refname,1068const struct object_id *oid,unsigned int ref_flags,1069unsigned int pack_flags)1070{1071/* Do not pack per-worktree refs: */1072if(ref_type(refname) != REF_TYPE_NORMAL)1073return0;10741075/* Do not pack non-tags unless PACK_REFS_ALL is set: */1076if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1077return0;10781079/* Do not pack symbolic refs: */1080if(ref_flags & REF_ISSYMREF)1081return0;10821083/* Do not pack broken refs: */1084if(!ref_resolves_to_object(refname, oid, ref_flags))1085return0;10861087return1;1088}10891090static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1091{1092struct files_ref_store *refs =1093files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1094"pack_refs");1095struct ref_iterator *iter;1096int ok;1097struct ref_to_prune *refs_to_prune = NULL;1098struct strbuf err = STRBUF_INIT;10991100packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);11011102 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1103while((ok =ref_iterator_advance(iter)) == ITER_OK) {1104/*1105 * If the loose reference can be packed, add an entry1106 * in the packed ref cache. If the reference should be1107 * pruned, also add it to refs_to_prune.1108 */1109if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1110 flags))1111continue;11121113/*1114 * Create an entry in the packed-refs cache equivalent1115 * to the one from the loose ref cache, except that1116 * we don't copy the peeled status, because we want it1117 * to be re-peeled.1118 */1119add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11201121/* Schedule the loose reference for pruning if requested. */1122if((flags & PACK_REFS_PRUNE)) {1123struct ref_to_prune *n;1124FLEX_ALLOC_STR(n, name, iter->refname);1125hashcpy(n->sha1, iter->oid->hash);1126 n->next = refs_to_prune;1127 refs_to_prune = n;1128}1129}1130if(ok != ITER_DONE)1131die("error while iterating over references");11321133if(commit_packed_refs(refs->packed_ref_store, &err))1134die("unable to overwrite old ref-pack file:%s", err.buf);1135packed_refs_unlock(refs->packed_ref_store);11361137prune_refs(refs, refs_to_prune);1138strbuf_release(&err);1139return0;1140}11411142static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1143struct string_list *refnames,unsigned int flags)1144{1145struct files_ref_store *refs =1146files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1147struct strbuf err = STRBUF_INIT;1148int i, result =0;11491150if(!refnames->nr)1151return0;11521153if(packed_refs_lock(refs->packed_ref_store,0, &err))1154goto error;11551156if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1157packed_refs_unlock(refs->packed_ref_store);1158goto error;1159}11601161packed_refs_unlock(refs->packed_ref_store);11621163for(i =0; i < refnames->nr; i++) {1164const char*refname = refnames->items[i].string;11651166if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1167 result |=error(_("could not remove reference%s"), refname);1168}11691170strbuf_release(&err);1171return result;11721173error:1174/*1175 * If we failed to rewrite the packed-refs file, then it is1176 * unsafe to try to remove loose refs, because doing so might1177 * expose an obsolete packed value for a reference that might1178 * even point at an object that has been garbage collected.1179 */1180if(refnames->nr ==1)1181error(_("could not delete reference%s:%s"),1182 refnames->items[0].string, err.buf);1183else1184error(_("could not delete references:%s"), err.buf);11851186strbuf_release(&err);1187return-1;1188}11891190/*1191 * People using contrib's git-new-workdir have .git/logs/refs ->1192 * /some/other/path/.git/logs/refs, and that may live on another device.1193 *1194 * IOW, to avoid cross device rename errors, the temporary renamed log must1195 * live into logs/refs.1196 */1197#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11981199struct rename_cb {1200const char*tmp_renamed_log;1201int true_errno;1202};12031204static intrename_tmp_log_callback(const char*path,void*cb_data)1205{1206struct rename_cb *cb = cb_data;12071208if(rename(cb->tmp_renamed_log, path)) {1209/*1210 * rename(a, b) when b is an existing directory ought1211 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1212 * Sheesh. Record the true errno for error reporting,1213 * but report EISDIR to raceproof_create_file() so1214 * that it knows to retry.1215 */1216 cb->true_errno = errno;1217if(errno == ENOTDIR)1218 errno = EISDIR;1219return-1;1220}else{1221return0;1222}1223}12241225static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1226{1227struct strbuf path = STRBUF_INIT;1228struct strbuf tmp = STRBUF_INIT;1229struct rename_cb cb;1230int ret;12311232files_reflog_path(refs, &path, newrefname);1233files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1234 cb.tmp_renamed_log = tmp.buf;1235 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1236if(ret) {1237if(errno == EISDIR)1238error("directory not empty:%s", path.buf);1239else1240error("unable to move logfile%sto%s:%s",1241 tmp.buf, path.buf,1242strerror(cb.true_errno));1243}12441245strbuf_release(&path);1246strbuf_release(&tmp);1247return ret;1248}12491250static intwrite_ref_to_lockfile(struct ref_lock *lock,1251const struct object_id *oid,struct strbuf *err);1252static intcommit_ref_update(struct files_ref_store *refs,1253struct ref_lock *lock,1254const struct object_id *oid,const char*logmsg,1255struct strbuf *err);12561257static intfiles_rename_ref(struct ref_store *ref_store,1258const char*oldrefname,const char*newrefname,1259const char*logmsg)1260{1261struct files_ref_store *refs =1262files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1263struct object_id oid, orig_oid;1264int flag =0, logmoved =0;1265struct ref_lock *lock;1266struct stat loginfo;1267struct strbuf sb_oldref = STRBUF_INIT;1268struct strbuf sb_newref = STRBUF_INIT;1269struct strbuf tmp_renamed_log = STRBUF_INIT;1270int log, ret;1271struct strbuf err = STRBUF_INIT;12721273files_reflog_path(refs, &sb_oldref, oldrefname);1274files_reflog_path(refs, &sb_newref, newrefname);1275files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12761277 log = !lstat(sb_oldref.buf, &loginfo);1278if(log &&S_ISLNK(loginfo.st_mode)) {1279 ret =error("reflog for%sis a symlink", oldrefname);1280goto out;1281}12821283if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1284 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1285 orig_oid.hash, &flag)) {1286 ret =error("refname%snot found", oldrefname);1287goto out;1288}12891290if(flag & REF_ISSYMREF) {1291 ret =error("refname%sis a symbolic ref, renaming it is not supported",1292 oldrefname);1293goto out;1294}1295if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1296 ret =1;1297goto out;1298}12991300if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1301 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1302 oldrefname,strerror(errno));1303goto out;1304}13051306if(refs_delete_ref(&refs->base, logmsg, oldrefname,1307 orig_oid.hash, REF_NODEREF)) {1308error("unable to delete old%s", oldrefname);1309goto rollback;1310}13111312/*1313 * Since we are doing a shallow lookup, oid is not the1314 * correct value to pass to delete_ref as old_oid. But that1315 * doesn't matter, because an old_oid check wouldn't add to1316 * the safety anyway; we want to delete the reference whatever1317 * its current value.1318 */1319if(!refs_read_ref_full(&refs->base, newrefname,1320 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1321 oid.hash, NULL) &&1322refs_delete_ref(&refs->base, NULL, newrefname,1323 NULL, REF_NODEREF)) {1324if(errno == EISDIR) {1325struct strbuf path = STRBUF_INIT;1326int result;13271328files_ref_path(refs, &path, newrefname);1329 result =remove_empty_directories(&path);1330strbuf_release(&path);13311332if(result) {1333error("Directory not empty:%s", newrefname);1334goto rollback;1335}1336}else{1337error("unable to delete existing%s", newrefname);1338goto rollback;1339}1340}13411342if(log &&rename_tmp_log(refs, newrefname))1343goto rollback;13441345 logmoved = log;13461347 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1348 REF_NODEREF, NULL, &err);1349if(!lock) {1350error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1351strbuf_release(&err);1352goto rollback;1353}1354oidcpy(&lock->old_oid, &orig_oid);13551356if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1357commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1358error("unable to write current sha1 into%s:%s", newrefname, err.buf);1359strbuf_release(&err);1360goto rollback;1361}13621363 ret =0;1364goto out;13651366 rollback:1367 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1368 REF_NODEREF, NULL, &err);1369if(!lock) {1370error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1371strbuf_release(&err);1372goto rollbacklog;1373}13741375 flag = log_all_ref_updates;1376 log_all_ref_updates = LOG_REFS_NONE;1377if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1378commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1379error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1380strbuf_release(&err);1381}1382 log_all_ref_updates = flag;13831384 rollbacklog:1385if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1386error("unable to restore logfile%sfrom%s:%s",1387 oldrefname, newrefname,strerror(errno));1388if(!logmoved && log &&1389rename(tmp_renamed_log.buf, sb_oldref.buf))1390error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1391 oldrefname,strerror(errno));1392 ret =1;1393 out:1394strbuf_release(&sb_newref);1395strbuf_release(&sb_oldref);1396strbuf_release(&tmp_renamed_log);13971398return ret;1399}14001401static intclose_ref(struct ref_lock *lock)1402{1403if(close_lock_file(lock->lk))1404return-1;1405return0;1406}14071408static intcommit_ref(struct ref_lock *lock)1409{1410char*path =get_locked_file_path(lock->lk);1411struct stat st;14121413if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1414/*1415 * There is a directory at the path we want to rename1416 * the lockfile to. Hopefully it is empty; try to1417 * delete it.1418 */1419size_t len =strlen(path);1420struct strbuf sb_path = STRBUF_INIT;14211422strbuf_attach(&sb_path, path, len, len);14231424/*1425 * If this fails, commit_lock_file() will also fail1426 * and will report the problem.1427 */1428remove_empty_directories(&sb_path);1429strbuf_release(&sb_path);1430}else{1431free(path);1432}14331434if(commit_lock_file(lock->lk))1435return-1;1436return0;1437}14381439static intopen_or_create_logfile(const char*path,void*cb)1440{1441int*fd = cb;14421443*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1444return(*fd <0) ? -1:0;1445}14461447/*1448 * Create a reflog for a ref. If force_create = 0, only create the1449 * reflog for certain refs (those for which should_autocreate_reflog1450 * returns non-zero). Otherwise, create it regardless of the reference1451 * name. If the logfile already existed or was created, return 0 and1452 * set *logfd to the file descriptor opened for appending to the file.1453 * If no logfile exists and we decided not to create one, return 0 and1454 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1455 * return -1.1456 */1457static intlog_ref_setup(struct files_ref_store *refs,1458const char*refname,int force_create,1459int*logfd,struct strbuf *err)1460{1461struct strbuf logfile_sb = STRBUF_INIT;1462char*logfile;14631464files_reflog_path(refs, &logfile_sb, refname);1465 logfile =strbuf_detach(&logfile_sb, NULL);14661467if(force_create ||should_autocreate_reflog(refname)) {1468if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1469if(errno == ENOENT)1470strbuf_addf(err,"unable to create directory for '%s': "1471"%s", logfile,strerror(errno));1472else if(errno == EISDIR)1473strbuf_addf(err,"there are still logs under '%s'",1474 logfile);1475else1476strbuf_addf(err,"unable to append to '%s':%s",1477 logfile,strerror(errno));14781479goto error;1480}1481}else{1482*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1483if(*logfd <0) {1484if(errno == ENOENT || errno == EISDIR) {1485/*1486 * The logfile doesn't already exist,1487 * but that is not an error; it only1488 * means that we won't write log1489 * entries to it.1490 */1491;1492}else{1493strbuf_addf(err,"unable to append to '%s':%s",1494 logfile,strerror(errno));1495goto error;1496}1497}1498}14991500if(*logfd >=0)1501adjust_shared_perm(logfile);15021503free(logfile);1504return0;15051506error:1507free(logfile);1508return-1;1509}15101511static intfiles_create_reflog(struct ref_store *ref_store,1512const char*refname,int force_create,1513struct strbuf *err)1514{1515struct files_ref_store *refs =1516files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1517int fd;15181519if(log_ref_setup(refs, refname, force_create, &fd, err))1520return-1;15211522if(fd >=0)1523close(fd);15241525return0;1526}15271528static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1529const struct object_id *new_oid,1530const char*committer,const char*msg)1531{1532int msglen, written;1533unsigned maxlen, len;1534char*logrec;15351536 msglen = msg ?strlen(msg) :0;1537 maxlen =strlen(committer) + msglen +100;1538 logrec =xmalloc(maxlen);1539 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1540oid_to_hex(old_oid),1541oid_to_hex(new_oid),1542 committer);1543if(msglen)1544 len +=copy_reflog_msg(logrec + len -1, msg) -1;15451546 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1547free(logrec);1548if(written != len)1549return-1;15501551return0;1552}15531554static intfiles_log_ref_write(struct files_ref_store *refs,1555const char*refname,const struct object_id *old_oid,1556const struct object_id *new_oid,const char*msg,1557int flags,struct strbuf *err)1558{1559int logfd, result;15601561if(log_all_ref_updates == LOG_REFS_UNSET)1562 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15631564 result =log_ref_setup(refs, refname,1565 flags & REF_FORCE_CREATE_REFLOG,1566&logfd, err);15671568if(result)1569return result;15701571if(logfd <0)1572return0;1573 result =log_ref_write_fd(logfd, old_oid, new_oid,1574git_committer_info(0), msg);1575if(result) {1576struct strbuf sb = STRBUF_INIT;1577int save_errno = errno;15781579files_reflog_path(refs, &sb, refname);1580strbuf_addf(err,"unable to append to '%s':%s",1581 sb.buf,strerror(save_errno));1582strbuf_release(&sb);1583close(logfd);1584return-1;1585}1586if(close(logfd)) {1587struct strbuf sb = STRBUF_INIT;1588int save_errno = errno;15891590files_reflog_path(refs, &sb, refname);1591strbuf_addf(err,"unable to append to '%s':%s",1592 sb.buf,strerror(save_errno));1593strbuf_release(&sb);1594return-1;1595}1596return0;1597}15981599/*1600 * Write sha1 into the open lockfile, then close the lockfile. On1601 * errors, rollback the lockfile, fill in *err and1602 * return -1.1603 */1604static intwrite_ref_to_lockfile(struct ref_lock *lock,1605const struct object_id *oid,struct strbuf *err)1606{1607static char term ='\n';1608struct object *o;1609int fd;16101611 o =parse_object(oid);1612if(!o) {1613strbuf_addf(err,1614"trying to write ref '%s' with nonexistent object%s",1615 lock->ref_name,oid_to_hex(oid));1616unlock_ref(lock);1617return-1;1618}1619if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1620strbuf_addf(err,1621"trying to write non-commit object%sto branch '%s'",1622oid_to_hex(oid), lock->ref_name);1623unlock_ref(lock);1624return-1;1625}1626 fd =get_lock_file_fd(lock->lk);1627if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1628write_in_full(fd, &term,1) !=1||1629close_ref(lock) <0) {1630strbuf_addf(err,1631"couldn't write '%s'",get_lock_file_path(lock->lk));1632unlock_ref(lock);1633return-1;1634}1635return0;1636}16371638/*1639 * Commit a change to a loose reference that has already been written1640 * to the loose reference lockfile. Also update the reflogs if1641 * necessary, using the specified lockmsg (which can be NULL).1642 */1643static intcommit_ref_update(struct files_ref_store *refs,1644struct ref_lock *lock,1645const struct object_id *oid,const char*logmsg,1646struct strbuf *err)1647{1648files_assert_main_repository(refs,"commit_ref_update");16491650clear_loose_ref_cache(refs);1651if(files_log_ref_write(refs, lock->ref_name,1652&lock->old_oid, oid,1653 logmsg,0, err)) {1654char*old_msg =strbuf_detach(err, NULL);1655strbuf_addf(err,"cannot update the ref '%s':%s",1656 lock->ref_name, old_msg);1657free(old_msg);1658unlock_ref(lock);1659return-1;1660}16611662if(strcmp(lock->ref_name,"HEAD") !=0) {1663/*1664 * Special hack: If a branch is updated directly and HEAD1665 * points to it (may happen on the remote side of a push1666 * for example) then logically the HEAD reflog should be1667 * updated too.1668 * A generic solution implies reverse symref information,1669 * but finding all symrefs pointing to the given branch1670 * would be rather costly for this rare event (the direct1671 * update of a branch) to be worth it. So let's cheat and1672 * check with HEAD only which should cover 99% of all usage1673 * scenarios (even 100% of the default ones).1674 */1675struct object_id head_oid;1676int head_flag;1677const char*head_ref;16781679 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1680 RESOLVE_REF_READING,1681 head_oid.hash, &head_flag);1682if(head_ref && (head_flag & REF_ISSYMREF) &&1683!strcmp(head_ref, lock->ref_name)) {1684struct strbuf log_err = STRBUF_INIT;1685if(files_log_ref_write(refs,"HEAD",1686&lock->old_oid, oid,1687 logmsg,0, &log_err)) {1688error("%s", log_err.buf);1689strbuf_release(&log_err);1690}1691}1692}16931694if(commit_ref(lock)) {1695strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1696unlock_ref(lock);1697return-1;1698}16991700unlock_ref(lock);1701return0;1702}17031704static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1705{1706int ret = -1;1707#ifndef NO_SYMLINK_HEAD1708char*ref_path =get_locked_file_path(lock->lk);1709unlink(ref_path);1710 ret =symlink(target, ref_path);1711free(ref_path);17121713if(ret)1714fprintf(stderr,"no symlink - falling back to symbolic ref\n");1715#endif1716return ret;1717}17181719static voidupdate_symref_reflog(struct files_ref_store *refs,1720struct ref_lock *lock,const char*refname,1721const char*target,const char*logmsg)1722{1723struct strbuf err = STRBUF_INIT;1724struct object_id new_oid;1725if(logmsg &&1726!refs_read_ref_full(&refs->base, target,1727 RESOLVE_REF_READING, new_oid.hash, NULL) &&1728files_log_ref_write(refs, refname, &lock->old_oid,1729&new_oid, logmsg,0, &err)) {1730error("%s", err.buf);1731strbuf_release(&err);1732}1733}17341735static intcreate_symref_locked(struct files_ref_store *refs,1736struct ref_lock *lock,const char*refname,1737const char*target,const char*logmsg)1738{1739if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1740update_symref_reflog(refs, lock, refname, target, logmsg);1741return0;1742}17431744if(!fdopen_lock_file(lock->lk,"w"))1745returnerror("unable to fdopen%s:%s",1746 lock->lk->tempfile.filename.buf,strerror(errno));17471748update_symref_reflog(refs, lock, refname, target, logmsg);17491750/* no error check; commit_ref will check ferror */1751fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1752if(commit_ref(lock) <0)1753returnerror("unable to write symref for%s:%s", refname,1754strerror(errno));1755return0;1756}17571758static intfiles_create_symref(struct ref_store *ref_store,1759const char*refname,const char*target,1760const char*logmsg)1761{1762struct files_ref_store *refs =1763files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1764struct strbuf err = STRBUF_INIT;1765struct ref_lock *lock;1766int ret;17671768 lock =lock_ref_sha1_basic(refs, refname, NULL,1769 NULL, NULL, REF_NODEREF, NULL,1770&err);1771if(!lock) {1772error("%s", err.buf);1773strbuf_release(&err);1774return-1;1775}17761777 ret =create_symref_locked(refs, lock, refname, target, logmsg);1778unlock_ref(lock);1779return ret;1780}17811782static intfiles_reflog_exists(struct ref_store *ref_store,1783const char*refname)1784{1785struct files_ref_store *refs =1786files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1787struct strbuf sb = STRBUF_INIT;1788struct stat st;1789int ret;17901791files_reflog_path(refs, &sb, refname);1792 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1793strbuf_release(&sb);1794return ret;1795}17961797static intfiles_delete_reflog(struct ref_store *ref_store,1798const char*refname)1799{1800struct files_ref_store *refs =1801files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1802struct strbuf sb = STRBUF_INIT;1803int ret;18041805files_reflog_path(refs, &sb, refname);1806 ret =remove_path(sb.buf);1807strbuf_release(&sb);1808return ret;1809}18101811static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1812{1813struct object_id ooid, noid;1814char*email_end, *message;1815 timestamp_t timestamp;1816int tz;1817const char*p = sb->buf;18181819/* old SP new SP name <email> SP time TAB msg LF */1820if(!sb->len || sb->buf[sb->len -1] !='\n'||1821parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1822parse_oid_hex(p, &noid, &p) || *p++ !=' '||1823!(email_end =strchr(p,'>')) ||1824 email_end[1] !=' '||1825!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1826!message || message[0] !=' '||1827(message[1] !='+'&& message[1] !='-') ||1828!isdigit(message[2]) || !isdigit(message[3]) ||1829!isdigit(message[4]) || !isdigit(message[5]))1830return0;/* corrupt? */1831 email_end[1] ='\0';1832 tz =strtol(message +1, NULL,10);1833if(message[6] !='\t')1834 message +=6;1835else1836 message +=7;1837returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1838}18391840static char*find_beginning_of_line(char*bob,char*scan)1841{1842while(bob < scan && *(--scan) !='\n')1843;/* keep scanning backwards */1844/*1845 * Return either beginning of the buffer, or LF at the end of1846 * the previous line.1847 */1848return scan;1849}18501851static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1852const char*refname,1853 each_reflog_ent_fn fn,1854void*cb_data)1855{1856struct files_ref_store *refs =1857files_downcast(ref_store, REF_STORE_READ,1858"for_each_reflog_ent_reverse");1859struct strbuf sb = STRBUF_INIT;1860FILE*logfp;1861long pos;1862int ret =0, at_tail =1;18631864files_reflog_path(refs, &sb, refname);1865 logfp =fopen(sb.buf,"r");1866strbuf_release(&sb);1867if(!logfp)1868return-1;18691870/* Jump to the end */1871if(fseek(logfp,0, SEEK_END) <0)1872 ret =error("cannot seek back reflog for%s:%s",1873 refname,strerror(errno));1874 pos =ftell(logfp);1875while(!ret &&0< pos) {1876int cnt;1877size_t nread;1878char buf[BUFSIZ];1879char*endp, *scanp;18801881/* Fill next block from the end */1882 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1883if(fseek(logfp, pos - cnt, SEEK_SET)) {1884 ret =error("cannot seek back reflog for%s:%s",1885 refname,strerror(errno));1886break;1887}1888 nread =fread(buf, cnt,1, logfp);1889if(nread !=1) {1890 ret =error("cannot read%dbytes from reflog for%s:%s",1891 cnt, refname,strerror(errno));1892break;1893}1894 pos -= cnt;18951896 scanp = endp = buf + cnt;1897if(at_tail && scanp[-1] =='\n')1898/* Looking at the final LF at the end of the file */1899 scanp--;1900 at_tail =0;19011902while(buf < scanp) {1903/*1904 * terminating LF of the previous line, or the beginning1905 * of the buffer.1906 */1907char*bp;19081909 bp =find_beginning_of_line(buf, scanp);19101911if(*bp =='\n') {1912/*1913 * The newline is the end of the previous line,1914 * so we know we have complete line starting1915 * at (bp + 1). Prefix it onto any prior data1916 * we collected for the line and process it.1917 */1918strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1919 scanp = bp;1920 endp = bp +1;1921 ret =show_one_reflog_ent(&sb, fn, cb_data);1922strbuf_reset(&sb);1923if(ret)1924break;1925}else if(!pos) {1926/*1927 * We are at the start of the buffer, and the1928 * start of the file; there is no previous1929 * line, and we have everything for this one.1930 * Process it, and we can end the loop.1931 */1932strbuf_splice(&sb,0,0, buf, endp - buf);1933 ret =show_one_reflog_ent(&sb, fn, cb_data);1934strbuf_reset(&sb);1935break;1936}19371938if(bp == buf) {1939/*1940 * We are at the start of the buffer, and there1941 * is more file to read backwards. Which means1942 * we are in the middle of a line. Note that we1943 * may get here even if *bp was a newline; that1944 * just means we are at the exact end of the1945 * previous line, rather than some spot in the1946 * middle.1947 *1948 * Save away what we have to be combined with1949 * the data from the next read.1950 */1951strbuf_splice(&sb,0,0, buf, endp - buf);1952break;1953}1954}19551956}1957if(!ret && sb.len)1958die("BUG: reverse reflog parser had leftover data");19591960fclose(logfp);1961strbuf_release(&sb);1962return ret;1963}19641965static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1966const char*refname,1967 each_reflog_ent_fn fn,void*cb_data)1968{1969struct files_ref_store *refs =1970files_downcast(ref_store, REF_STORE_READ,1971"for_each_reflog_ent");1972FILE*logfp;1973struct strbuf sb = STRBUF_INIT;1974int ret =0;19751976files_reflog_path(refs, &sb, refname);1977 logfp =fopen(sb.buf,"r");1978strbuf_release(&sb);1979if(!logfp)1980return-1;19811982while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1983 ret =show_one_reflog_ent(&sb, fn, cb_data);1984fclose(logfp);1985strbuf_release(&sb);1986return ret;1987}19881989struct files_reflog_iterator {1990struct ref_iterator base;19911992struct ref_store *ref_store;1993struct dir_iterator *dir_iterator;1994struct object_id oid;1995};19961997static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1998{1999struct files_reflog_iterator *iter =2000(struct files_reflog_iterator *)ref_iterator;2001struct dir_iterator *diter = iter->dir_iterator;2002int ok;20032004while((ok =dir_iterator_advance(diter)) == ITER_OK) {2005int flags;20062007if(!S_ISREG(diter->st.st_mode))2008continue;2009if(diter->basename[0] =='.')2010continue;2011if(ends_with(diter->basename,".lock"))2012continue;20132014if(refs_read_ref_full(iter->ref_store,2015 diter->relative_path,0,2016 iter->oid.hash, &flags)) {2017error("bad ref for%s", diter->path.buf);2018continue;2019}20202021 iter->base.refname = diter->relative_path;2022 iter->base.oid = &iter->oid;2023 iter->base.flags = flags;2024return ITER_OK;2025}20262027 iter->dir_iterator = NULL;2028if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2029 ok = ITER_ERROR;2030return ok;2031}20322033static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2034struct object_id *peeled)2035{2036die("BUG: ref_iterator_peel() called for reflog_iterator");2037}20382039static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2040{2041struct files_reflog_iterator *iter =2042(struct files_reflog_iterator *)ref_iterator;2043int ok = ITER_DONE;20442045if(iter->dir_iterator)2046 ok =dir_iterator_abort(iter->dir_iterator);20472048base_ref_iterator_free(ref_iterator);2049return ok;2050}20512052static struct ref_iterator_vtable files_reflog_iterator_vtable = {2053 files_reflog_iterator_advance,2054 files_reflog_iterator_peel,2055 files_reflog_iterator_abort2056};20572058static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2059{2060struct files_ref_store *refs =2061files_downcast(ref_store, REF_STORE_READ,2062"reflog_iterator_begin");2063struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2064struct ref_iterator *ref_iterator = &iter->base;2065struct strbuf sb = STRBUF_INIT;20662067base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2068files_reflog_path(refs, &sb, NULL);2069 iter->dir_iterator =dir_iterator_begin(sb.buf);2070 iter->ref_store = ref_store;2071strbuf_release(&sb);2072return ref_iterator;2073}20742075/*2076 * If update is a direct update of head_ref (the reference pointed to2077 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2078 */2079static intsplit_head_update(struct ref_update *update,2080struct ref_transaction *transaction,2081const char*head_ref,2082struct string_list *affected_refnames,2083struct strbuf *err)2084{2085struct string_list_item *item;2086struct ref_update *new_update;20872088if((update->flags & REF_LOG_ONLY) ||2089(update->flags & REF_ISPRUNING) ||2090(update->flags & REF_UPDATE_VIA_HEAD))2091return0;20922093if(strcmp(update->refname, head_ref))2094return0;20952096/*2097 * First make sure that HEAD is not already in the2098 * transaction. This insertion is O(N) in the transaction2099 * size, but it happens at most once per transaction.2100 */2101 item =string_list_insert(affected_refnames,"HEAD");2102if(item->util) {2103/* An entry already existed */2104strbuf_addf(err,2105"multiple updates for 'HEAD' (including one "2106"via its referent '%s') are not allowed",2107 update->refname);2108return TRANSACTION_NAME_CONFLICT;2109}21102111 new_update =ref_transaction_add_update(2112 transaction,"HEAD",2113 update->flags | REF_LOG_ONLY | REF_NODEREF,2114 update->new_oid.hash, update->old_oid.hash,2115 update->msg);21162117 item->util = new_update;21182119return0;2120}21212122/*2123 * update is for a symref that points at referent and doesn't have2124 * REF_NODEREF set. Split it into two updates:2125 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2126 * - A new, separate update for the referent reference2127 * Note that the new update will itself be subject to splitting when2128 * the iteration gets to it.2129 */2130static intsplit_symref_update(struct files_ref_store *refs,2131struct ref_update *update,2132const char*referent,2133struct ref_transaction *transaction,2134struct string_list *affected_refnames,2135struct strbuf *err)2136{2137struct string_list_item *item;2138struct ref_update *new_update;2139unsigned int new_flags;21402141/*2142 * First make sure that referent is not already in the2143 * transaction. This insertion is O(N) in the transaction2144 * size, but it happens at most once per symref in a2145 * transaction.2146 */2147 item =string_list_insert(affected_refnames, referent);2148if(item->util) {2149/* An entry already existed */2150strbuf_addf(err,2151"multiple updates for '%s' (including one "2152"via symref '%s') are not allowed",2153 referent, update->refname);2154return TRANSACTION_NAME_CONFLICT;2155}21562157 new_flags = update->flags;2158if(!strcmp(update->refname,"HEAD")) {2159/*2160 * Record that the new update came via HEAD, so that2161 * when we process it, split_head_update() doesn't try2162 * to add another reflog update for HEAD. Note that2163 * this bit will be propagated if the new_update2164 * itself needs to be split.2165 */2166 new_flags |= REF_UPDATE_VIA_HEAD;2167}21682169 new_update =ref_transaction_add_update(2170 transaction, referent, new_flags,2171 update->new_oid.hash, update->old_oid.hash,2172 update->msg);21732174 new_update->parent_update = update;21752176/*2177 * Change the symbolic ref update to log only. Also, it2178 * doesn't need to check its old SHA-1 value, as that will be2179 * done when new_update is processed.2180 */2181 update->flags |= REF_LOG_ONLY | REF_NODEREF;2182 update->flags &= ~REF_HAVE_OLD;21832184 item->util = new_update;21852186return0;2187}21882189/*2190 * Return the refname under which update was originally requested.2191 */2192static const char*original_update_refname(struct ref_update *update)2193{2194while(update->parent_update)2195 update = update->parent_update;21962197return update->refname;2198}21992200/*2201 * Check whether the REF_HAVE_OLD and old_oid values stored in update2202 * are consistent with oid, which is the reference's current value. If2203 * everything is OK, return 0; otherwise, write an error message to2204 * err and return -1.2205 */2206static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2207struct strbuf *err)2208{2209if(!(update->flags & REF_HAVE_OLD) ||2210!oidcmp(oid, &update->old_oid))2211return0;22122213if(is_null_oid(&update->old_oid))2214strbuf_addf(err,"cannot lock ref '%s': "2215"reference already exists",2216original_update_refname(update));2217else if(is_null_oid(oid))2218strbuf_addf(err,"cannot lock ref '%s': "2219"reference is missing but expected%s",2220original_update_refname(update),2221oid_to_hex(&update->old_oid));2222else2223strbuf_addf(err,"cannot lock ref '%s': "2224"is at%sbut expected%s",2225original_update_refname(update),2226oid_to_hex(oid),2227oid_to_hex(&update->old_oid));22282229return-1;2230}22312232/*2233 * Prepare for carrying out update:2234 * - Lock the reference referred to by update.2235 * - Read the reference under lock.2236 * - Check that its old SHA-1 value (if specified) is correct, and in2237 * any case record it in update->lock->old_oid for later use when2238 * writing the reflog.2239 * - If it is a symref update without REF_NODEREF, split it up into a2240 * REF_LOG_ONLY update of the symref and add a separate update for2241 * the referent to transaction.2242 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2243 * update of HEAD.2244 */2245static intlock_ref_for_update(struct files_ref_store *refs,2246struct ref_update *update,2247struct ref_transaction *transaction,2248const char*head_ref,2249struct string_list *affected_refnames,2250struct strbuf *err)2251{2252struct strbuf referent = STRBUF_INIT;2253int mustexist = (update->flags & REF_HAVE_OLD) &&2254!is_null_oid(&update->old_oid);2255int ret;2256struct ref_lock *lock;22572258files_assert_main_repository(refs,"lock_ref_for_update");22592260if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2261 update->flags |= REF_DELETING;22622263if(head_ref) {2264 ret =split_head_update(update, transaction, head_ref,2265 affected_refnames, err);2266if(ret)2267return ret;2268}22692270 ret =lock_raw_ref(refs, update->refname, mustexist,2271 affected_refnames, NULL,2272&lock, &referent,2273&update->type, err);2274if(ret) {2275char*reason;22762277 reason =strbuf_detach(err, NULL);2278strbuf_addf(err,"cannot lock ref '%s':%s",2279original_update_refname(update), reason);2280free(reason);2281return ret;2282}22832284 update->backend_data = lock;22852286if(update->type & REF_ISSYMREF) {2287if(update->flags & REF_NODEREF) {2288/*2289 * We won't be reading the referent as part of2290 * the transaction, so we have to read it here2291 * to record and possibly check old_sha1:2292 */2293if(refs_read_ref_full(&refs->base,2294 referent.buf,0,2295 lock->old_oid.hash, NULL)) {2296if(update->flags & REF_HAVE_OLD) {2297strbuf_addf(err,"cannot lock ref '%s': "2298"error reading reference",2299original_update_refname(update));2300return-1;2301}2302}else if(check_old_oid(update, &lock->old_oid, err)) {2303return TRANSACTION_GENERIC_ERROR;2304}2305}else{2306/*2307 * Create a new update for the reference this2308 * symref is pointing at. Also, we will record2309 * and verify old_sha1 for this update as part2310 * of processing the split-off update, so we2311 * don't have to do it here.2312 */2313 ret =split_symref_update(refs, update,2314 referent.buf, transaction,2315 affected_refnames, err);2316if(ret)2317return ret;2318}2319}else{2320struct ref_update *parent_update;23212322if(check_old_oid(update, &lock->old_oid, err))2323return TRANSACTION_GENERIC_ERROR;23242325/*2326 * If this update is happening indirectly because of a2327 * symref update, record the old SHA-1 in the parent2328 * update:2329 */2330for(parent_update = update->parent_update;2331 parent_update;2332 parent_update = parent_update->parent_update) {2333struct ref_lock *parent_lock = parent_update->backend_data;2334oidcpy(&parent_lock->old_oid, &lock->old_oid);2335}2336}23372338if((update->flags & REF_HAVE_NEW) &&2339!(update->flags & REF_DELETING) &&2340!(update->flags & REF_LOG_ONLY)) {2341if(!(update->type & REF_ISSYMREF) &&2342!oidcmp(&lock->old_oid, &update->new_oid)) {2343/*2344 * The reference already has the desired2345 * value, so we don't need to write it.2346 */2347}else if(write_ref_to_lockfile(lock, &update->new_oid,2348 err)) {2349char*write_err =strbuf_detach(err, NULL);23502351/*2352 * The lock was freed upon failure of2353 * write_ref_to_lockfile():2354 */2355 update->backend_data = NULL;2356strbuf_addf(err,2357"cannot update ref '%s':%s",2358 update->refname, write_err);2359free(write_err);2360return TRANSACTION_GENERIC_ERROR;2361}else{2362 update->flags |= REF_NEEDS_COMMIT;2363}2364}2365if(!(update->flags & REF_NEEDS_COMMIT)) {2366/*2367 * We didn't call write_ref_to_lockfile(), so2368 * the lockfile is still open. Close it to2369 * free up the file descriptor:2370 */2371if(close_ref(lock)) {2372strbuf_addf(err,"couldn't close '%s.lock'",2373 update->refname);2374return TRANSACTION_GENERIC_ERROR;2375}2376}2377return0;2378}23792380/*2381 * Unlock any references in `transaction` that are still locked, and2382 * mark the transaction closed.2383 */2384static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2385{2386size_t i;23872388for(i =0; i < transaction->nr; i++) {2389struct ref_update *update = transaction->updates[i];2390struct ref_lock *lock = update->backend_data;23912392if(lock) {2393unlock_ref(lock);2394 update->backend_data = NULL;2395}2396}23972398 transaction->state = REF_TRANSACTION_CLOSED;2399}24002401static intfiles_transaction_prepare(struct ref_store *ref_store,2402struct ref_transaction *transaction,2403struct strbuf *err)2404{2405struct files_ref_store *refs =2406files_downcast(ref_store, REF_STORE_WRITE,2407"ref_transaction_prepare");2408size_t i;2409int ret =0;2410struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2411char*head_ref = NULL;2412int head_type;2413struct object_id head_oid;24142415assert(err);24162417if(!transaction->nr)2418goto cleanup;24192420/*2421 * Fail if a refname appears more than once in the2422 * transaction. (If we end up splitting up any updates using2423 * split_symref_update() or split_head_update(), those2424 * functions will check that the new updates don't have the2425 * same refname as any existing ones.)2426 */2427for(i =0; i < transaction->nr; i++) {2428struct ref_update *update = transaction->updates[i];2429struct string_list_item *item =2430string_list_append(&affected_refnames, update->refname);24312432/*2433 * We store a pointer to update in item->util, but at2434 * the moment we never use the value of this field2435 * except to check whether it is non-NULL.2436 */2437 item->util = update;2438}2439string_list_sort(&affected_refnames);2440if(ref_update_reject_duplicates(&affected_refnames, err)) {2441 ret = TRANSACTION_GENERIC_ERROR;2442goto cleanup;2443}24442445/*2446 * Special hack: If a branch is updated directly and HEAD2447 * points to it (may happen on the remote side of a push2448 * for example) then logically the HEAD reflog should be2449 * updated too.2450 *2451 * A generic solution would require reverse symref lookups,2452 * but finding all symrefs pointing to a given branch would be2453 * rather costly for this rare event (the direct update of a2454 * branch) to be worth it. So let's cheat and check with HEAD2455 * only, which should cover 99% of all usage scenarios (even2456 * 100% of the default ones).2457 *2458 * So if HEAD is a symbolic reference, then record the name of2459 * the reference that it points to. If we see an update of2460 * head_ref within the transaction, then split_head_update()2461 * arranges for the reflog of HEAD to be updated, too.2462 */2463 head_ref =refs_resolve_refdup(ref_store,"HEAD",2464 RESOLVE_REF_NO_RECURSE,2465 head_oid.hash, &head_type);24662467if(head_ref && !(head_type & REF_ISSYMREF)) {2468FREE_AND_NULL(head_ref);2469}24702471/*2472 * Acquire all locks, verify old values if provided, check2473 * that new values are valid, and write new values to the2474 * lockfiles, ready to be activated. Only keep one lockfile2475 * open at a time to avoid running out of file descriptors.2476 * Note that lock_ref_for_update() might append more updates2477 * to the transaction.2478 */2479for(i =0; i < transaction->nr; i++) {2480struct ref_update *update = transaction->updates[i];24812482 ret =lock_ref_for_update(refs, update, transaction,2483 head_ref, &affected_refnames, err);2484if(ret)2485break;2486}24872488cleanup:2489free(head_ref);2490string_list_clear(&affected_refnames,0);24912492if(ret)2493files_transaction_cleanup(transaction);2494else2495 transaction->state = REF_TRANSACTION_PREPARED;24962497return ret;2498}24992500static intfiles_transaction_finish(struct ref_store *ref_store,2501struct ref_transaction *transaction,2502struct strbuf *err)2503{2504struct files_ref_store *refs =2505files_downcast(ref_store,0,"ref_transaction_finish");2506size_t i;2507int ret =0;2508struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2509struct string_list_item *ref_to_delete;2510struct strbuf sb = STRBUF_INIT;25112512assert(err);25132514if(!transaction->nr) {2515 transaction->state = REF_TRANSACTION_CLOSED;2516return0;2517}25182519/* Perform updates first so live commits remain referenced */2520for(i =0; i < transaction->nr; i++) {2521struct ref_update *update = transaction->updates[i];2522struct ref_lock *lock = update->backend_data;25232524if(update->flags & REF_NEEDS_COMMIT ||2525 update->flags & REF_LOG_ONLY) {2526if(files_log_ref_write(refs,2527 lock->ref_name,2528&lock->old_oid,2529&update->new_oid,2530 update->msg, update->flags,2531 err)) {2532char*old_msg =strbuf_detach(err, NULL);25332534strbuf_addf(err,"cannot update the ref '%s':%s",2535 lock->ref_name, old_msg);2536free(old_msg);2537unlock_ref(lock);2538 update->backend_data = NULL;2539 ret = TRANSACTION_GENERIC_ERROR;2540goto cleanup;2541}2542}2543if(update->flags & REF_NEEDS_COMMIT) {2544clear_loose_ref_cache(refs);2545if(commit_ref(lock)) {2546strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2547unlock_ref(lock);2548 update->backend_data = NULL;2549 ret = TRANSACTION_GENERIC_ERROR;2550goto cleanup;2551}2552}2553}2554/* Perform deletes now that updates are safely completed */2555for(i =0; i < transaction->nr; i++) {2556struct ref_update *update = transaction->updates[i];2557struct ref_lock *lock = update->backend_data;25582559if(update->flags & REF_DELETING &&2560!(update->flags & REF_LOG_ONLY)) {2561if(!(update->type & REF_ISPACKED) ||2562 update->type & REF_ISSYMREF) {2563/* It is a loose reference. */2564strbuf_reset(&sb);2565files_ref_path(refs, &sb, lock->ref_name);2566if(unlink_or_msg(sb.buf, err)) {2567 ret = TRANSACTION_GENERIC_ERROR;2568goto cleanup;2569}2570 update->flags |= REF_DELETED_LOOSE;2571}25722573if(!(update->flags & REF_ISPRUNING))2574string_list_append(&refs_to_delete,2575 lock->ref_name);2576}2577}25782579if(packed_refs_lock(refs->packed_ref_store,0, err)) {2580 ret = TRANSACTION_GENERIC_ERROR;2581goto cleanup;2582}25832584if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2585 ret = TRANSACTION_GENERIC_ERROR;2586packed_refs_unlock(refs->packed_ref_store);2587goto cleanup;2588}25892590packed_refs_unlock(refs->packed_ref_store);25912592/* Delete the reflogs of any references that were deleted: */2593for_each_string_list_item(ref_to_delete, &refs_to_delete) {2594strbuf_reset(&sb);2595files_reflog_path(refs, &sb, ref_to_delete->string);2596if(!unlink_or_warn(sb.buf))2597try_remove_empty_parents(refs, ref_to_delete->string,2598 REMOVE_EMPTY_PARENTS_REFLOG);2599}26002601clear_loose_ref_cache(refs);26022603cleanup:2604files_transaction_cleanup(transaction);26052606for(i =0; i < transaction->nr; i++) {2607struct ref_update *update = transaction->updates[i];26082609if(update->flags & REF_DELETED_LOOSE) {2610/*2611 * The loose reference was deleted. Delete any2612 * empty parent directories. (Note that this2613 * can only work because we have already2614 * removed the lockfile.)2615 */2616try_remove_empty_parents(refs, update->refname,2617 REMOVE_EMPTY_PARENTS_REF);2618}2619}26202621strbuf_release(&sb);2622string_list_clear(&refs_to_delete,0);2623return ret;2624}26252626static intfiles_transaction_abort(struct ref_store *ref_store,2627struct ref_transaction *transaction,2628struct strbuf *err)2629{2630files_transaction_cleanup(transaction);2631return0;2632}26332634static intref_present(const char*refname,2635const struct object_id *oid,int flags,void*cb_data)2636{2637struct string_list *affected_refnames = cb_data;26382639returnstring_list_has_string(affected_refnames, refname);2640}26412642static intfiles_initial_transaction_commit(struct ref_store *ref_store,2643struct ref_transaction *transaction,2644struct strbuf *err)2645{2646struct files_ref_store *refs =2647files_downcast(ref_store, REF_STORE_WRITE,2648"initial_ref_transaction_commit");2649size_t i;2650int ret =0;2651struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26522653assert(err);26542655if(transaction->state != REF_TRANSACTION_OPEN)2656die("BUG: commit called for transaction that is not open");26572658/* Fail if a refname appears more than once in the transaction: */2659for(i =0; i < transaction->nr; i++)2660string_list_append(&affected_refnames,2661 transaction->updates[i]->refname);2662string_list_sort(&affected_refnames);2663if(ref_update_reject_duplicates(&affected_refnames, err)) {2664 ret = TRANSACTION_GENERIC_ERROR;2665goto cleanup;2666}26672668/*2669 * It's really undefined to call this function in an active2670 * repository or when there are existing references: we are2671 * only locking and changing packed-refs, so (1) any2672 * simultaneous processes might try to change a reference at2673 * the same time we do, and (2) any existing loose versions of2674 * the references that we are setting would have precedence2675 * over our values. But some remote helpers create the remote2676 * "HEAD" and "master" branches before calling this function,2677 * so here we really only check that none of the references2678 * that we are creating already exists.2679 */2680if(refs_for_each_rawref(&refs->base, ref_present,2681&affected_refnames))2682die("BUG: initial ref transaction called with existing refs");26832684for(i =0; i < transaction->nr; i++) {2685struct ref_update *update = transaction->updates[i];26862687if((update->flags & REF_HAVE_OLD) &&2688!is_null_oid(&update->old_oid))2689die("BUG: initial ref transaction with old_sha1 set");2690if(refs_verify_refname_available(&refs->base, update->refname,2691&affected_refnames, NULL,2692 err)) {2693 ret = TRANSACTION_NAME_CONFLICT;2694goto cleanup;2695}2696}26972698if(packed_refs_lock(refs->packed_ref_store,0, err)) {2699 ret = TRANSACTION_GENERIC_ERROR;2700goto cleanup;2701}27022703for(i =0; i < transaction->nr; i++) {2704struct ref_update *update = transaction->updates[i];27052706if((update->flags & REF_HAVE_NEW) &&2707!is_null_oid(&update->new_oid))2708add_packed_ref(refs->packed_ref_store, update->refname,2709&update->new_oid);2710}27112712if(commit_packed_refs(refs->packed_ref_store, err)) {2713 ret = TRANSACTION_GENERIC_ERROR;2714goto cleanup;2715}27162717cleanup:2718packed_refs_unlock(refs->packed_ref_store);2719 transaction->state = REF_TRANSACTION_CLOSED;2720string_list_clear(&affected_refnames,0);2721return ret;2722}27232724struct expire_reflog_cb {2725unsigned int flags;2726 reflog_expiry_should_prune_fn *should_prune_fn;2727void*policy_cb;2728FILE*newlog;2729struct object_id last_kept_oid;2730};27312732static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2733const char*email, timestamp_t timestamp,int tz,2734const char*message,void*cb_data)2735{2736struct expire_reflog_cb *cb = cb_data;2737struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27382739if(cb->flags & EXPIRE_REFLOGS_REWRITE)2740 ooid = &cb->last_kept_oid;27412742if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2743 message, policy_cb)) {2744if(!cb->newlog)2745printf("would prune%s", message);2746else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2747printf("prune%s", message);2748}else{2749if(cb->newlog) {2750fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2751oid_to_hex(ooid),oid_to_hex(noid),2752 email, timestamp, tz, message);2753oidcpy(&cb->last_kept_oid, noid);2754}2755if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2756printf("keep%s", message);2757}2758return0;2759}27602761static intfiles_reflog_expire(struct ref_store *ref_store,2762const char*refname,const unsigned char*sha1,2763unsigned int flags,2764 reflog_expiry_prepare_fn prepare_fn,2765 reflog_expiry_should_prune_fn should_prune_fn,2766 reflog_expiry_cleanup_fn cleanup_fn,2767void*policy_cb_data)2768{2769struct files_ref_store *refs =2770files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2771static struct lock_file reflog_lock;2772struct expire_reflog_cb cb;2773struct ref_lock *lock;2774struct strbuf log_file_sb = STRBUF_INIT;2775char*log_file;2776int status =0;2777int type;2778struct strbuf err = STRBUF_INIT;2779struct object_id oid;27802781memset(&cb,0,sizeof(cb));2782 cb.flags = flags;2783 cb.policy_cb = policy_cb_data;2784 cb.should_prune_fn = should_prune_fn;27852786/*2787 * The reflog file is locked by holding the lock on the2788 * reference itself, plus we might need to update the2789 * reference if --updateref was specified:2790 */2791 lock =lock_ref_sha1_basic(refs, refname, sha1,2792 NULL, NULL, REF_NODEREF,2793&type, &err);2794if(!lock) {2795error("cannot lock ref '%s':%s", refname, err.buf);2796strbuf_release(&err);2797return-1;2798}2799if(!refs_reflog_exists(ref_store, refname)) {2800unlock_ref(lock);2801return0;2802}28032804files_reflog_path(refs, &log_file_sb, refname);2805 log_file =strbuf_detach(&log_file_sb, NULL);2806if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2807/*2808 * Even though holding $GIT_DIR/logs/$reflog.lock has2809 * no locking implications, we use the lock_file2810 * machinery here anyway because it does a lot of the2811 * work we need, including cleaning up if the program2812 * exits unexpectedly.2813 */2814if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2815struct strbuf err = STRBUF_INIT;2816unable_to_lock_message(log_file, errno, &err);2817error("%s", err.buf);2818strbuf_release(&err);2819goto failure;2820}2821 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2822if(!cb.newlog) {2823error("cannot fdopen%s(%s)",2824get_lock_file_path(&reflog_lock),strerror(errno));2825goto failure;2826}2827}28282829hashcpy(oid.hash, sha1);28302831(*prepare_fn)(refname, &oid, cb.policy_cb);2832refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2833(*cleanup_fn)(cb.policy_cb);28342835if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2836/*2837 * It doesn't make sense to adjust a reference pointed2838 * to by a symbolic ref based on expiring entries in2839 * the symbolic reference's reflog. Nor can we update2840 * a reference if there are no remaining reflog2841 * entries.2842 */2843int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2844!(type & REF_ISSYMREF) &&2845!is_null_oid(&cb.last_kept_oid);28462847if(close_lock_file(&reflog_lock)) {2848 status |=error("couldn't write%s:%s", log_file,2849strerror(errno));2850}else if(update &&2851(write_in_full(get_lock_file_fd(lock->lk),2852oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2853write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2854close_ref(lock) <0)) {2855 status |=error("couldn't write%s",2856get_lock_file_path(lock->lk));2857rollback_lock_file(&reflog_lock);2858}else if(commit_lock_file(&reflog_lock)) {2859 status |=error("unable to write reflog '%s' (%s)",2860 log_file,strerror(errno));2861}else if(update &&commit_ref(lock)) {2862 status |=error("couldn't set%s", lock->ref_name);2863}2864}2865free(log_file);2866unlock_ref(lock);2867return status;28682869 failure:2870rollback_lock_file(&reflog_lock);2871free(log_file);2872unlock_ref(lock);2873return-1;2874}28752876static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2877{2878struct files_ref_store *refs =2879files_downcast(ref_store, REF_STORE_WRITE,"init_db");2880struct strbuf sb = STRBUF_INIT;28812882/*2883 * Create .git/refs/{heads,tags}2884 */2885files_ref_path(refs, &sb,"refs/heads");2886safe_create_dir(sb.buf,1);28872888strbuf_reset(&sb);2889files_ref_path(refs, &sb,"refs/tags");2890safe_create_dir(sb.buf,1);28912892strbuf_release(&sb);2893return0;2894}28952896struct ref_storage_be refs_be_files = {2897 NULL,2898"files",2899 files_ref_store_create,2900 files_init_db,2901 files_transaction_prepare,2902 files_transaction_finish,2903 files_transaction_abort,2904 files_initial_transaction_commit,29052906 files_pack_refs,2907 files_peel_ref,2908 files_create_symref,2909 files_delete_refs,2910 files_rename_ref,29112912 files_ref_iterator_begin,2913 files_read_raw_ref,29142915 files_reflog_iterator_begin,2916 files_for_each_reflog_ent,2917 files_for_each_reflog_ent_reverse,2918 files_reflog_exists,2919 files_create_reflog,2920 files_delete_reflog,2921 files_reflog_expire2922};