1#include"../cache.h" 2#include"../config.h" 3#include"../refs.h" 4#include"refs-internal.h" 5#include"ref-cache.h" 6#include"packed-backend.h" 7#include"../iterator.h" 8#include"../dir-iterator.h" 9#include"../lockfile.h" 10#include"../object.h" 11#include"../dir.h" 12 13struct ref_lock { 14char*ref_name; 15struct lock_file *lk; 16struct object_id old_oid; 17}; 18 19/* 20 * Future: need to be in "struct repository" 21 * when doing a full libification. 22 */ 23struct files_ref_store { 24struct ref_store base; 25unsigned int store_flags; 26 27char*gitdir; 28char*gitcommondir; 29 30struct ref_cache *loose; 31 32struct ref_store *packed_ref_store; 33}; 34 35static voidclear_loose_ref_cache(struct files_ref_store *refs) 36{ 37if(refs->loose) { 38free_ref_cache(refs->loose); 39 refs->loose = NULL; 40} 41} 42 43/* 44 * Create a new submodule ref cache and add it to the internal 45 * set of caches. 46 */ 47static struct ref_store *files_ref_store_create(const char*gitdir, 48unsigned int flags) 49{ 50struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 51struct ref_store *ref_store = (struct ref_store *)refs; 52struct strbuf sb = STRBUF_INIT; 53 54base_ref_store_init(ref_store, &refs_be_files); 55 refs->store_flags = flags; 56 57 refs->gitdir =xstrdup(gitdir); 58get_common_dir_noenv(&sb, gitdir); 59 refs->gitcommondir =strbuf_detach(&sb, NULL); 60strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 61 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 62strbuf_release(&sb); 63 64return ref_store; 65} 66 67/* 68 * Die if refs is not the main ref store. caller is used in any 69 * necessary error messages. 70 */ 71static voidfiles_assert_main_repository(struct files_ref_store *refs, 72const char*caller) 73{ 74if(refs->store_flags & REF_STORE_MAIN) 75return; 76 77die("BUG: operation%sonly allowed for main ref store", caller); 78} 79 80/* 81 * Downcast ref_store to files_ref_store. Die if ref_store is not a 82 * files_ref_store. required_flags is compared with ref_store's 83 * store_flags to ensure the ref_store has all required capabilities. 84 * "caller" is used in any necessary error messages. 85 */ 86static struct files_ref_store *files_downcast(struct ref_store *ref_store, 87unsigned int required_flags, 88const char*caller) 89{ 90struct files_ref_store *refs; 91 92if(ref_store->be != &refs_be_files) 93die("BUG: ref_store is type\"%s\"not\"files\"in%s", 94 ref_store->be->name, caller); 95 96 refs = (struct files_ref_store *)ref_store; 97 98if((refs->store_flags & required_flags) != required_flags) 99die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 100 caller, required_flags, refs->store_flags); 101 102return refs; 103} 104 105static voidfiles_reflog_path(struct files_ref_store *refs, 106struct strbuf *sb, 107const char*refname) 108{ 109if(!refname) { 110/* 111 * FIXME: of course this is wrong in multi worktree 112 * setting. To be fixed real soon. 113 */ 114strbuf_addf(sb,"%s/logs", refs->gitcommondir); 115return; 116} 117 118switch(ref_type(refname)) { 119case REF_TYPE_PER_WORKTREE: 120case REF_TYPE_PSEUDOREF: 121strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 122break; 123case REF_TYPE_NORMAL: 124strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 125break; 126default: 127die("BUG: unknown ref type%dof ref%s", 128ref_type(refname), refname); 129} 130} 131 132static voidfiles_ref_path(struct files_ref_store *refs, 133struct strbuf *sb, 134const char*refname) 135{ 136switch(ref_type(refname)) { 137case REF_TYPE_PER_WORKTREE: 138case REF_TYPE_PSEUDOREF: 139strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 140break; 141case REF_TYPE_NORMAL: 142strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 143break; 144default: 145die("BUG: unknown ref type%dof ref%s", 146ref_type(refname), refname); 147} 148} 149 150/* 151 * Read the loose references from the namespace dirname into dir 152 * (without recursing). dirname must end with '/'. dir must be the 153 * directory entry corresponding to dirname. 154 */ 155static voidloose_fill_ref_dir(struct ref_store *ref_store, 156struct ref_dir *dir,const char*dirname) 157{ 158struct files_ref_store *refs = 159files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 160DIR*d; 161struct dirent *de; 162int dirnamelen =strlen(dirname); 163struct strbuf refname; 164struct strbuf path = STRBUF_INIT; 165size_t path_baselen; 166 167files_ref_path(refs, &path, dirname); 168 path_baselen = path.len; 169 170 d =opendir(path.buf); 171if(!d) { 172strbuf_release(&path); 173return; 174} 175 176strbuf_init(&refname, dirnamelen +257); 177strbuf_add(&refname, dirname, dirnamelen); 178 179while((de =readdir(d)) != NULL) { 180struct object_id oid; 181struct stat st; 182int flag; 183 184if(de->d_name[0] =='.') 185continue; 186if(ends_with(de->d_name,".lock")) 187continue; 188strbuf_addstr(&refname, de->d_name); 189strbuf_addstr(&path, de->d_name); 190if(stat(path.buf, &st) <0) { 191;/* silently ignore */ 192}else if(S_ISDIR(st.st_mode)) { 193strbuf_addch(&refname,'/'); 194add_entry_to_dir(dir, 195create_dir_entry(dir->cache, refname.buf, 196 refname.len,1)); 197}else{ 198if(!refs_resolve_ref_unsafe(&refs->base, 199 refname.buf, 200 RESOLVE_REF_READING, 201 oid.hash, &flag)) { 202oidclr(&oid); 203 flag |= REF_ISBROKEN; 204}else if(is_null_oid(&oid)) { 205/* 206 * It is so astronomically unlikely 207 * that NULL_SHA1 is the SHA-1 of an 208 * actual object that we consider its 209 * appearance in a loose reference 210 * file to be repo corruption 211 * (probably due to a software bug). 212 */ 213 flag |= REF_ISBROKEN; 214} 215 216if(check_refname_format(refname.buf, 217 REFNAME_ALLOW_ONELEVEL)) { 218if(!refname_is_safe(refname.buf)) 219die("loose refname is dangerous:%s", refname.buf); 220oidclr(&oid); 221 flag |= REF_BAD_NAME | REF_ISBROKEN; 222} 223add_entry_to_dir(dir, 224create_ref_entry(refname.buf, &oid, flag)); 225} 226strbuf_setlen(&refname, dirnamelen); 227strbuf_setlen(&path, path_baselen); 228} 229strbuf_release(&refname); 230strbuf_release(&path); 231closedir(d); 232 233/* 234 * Manually add refs/bisect, which, being per-worktree, might 235 * not appear in the directory listing for refs/ in the main 236 * repo. 237 */ 238if(!strcmp(dirname,"refs/")) { 239int pos =search_ref_dir(dir,"refs/bisect/",12); 240 241if(pos <0) { 242struct ref_entry *child_entry =create_dir_entry( 243 dir->cache,"refs/bisect/",12,1); 244add_entry_to_dir(dir, child_entry); 245} 246} 247} 248 249static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 250{ 251if(!refs->loose) { 252/* 253 * Mark the top-level directory complete because we 254 * are about to read the only subdirectory that can 255 * hold references: 256 */ 257 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 258 259/* We're going to fill the top level ourselves: */ 260 refs->loose->root->flag &= ~REF_INCOMPLETE; 261 262/* 263 * Add an incomplete entry for "refs/" (to be filled 264 * lazily): 265 */ 266add_entry_to_dir(get_ref_dir(refs->loose->root), 267create_dir_entry(refs->loose,"refs/",5,1)); 268} 269return refs->loose; 270} 271 272static intfiles_read_raw_ref(struct ref_store *ref_store, 273const char*refname,unsigned char*sha1, 274struct strbuf *referent,unsigned int*type) 275{ 276struct files_ref_store *refs = 277files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 278struct strbuf sb_contents = STRBUF_INIT; 279struct strbuf sb_path = STRBUF_INIT; 280const char*path; 281const char*buf; 282struct stat st; 283int fd; 284int ret = -1; 285int save_errno; 286int remaining_retries =3; 287 288*type =0; 289strbuf_reset(&sb_path); 290 291files_ref_path(refs, &sb_path, refname); 292 293 path = sb_path.buf; 294 295stat_ref: 296/* 297 * We might have to loop back here to avoid a race 298 * condition: first we lstat() the file, then we try 299 * to read it as a link or as a file. But if somebody 300 * changes the type of the file (file <-> directory 301 * <-> symlink) between the lstat() and reading, then 302 * we don't want to report that as an error but rather 303 * try again starting with the lstat(). 304 * 305 * We'll keep a count of the retries, though, just to avoid 306 * any confusing situation sending us into an infinite loop. 307 */ 308 309if(remaining_retries-- <=0) 310goto out; 311 312if(lstat(path, &st) <0) { 313if(errno != ENOENT) 314goto out; 315if(refs_read_raw_ref(refs->packed_ref_store, refname, 316 sha1, referent, type)) { 317 errno = ENOENT; 318goto out; 319} 320 ret =0; 321goto out; 322} 323 324/* Follow "normalized" - ie "refs/.." symlinks by hand */ 325if(S_ISLNK(st.st_mode)) { 326strbuf_reset(&sb_contents); 327if(strbuf_readlink(&sb_contents, path,0) <0) { 328if(errno == ENOENT || errno == EINVAL) 329/* inconsistent with lstat; retry */ 330goto stat_ref; 331else 332goto out; 333} 334if(starts_with(sb_contents.buf,"refs/") && 335!check_refname_format(sb_contents.buf,0)) { 336strbuf_swap(&sb_contents, referent); 337*type |= REF_ISSYMREF; 338 ret =0; 339goto out; 340} 341/* 342 * It doesn't look like a refname; fall through to just 343 * treating it like a non-symlink, and reading whatever it 344 * points to. 345 */ 346} 347 348/* Is it a directory? */ 349if(S_ISDIR(st.st_mode)) { 350/* 351 * Even though there is a directory where the loose 352 * ref is supposed to be, there could still be a 353 * packed ref: 354 */ 355if(refs_read_raw_ref(refs->packed_ref_store, refname, 356 sha1, referent, type)) { 357 errno = EISDIR; 358goto out; 359} 360 ret =0; 361goto out; 362} 363 364/* 365 * Anything else, just open it and try to use it as 366 * a ref 367 */ 368 fd =open(path, O_RDONLY); 369if(fd <0) { 370if(errno == ENOENT && !S_ISLNK(st.st_mode)) 371/* inconsistent with lstat; retry */ 372goto stat_ref; 373else 374goto out; 375} 376strbuf_reset(&sb_contents); 377if(strbuf_read(&sb_contents, fd,256) <0) { 378int save_errno = errno; 379close(fd); 380 errno = save_errno; 381goto out; 382} 383close(fd); 384strbuf_rtrim(&sb_contents); 385 buf = sb_contents.buf; 386if(starts_with(buf,"ref:")) { 387 buf +=4; 388while(isspace(*buf)) 389 buf++; 390 391strbuf_reset(referent); 392strbuf_addstr(referent, buf); 393*type |= REF_ISSYMREF; 394 ret =0; 395goto out; 396} 397 398/* 399 * Please note that FETCH_HEAD has additional 400 * data after the sha. 401 */ 402if(get_sha1_hex(buf, sha1) || 403(buf[40] !='\0'&& !isspace(buf[40]))) { 404*type |= REF_ISBROKEN; 405 errno = EINVAL; 406goto out; 407} 408 409 ret =0; 410 411out: 412 save_errno = errno; 413strbuf_release(&sb_path); 414strbuf_release(&sb_contents); 415 errno = save_errno; 416return ret; 417} 418 419static voidunlock_ref(struct ref_lock *lock) 420{ 421/* Do not free lock->lk -- atexit() still looks at them */ 422if(lock->lk) 423rollback_lock_file(lock->lk); 424free(lock->ref_name); 425free(lock); 426} 427 428/* 429 * Lock refname, without following symrefs, and set *lock_p to point 430 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 431 * and type similarly to read_raw_ref(). 432 * 433 * The caller must verify that refname is a "safe" reference name (in 434 * the sense of refname_is_safe()) before calling this function. 435 * 436 * If the reference doesn't already exist, verify that refname doesn't 437 * have a D/F conflict with any existing references. extras and skip 438 * are passed to refs_verify_refname_available() for this check. 439 * 440 * If mustexist is not set and the reference is not found or is 441 * broken, lock the reference anyway but clear sha1. 442 * 443 * Return 0 on success. On failure, write an error message to err and 444 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 445 * 446 * Implementation note: This function is basically 447 * 448 * lock reference 449 * read_raw_ref() 450 * 451 * but it includes a lot more code to 452 * - Deal with possible races with other processes 453 * - Avoid calling refs_verify_refname_available() when it can be 454 * avoided, namely if we were successfully able to read the ref 455 * - Generate informative error messages in the case of failure 456 */ 457static intlock_raw_ref(struct files_ref_store *refs, 458const char*refname,int mustexist, 459const struct string_list *extras, 460const struct string_list *skip, 461struct ref_lock **lock_p, 462struct strbuf *referent, 463unsigned int*type, 464struct strbuf *err) 465{ 466struct ref_lock *lock; 467struct strbuf ref_file = STRBUF_INIT; 468int attempts_remaining =3; 469int ret = TRANSACTION_GENERIC_ERROR; 470 471assert(err); 472files_assert_main_repository(refs,"lock_raw_ref"); 473 474*type =0; 475 476/* First lock the file so it can't change out from under us. */ 477 478*lock_p = lock =xcalloc(1,sizeof(*lock)); 479 480 lock->ref_name =xstrdup(refname); 481files_ref_path(refs, &ref_file, refname); 482 483retry: 484switch(safe_create_leading_directories(ref_file.buf)) { 485case SCLD_OK: 486break;/* success */ 487case SCLD_EXISTS: 488/* 489 * Suppose refname is "refs/foo/bar". We just failed 490 * to create the containing directory, "refs/foo", 491 * because there was a non-directory in the way. This 492 * indicates a D/F conflict, probably because of 493 * another reference such as "refs/foo". There is no 494 * reason to expect this error to be transitory. 495 */ 496if(refs_verify_refname_available(&refs->base, refname, 497 extras, skip, err)) { 498if(mustexist) { 499/* 500 * To the user the relevant error is 501 * that the "mustexist" reference is 502 * missing: 503 */ 504strbuf_reset(err); 505strbuf_addf(err,"unable to resolve reference '%s'", 506 refname); 507}else{ 508/* 509 * The error message set by 510 * refs_verify_refname_available() is 511 * OK. 512 */ 513 ret = TRANSACTION_NAME_CONFLICT; 514} 515}else{ 516/* 517 * The file that is in the way isn't a loose 518 * reference. Report it as a low-level 519 * failure. 520 */ 521strbuf_addf(err,"unable to create lock file%s.lock; " 522"non-directory in the way", 523 ref_file.buf); 524} 525goto error_return; 526case SCLD_VANISHED: 527/* Maybe another process was tidying up. Try again. */ 528if(--attempts_remaining >0) 529goto retry; 530/* fall through */ 531default: 532strbuf_addf(err,"unable to create directory for%s", 533 ref_file.buf); 534goto error_return; 535} 536 537if(!lock->lk) 538 lock->lk =xcalloc(1,sizeof(struct lock_file)); 539 540if(hold_lock_file_for_update_timeout( 541 lock->lk, ref_file.buf, LOCK_NO_DEREF, 542get_files_ref_lock_timeout_ms()) <0) { 543if(errno == ENOENT && --attempts_remaining >0) { 544/* 545 * Maybe somebody just deleted one of the 546 * directories leading to ref_file. Try 547 * again: 548 */ 549goto retry; 550}else{ 551unable_to_lock_message(ref_file.buf, errno, err); 552goto error_return; 553} 554} 555 556/* 557 * Now we hold the lock and can read the reference without 558 * fear that its value will change. 559 */ 560 561if(files_read_raw_ref(&refs->base, refname, 562 lock->old_oid.hash, referent, type)) { 563if(errno == ENOENT) { 564if(mustexist) { 565/* Garden variety missing reference. */ 566strbuf_addf(err,"unable to resolve reference '%s'", 567 refname); 568goto error_return; 569}else{ 570/* 571 * Reference is missing, but that's OK. We 572 * know that there is not a conflict with 573 * another loose reference because 574 * (supposing that we are trying to lock 575 * reference "refs/foo/bar"): 576 * 577 * - We were successfully able to create 578 * the lockfile refs/foo/bar.lock, so we 579 * know there cannot be a loose reference 580 * named "refs/foo". 581 * 582 * - We got ENOENT and not EISDIR, so we 583 * know that there cannot be a loose 584 * reference named "refs/foo/bar/baz". 585 */ 586} 587}else if(errno == EISDIR) { 588/* 589 * There is a directory in the way. It might have 590 * contained references that have been deleted. If 591 * we don't require that the reference already 592 * exists, try to remove the directory so that it 593 * doesn't cause trouble when we want to rename the 594 * lockfile into place later. 595 */ 596if(mustexist) { 597/* Garden variety missing reference. */ 598strbuf_addf(err,"unable to resolve reference '%s'", 599 refname); 600goto error_return; 601}else if(remove_dir_recursively(&ref_file, 602 REMOVE_DIR_EMPTY_ONLY)) { 603if(refs_verify_refname_available( 604&refs->base, refname, 605 extras, skip, err)) { 606/* 607 * The error message set by 608 * verify_refname_available() is OK. 609 */ 610 ret = TRANSACTION_NAME_CONFLICT; 611goto error_return; 612}else{ 613/* 614 * We can't delete the directory, 615 * but we also don't know of any 616 * references that it should 617 * contain. 618 */ 619strbuf_addf(err,"there is a non-empty directory '%s' " 620"blocking reference '%s'", 621 ref_file.buf, refname); 622goto error_return; 623} 624} 625}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 626strbuf_addf(err,"unable to resolve reference '%s': " 627"reference broken", refname); 628goto error_return; 629}else{ 630strbuf_addf(err,"unable to resolve reference '%s':%s", 631 refname,strerror(errno)); 632goto error_return; 633} 634 635/* 636 * If the ref did not exist and we are creating it, 637 * make sure there is no existing packed ref that 638 * conflicts with refname: 639 */ 640if(refs_verify_refname_available( 641 refs->packed_ref_store, refname, 642 extras, skip, err)) 643goto error_return; 644} 645 646 ret =0; 647goto out; 648 649error_return: 650unlock_ref(lock); 651*lock_p = NULL; 652 653out: 654strbuf_release(&ref_file); 655return ret; 656} 657 658static intfiles_peel_ref(struct ref_store *ref_store, 659const char*refname,unsigned char*sha1) 660{ 661struct files_ref_store *refs = 662files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 663"peel_ref"); 664int flag; 665unsigned char base[20]; 666 667if(current_ref_iter && current_ref_iter->refname == refname) { 668struct object_id peeled; 669 670if(ref_iterator_peel(current_ref_iter, &peeled)) 671return-1; 672hashcpy(sha1, peeled.hash); 673return0; 674} 675 676if(refs_read_ref_full(ref_store, refname, 677 RESOLVE_REF_READING, base, &flag)) 678return-1; 679 680/* 681 * If the reference is packed, read its ref_entry from the 682 * cache in the hope that we already know its peeled value. 683 * We only try this optimization on packed references because 684 * (a) forcing the filling of the loose reference cache could 685 * be expensive and (b) loose references anyway usually do not 686 * have REF_KNOWS_PEELED. 687 */ 688if(flag & REF_ISPACKED && 689!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 690return0; 691 692returnpeel_object(base, sha1); 693} 694 695struct files_ref_iterator { 696struct ref_iterator base; 697 698struct ref_iterator *iter0; 699unsigned int flags; 700}; 701 702static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 703{ 704struct files_ref_iterator *iter = 705(struct files_ref_iterator *)ref_iterator; 706int ok; 707 708while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 709if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 710ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 711continue; 712 713if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 714!ref_resolves_to_object(iter->iter0->refname, 715 iter->iter0->oid, 716 iter->iter0->flags)) 717continue; 718 719 iter->base.refname = iter->iter0->refname; 720 iter->base.oid = iter->iter0->oid; 721 iter->base.flags = iter->iter0->flags; 722return ITER_OK; 723} 724 725 iter->iter0 = NULL; 726if(ref_iterator_abort(ref_iterator) != ITER_DONE) 727 ok = ITER_ERROR; 728 729return ok; 730} 731 732static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 733struct object_id *peeled) 734{ 735struct files_ref_iterator *iter = 736(struct files_ref_iterator *)ref_iterator; 737 738returnref_iterator_peel(iter->iter0, peeled); 739} 740 741static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 742{ 743struct files_ref_iterator *iter = 744(struct files_ref_iterator *)ref_iterator; 745int ok = ITER_DONE; 746 747if(iter->iter0) 748 ok =ref_iterator_abort(iter->iter0); 749 750base_ref_iterator_free(ref_iterator); 751return ok; 752} 753 754static struct ref_iterator_vtable files_ref_iterator_vtable = { 755 files_ref_iterator_advance, 756 files_ref_iterator_peel, 757 files_ref_iterator_abort 758}; 759 760static struct ref_iterator *files_ref_iterator_begin( 761struct ref_store *ref_store, 762const char*prefix,unsigned int flags) 763{ 764struct files_ref_store *refs; 765struct ref_iterator *loose_iter, *packed_iter, *overlay_iter; 766struct files_ref_iterator *iter; 767struct ref_iterator *ref_iterator; 768unsigned int required_flags = REF_STORE_READ; 769 770if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 771 required_flags |= REF_STORE_ODB; 772 773 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 774 775/* 776 * We must make sure that all loose refs are read before 777 * accessing the packed-refs file; this avoids a race 778 * condition if loose refs are migrated to the packed-refs 779 * file by a simultaneous process, but our in-memory view is 780 * from before the migration. We ensure this as follows: 781 * First, we call start the loose refs iteration with its 782 * `prime_ref` argument set to true. This causes the loose 783 * references in the subtree to be pre-read into the cache. 784 * (If they've already been read, that's OK; we only need to 785 * guarantee that they're read before the packed refs, not 786 * *how much* before.) After that, we call 787 * packed_ref_iterator_begin(), which internally checks 788 * whether the packed-ref cache is up to date with what is on 789 * disk, and re-reads it if not. 790 */ 791 792 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 793 prefix,1); 794 795/* 796 * The packed-refs file might contain broken references, for 797 * example an old version of a reference that points at an 798 * object that has since been garbage-collected. This is OK as 799 * long as there is a corresponding loose reference that 800 * overrides it, and we don't want to emit an error message in 801 * this case. So ask the packed_ref_store for all of its 802 * references, and (if needed) do our own check for broken 803 * ones in files_ref_iterator_advance(), after we have merged 804 * the packed and loose references. 805 */ 806 packed_iter =refs_ref_iterator_begin( 807 refs->packed_ref_store, prefix,0, 808 DO_FOR_EACH_INCLUDE_BROKEN); 809 810 overlay_iter =overlay_ref_iterator_begin(loose_iter, packed_iter); 811 812 iter =xcalloc(1,sizeof(*iter)); 813 ref_iterator = &iter->base; 814base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable, 815 overlay_iter->ordered); 816 iter->iter0 = overlay_iter; 817 iter->flags = flags; 818 819return ref_iterator; 820} 821 822/* 823 * Verify that the reference locked by lock has the value old_sha1. 824 * Fail if the reference doesn't exist and mustexist is set. Return 0 825 * on success. On error, write an error message to err, set errno, and 826 * return a negative value. 827 */ 828static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 829const unsigned char*old_sha1,int mustexist, 830struct strbuf *err) 831{ 832assert(err); 833 834if(refs_read_ref_full(ref_store, lock->ref_name, 835 mustexist ? RESOLVE_REF_READING :0, 836 lock->old_oid.hash, NULL)) { 837if(old_sha1) { 838int save_errno = errno; 839strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 840 errno = save_errno; 841return-1; 842}else{ 843oidclr(&lock->old_oid); 844return0; 845} 846} 847if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 848strbuf_addf(err,"ref '%s' is at%sbut expected%s", 849 lock->ref_name, 850oid_to_hex(&lock->old_oid), 851sha1_to_hex(old_sha1)); 852 errno = EBUSY; 853return-1; 854} 855return0; 856} 857 858static intremove_empty_directories(struct strbuf *path) 859{ 860/* 861 * we want to create a file but there is a directory there; 862 * if that is an empty directory (or a directory that contains 863 * only empty directories), remove them. 864 */ 865returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 866} 867 868static intcreate_reflock(const char*path,void*cb) 869{ 870struct lock_file *lk = cb; 871 872returnhold_lock_file_for_update_timeout( 873 lk, path, LOCK_NO_DEREF, 874get_files_ref_lock_timeout_ms()) <0? -1:0; 875} 876 877/* 878 * Locks a ref returning the lock on success and NULL on failure. 879 * On failure errno is set to something meaningful. 880 */ 881static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 882const char*refname, 883const unsigned char*old_sha1, 884const struct string_list *extras, 885const struct string_list *skip, 886unsigned int flags,int*type, 887struct strbuf *err) 888{ 889struct strbuf ref_file = STRBUF_INIT; 890struct ref_lock *lock; 891int last_errno =0; 892int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 893int resolve_flags = RESOLVE_REF_NO_RECURSE; 894int resolved; 895 896files_assert_main_repository(refs,"lock_ref_sha1_basic"); 897assert(err); 898 899 lock =xcalloc(1,sizeof(struct ref_lock)); 900 901if(mustexist) 902 resolve_flags |= RESOLVE_REF_READING; 903if(flags & REF_DELETING) 904 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 905 906files_ref_path(refs, &ref_file, refname); 907 resolved = !!refs_resolve_ref_unsafe(&refs->base, 908 refname, resolve_flags, 909 lock->old_oid.hash, type); 910if(!resolved && errno == EISDIR) { 911/* 912 * we are trying to lock foo but we used to 913 * have foo/bar which now does not exist; 914 * it is normal for the empty directory 'foo' 915 * to remain. 916 */ 917if(remove_empty_directories(&ref_file)) { 918 last_errno = errno; 919if(!refs_verify_refname_available( 920&refs->base, 921 refname, extras, skip, err)) 922strbuf_addf(err,"there are still refs under '%s'", 923 refname); 924goto error_return; 925} 926 resolved = !!refs_resolve_ref_unsafe(&refs->base, 927 refname, resolve_flags, 928 lock->old_oid.hash, type); 929} 930if(!resolved) { 931 last_errno = errno; 932if(last_errno != ENOTDIR || 933!refs_verify_refname_available(&refs->base, refname, 934 extras, skip, err)) 935strbuf_addf(err,"unable to resolve reference '%s':%s", 936 refname,strerror(last_errno)); 937 938goto error_return; 939} 940 941/* 942 * If the ref did not exist and we are creating it, make sure 943 * there is no existing packed ref whose name begins with our 944 * refname, nor a packed ref whose name is a proper prefix of 945 * our refname. 946 */ 947if(is_null_oid(&lock->old_oid) && 948refs_verify_refname_available(refs->packed_ref_store, refname, 949 extras, skip, err)) { 950 last_errno = ENOTDIR; 951goto error_return; 952} 953 954 lock->lk =xcalloc(1,sizeof(struct lock_file)); 955 956 lock->ref_name =xstrdup(refname); 957 958if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 959 last_errno = errno; 960unable_to_lock_message(ref_file.buf, errno, err); 961goto error_return; 962} 963 964if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 965 last_errno = errno; 966goto error_return; 967} 968goto out; 969 970 error_return: 971unlock_ref(lock); 972 lock = NULL; 973 974 out: 975strbuf_release(&ref_file); 976 errno = last_errno; 977return lock; 978} 979 980struct ref_to_prune { 981struct ref_to_prune *next; 982unsigned char sha1[20]; 983char name[FLEX_ARRAY]; 984}; 985 986enum{ 987 REMOVE_EMPTY_PARENTS_REF =0x01, 988 REMOVE_EMPTY_PARENTS_REFLOG =0x02 989}; 990 991/* 992 * Remove empty parent directories associated with the specified 993 * reference and/or its reflog, but spare [logs/]refs/ and immediate 994 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 995 * REMOVE_EMPTY_PARENTS_REFLOG. 996 */ 997static voidtry_remove_empty_parents(struct files_ref_store *refs, 998const char*refname, 999unsigned int flags)1000{1001struct strbuf buf = STRBUF_INIT;1002struct strbuf sb = STRBUF_INIT;1003char*p, *q;1004int i;10051006strbuf_addstr(&buf, refname);1007 p = buf.buf;1008for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1009while(*p && *p !='/')1010 p++;1011/* tolerate duplicate slashes; see check_refname_format() */1012while(*p =='/')1013 p++;1014}1015 q = buf.buf + buf.len;1016while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1017while(q > p && *q !='/')1018 q--;1019while(q > p && *(q-1) =='/')1020 q--;1021if(q == p)1022break;1023strbuf_setlen(&buf, q - buf.buf);10241025strbuf_reset(&sb);1026files_ref_path(refs, &sb, buf.buf);1027if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1028 flags &= ~REMOVE_EMPTY_PARENTS_REF;10291030strbuf_reset(&sb);1031files_reflog_path(refs, &sb, buf.buf);1032if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1033 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1034}1035strbuf_release(&buf);1036strbuf_release(&sb);1037}10381039/* make sure nobody touched the ref, and unlink */1040static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1041{1042struct ref_transaction *transaction;1043struct strbuf err = STRBUF_INIT;10441045if(check_refname_format(r->name,0))1046return;10471048 transaction =ref_store_transaction_begin(&refs->base, &err);1049if(!transaction ||1050ref_transaction_delete(transaction, r->name, r->sha1,1051 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1052ref_transaction_commit(transaction, &err)) {1053ref_transaction_free(transaction);1054error("%s", err.buf);1055strbuf_release(&err);1056return;1057}1058ref_transaction_free(transaction);1059strbuf_release(&err);1060}10611062/*1063 * Prune the loose versions of the references in the linked list1064 * `*refs_to_prune`, freeing the entries in the list as we go.1065 */1066static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune **refs_to_prune)1067{1068while(*refs_to_prune) {1069struct ref_to_prune *r = *refs_to_prune;1070*refs_to_prune = r->next;1071prune_ref(refs, r);1072free(r);1073}1074}10751076/*1077 * Return true if the specified reference should be packed.1078 */1079static intshould_pack_ref(const char*refname,1080const struct object_id *oid,unsigned int ref_flags,1081unsigned int pack_flags)1082{1083/* Do not pack per-worktree refs: */1084if(ref_type(refname) != REF_TYPE_NORMAL)1085return0;10861087/* Do not pack non-tags unless PACK_REFS_ALL is set: */1088if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1089return0;10901091/* Do not pack symbolic refs: */1092if(ref_flags & REF_ISSYMREF)1093return0;10941095/* Do not pack broken refs: */1096if(!ref_resolves_to_object(refname, oid, ref_flags))1097return0;10981099return1;1100}11011102static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1103{1104struct files_ref_store *refs =1105files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1106"pack_refs");1107struct ref_iterator *iter;1108int ok;1109struct ref_to_prune *refs_to_prune = NULL;1110struct strbuf err = STRBUF_INIT;1111struct ref_transaction *transaction;11121113 transaction =ref_store_transaction_begin(refs->packed_ref_store, &err);1114if(!transaction)1115return-1;11161117packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);11181119 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1120while((ok =ref_iterator_advance(iter)) == ITER_OK) {1121/*1122 * If the loose reference can be packed, add an entry1123 * in the packed ref cache. If the reference should be1124 * pruned, also add it to refs_to_prune.1125 */1126if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1127 flags))1128continue;11291130/*1131 * Add a reference creation for this reference to the1132 * packed-refs transaction:1133 */1134if(ref_transaction_update(transaction, iter->refname,1135 iter->oid->hash, NULL,1136 REF_NODEREF, NULL, &err))1137die("failure preparing to create packed reference%s:%s",1138 iter->refname, err.buf);11391140/* Schedule the loose reference for pruning if requested. */1141if((flags & PACK_REFS_PRUNE)) {1142struct ref_to_prune *n;1143FLEX_ALLOC_STR(n, name, iter->refname);1144hashcpy(n->sha1, iter->oid->hash);1145 n->next = refs_to_prune;1146 refs_to_prune = n;1147}1148}1149if(ok != ITER_DONE)1150die("error while iterating over references");11511152if(ref_transaction_commit(transaction, &err))1153die("unable to write new packed-refs:%s", err.buf);11541155ref_transaction_free(transaction);11561157packed_refs_unlock(refs->packed_ref_store);11581159prune_refs(refs, &refs_to_prune);1160strbuf_release(&err);1161return0;1162}11631164static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1165struct string_list *refnames,unsigned int flags)1166{1167struct files_ref_store *refs =1168files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1169struct strbuf err = STRBUF_INIT;1170int i, result =0;11711172if(!refnames->nr)1173return0;11741175if(packed_refs_lock(refs->packed_ref_store,0, &err))1176goto error;11771178if(refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {1179packed_refs_unlock(refs->packed_ref_store);1180goto error;1181}11821183packed_refs_unlock(refs->packed_ref_store);11841185for(i =0; i < refnames->nr; i++) {1186const char*refname = refnames->items[i].string;11871188if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1189 result |=error(_("could not remove reference%s"), refname);1190}11911192strbuf_release(&err);1193return result;11941195error:1196/*1197 * If we failed to rewrite the packed-refs file, then it is1198 * unsafe to try to remove loose refs, because doing so might1199 * expose an obsolete packed value for a reference that might1200 * even point at an object that has been garbage collected.1201 */1202if(refnames->nr ==1)1203error(_("could not delete reference%s:%s"),1204 refnames->items[0].string, err.buf);1205else1206error(_("could not delete references:%s"), err.buf);12071208strbuf_release(&err);1209return-1;1210}12111212/*1213 * People using contrib's git-new-workdir have .git/logs/refs ->1214 * /some/other/path/.git/logs/refs, and that may live on another device.1215 *1216 * IOW, to avoid cross device rename errors, the temporary renamed log must1217 * live into logs/refs.1218 */1219#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"12201221struct rename_cb {1222const char*tmp_renamed_log;1223int true_errno;1224};12251226static intrename_tmp_log_callback(const char*path,void*cb_data)1227{1228struct rename_cb *cb = cb_data;12291230if(rename(cb->tmp_renamed_log, path)) {1231/*1232 * rename(a, b) when b is an existing directory ought1233 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1234 * Sheesh. Record the true errno for error reporting,1235 * but report EISDIR to raceproof_create_file() so1236 * that it knows to retry.1237 */1238 cb->true_errno = errno;1239if(errno == ENOTDIR)1240 errno = EISDIR;1241return-1;1242}else{1243return0;1244}1245}12461247static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1248{1249struct strbuf path = STRBUF_INIT;1250struct strbuf tmp = STRBUF_INIT;1251struct rename_cb cb;1252int ret;12531254files_reflog_path(refs, &path, newrefname);1255files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1256 cb.tmp_renamed_log = tmp.buf;1257 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1258if(ret) {1259if(errno == EISDIR)1260error("directory not empty:%s", path.buf);1261else1262error("unable to move logfile%sto%s:%s",1263 tmp.buf, path.buf,1264strerror(cb.true_errno));1265}12661267strbuf_release(&path);1268strbuf_release(&tmp);1269return ret;1270}12711272static intwrite_ref_to_lockfile(struct ref_lock *lock,1273const struct object_id *oid,struct strbuf *err);1274static intcommit_ref_update(struct files_ref_store *refs,1275struct ref_lock *lock,1276const struct object_id *oid,const char*logmsg,1277struct strbuf *err);12781279static intfiles_rename_ref(struct ref_store *ref_store,1280const char*oldrefname,const char*newrefname,1281const char*logmsg)1282{1283struct files_ref_store *refs =1284files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1285struct object_id oid, orig_oid;1286int flag =0, logmoved =0;1287struct ref_lock *lock;1288struct stat loginfo;1289struct strbuf sb_oldref = STRBUF_INIT;1290struct strbuf sb_newref = STRBUF_INIT;1291struct strbuf tmp_renamed_log = STRBUF_INIT;1292int log, ret;1293struct strbuf err = STRBUF_INIT;12941295files_reflog_path(refs, &sb_oldref, oldrefname);1296files_reflog_path(refs, &sb_newref, newrefname);1297files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12981299 log = !lstat(sb_oldref.buf, &loginfo);1300if(log &&S_ISLNK(loginfo.st_mode)) {1301 ret =error("reflog for%sis a symlink", oldrefname);1302goto out;1303}13041305if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1306 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1307 orig_oid.hash, &flag)) {1308 ret =error("refname%snot found", oldrefname);1309goto out;1310}13111312if(flag & REF_ISSYMREF) {1313 ret =error("refname%sis a symbolic ref, renaming it is not supported",1314 oldrefname);1315goto out;1316}1317if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1318 ret =1;1319goto out;1320}13211322if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1323 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1324 oldrefname,strerror(errno));1325goto out;1326}13271328if(refs_delete_ref(&refs->base, logmsg, oldrefname,1329 orig_oid.hash, REF_NODEREF)) {1330error("unable to delete old%s", oldrefname);1331goto rollback;1332}13331334/*1335 * Since we are doing a shallow lookup, oid is not the1336 * correct value to pass to delete_ref as old_oid. But that1337 * doesn't matter, because an old_oid check wouldn't add to1338 * the safety anyway; we want to delete the reference whatever1339 * its current value.1340 */1341if(!refs_read_ref_full(&refs->base, newrefname,1342 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1343 oid.hash, NULL) &&1344refs_delete_ref(&refs->base, NULL, newrefname,1345 NULL, REF_NODEREF)) {1346if(errno == EISDIR) {1347struct strbuf path = STRBUF_INIT;1348int result;13491350files_ref_path(refs, &path, newrefname);1351 result =remove_empty_directories(&path);1352strbuf_release(&path);13531354if(result) {1355error("Directory not empty:%s", newrefname);1356goto rollback;1357}1358}else{1359error("unable to delete existing%s", newrefname);1360goto rollback;1361}1362}13631364if(log &&rename_tmp_log(refs, newrefname))1365goto rollback;13661367 logmoved = log;13681369 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1370 REF_NODEREF, NULL, &err);1371if(!lock) {1372error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1373strbuf_release(&err);1374goto rollback;1375}1376oidcpy(&lock->old_oid, &orig_oid);13771378if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1379commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1380error("unable to write current sha1 into%s:%s", newrefname, err.buf);1381strbuf_release(&err);1382goto rollback;1383}13841385 ret =0;1386goto out;13871388 rollback:1389 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1390 REF_NODEREF, NULL, &err);1391if(!lock) {1392error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1393strbuf_release(&err);1394goto rollbacklog;1395}13961397 flag = log_all_ref_updates;1398 log_all_ref_updates = LOG_REFS_NONE;1399if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1400commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1401error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1402strbuf_release(&err);1403}1404 log_all_ref_updates = flag;14051406 rollbacklog:1407if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1408error("unable to restore logfile%sfrom%s:%s",1409 oldrefname, newrefname,strerror(errno));1410if(!logmoved && log &&1411rename(tmp_renamed_log.buf, sb_oldref.buf))1412error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1413 oldrefname,strerror(errno));1414 ret =1;1415 out:1416strbuf_release(&sb_newref);1417strbuf_release(&sb_oldref);1418strbuf_release(&tmp_renamed_log);14191420return ret;1421}14221423static intclose_ref(struct ref_lock *lock)1424{1425if(close_lock_file(lock->lk))1426return-1;1427return0;1428}14291430static intcommit_ref(struct ref_lock *lock)1431{1432char*path =get_locked_file_path(lock->lk);1433struct stat st;14341435if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1436/*1437 * There is a directory at the path we want to rename1438 * the lockfile to. Hopefully it is empty; try to1439 * delete it.1440 */1441size_t len =strlen(path);1442struct strbuf sb_path = STRBUF_INIT;14431444strbuf_attach(&sb_path, path, len, len);14451446/*1447 * If this fails, commit_lock_file() will also fail1448 * and will report the problem.1449 */1450remove_empty_directories(&sb_path);1451strbuf_release(&sb_path);1452}else{1453free(path);1454}14551456if(commit_lock_file(lock->lk))1457return-1;1458return0;1459}14601461static intopen_or_create_logfile(const char*path,void*cb)1462{1463int*fd = cb;14641465*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1466return(*fd <0) ? -1:0;1467}14681469/*1470 * Create a reflog for a ref. If force_create = 0, only create the1471 * reflog for certain refs (those for which should_autocreate_reflog1472 * returns non-zero). Otherwise, create it regardless of the reference1473 * name. If the logfile already existed or was created, return 0 and1474 * set *logfd to the file descriptor opened for appending to the file.1475 * If no logfile exists and we decided not to create one, return 0 and1476 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1477 * return -1.1478 */1479static intlog_ref_setup(struct files_ref_store *refs,1480const char*refname,int force_create,1481int*logfd,struct strbuf *err)1482{1483struct strbuf logfile_sb = STRBUF_INIT;1484char*logfile;14851486files_reflog_path(refs, &logfile_sb, refname);1487 logfile =strbuf_detach(&logfile_sb, NULL);14881489if(force_create ||should_autocreate_reflog(refname)) {1490if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1491if(errno == ENOENT)1492strbuf_addf(err,"unable to create directory for '%s': "1493"%s", logfile,strerror(errno));1494else if(errno == EISDIR)1495strbuf_addf(err,"there are still logs under '%s'",1496 logfile);1497else1498strbuf_addf(err,"unable to append to '%s':%s",1499 logfile,strerror(errno));15001501goto error;1502}1503}else{1504*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1505if(*logfd <0) {1506if(errno == ENOENT || errno == EISDIR) {1507/*1508 * The logfile doesn't already exist,1509 * but that is not an error; it only1510 * means that we won't write log1511 * entries to it.1512 */1513;1514}else{1515strbuf_addf(err,"unable to append to '%s':%s",1516 logfile,strerror(errno));1517goto error;1518}1519}1520}15211522if(*logfd >=0)1523adjust_shared_perm(logfile);15241525free(logfile);1526return0;15271528error:1529free(logfile);1530return-1;1531}15321533static intfiles_create_reflog(struct ref_store *ref_store,1534const char*refname,int force_create,1535struct strbuf *err)1536{1537struct files_ref_store *refs =1538files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1539int fd;15401541if(log_ref_setup(refs, refname, force_create, &fd, err))1542return-1;15431544if(fd >=0)1545close(fd);15461547return0;1548}15491550static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1551const struct object_id *new_oid,1552const char*committer,const char*msg)1553{1554int msglen, written;1555unsigned maxlen, len;1556char*logrec;15571558 msglen = msg ?strlen(msg) :0;1559 maxlen =strlen(committer) + msglen +100;1560 logrec =xmalloc(maxlen);1561 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1562oid_to_hex(old_oid),1563oid_to_hex(new_oid),1564 committer);1565if(msglen)1566 len +=copy_reflog_msg(logrec + len -1, msg) -1;15671568 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1569free(logrec);1570if(written != len)1571return-1;15721573return0;1574}15751576static intfiles_log_ref_write(struct files_ref_store *refs,1577const char*refname,const struct object_id *old_oid,1578const struct object_id *new_oid,const char*msg,1579int flags,struct strbuf *err)1580{1581int logfd, result;15821583if(log_all_ref_updates == LOG_REFS_UNSET)1584 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15851586 result =log_ref_setup(refs, refname,1587 flags & REF_FORCE_CREATE_REFLOG,1588&logfd, err);15891590if(result)1591return result;15921593if(logfd <0)1594return0;1595 result =log_ref_write_fd(logfd, old_oid, new_oid,1596git_committer_info(0), msg);1597if(result) {1598struct strbuf sb = STRBUF_INIT;1599int save_errno = errno;16001601files_reflog_path(refs, &sb, refname);1602strbuf_addf(err,"unable to append to '%s':%s",1603 sb.buf,strerror(save_errno));1604strbuf_release(&sb);1605close(logfd);1606return-1;1607}1608if(close(logfd)) {1609struct strbuf sb = STRBUF_INIT;1610int save_errno = errno;16111612files_reflog_path(refs, &sb, refname);1613strbuf_addf(err,"unable to append to '%s':%s",1614 sb.buf,strerror(save_errno));1615strbuf_release(&sb);1616return-1;1617}1618return0;1619}16201621/*1622 * Write sha1 into the open lockfile, then close the lockfile. On1623 * errors, rollback the lockfile, fill in *err and1624 * return -1.1625 */1626static intwrite_ref_to_lockfile(struct ref_lock *lock,1627const struct object_id *oid,struct strbuf *err)1628{1629static char term ='\n';1630struct object *o;1631int fd;16321633 o =parse_object(oid);1634if(!o) {1635strbuf_addf(err,1636"trying to write ref '%s' with nonexistent object%s",1637 lock->ref_name,oid_to_hex(oid));1638unlock_ref(lock);1639return-1;1640}1641if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1642strbuf_addf(err,1643"trying to write non-commit object%sto branch '%s'",1644oid_to_hex(oid), lock->ref_name);1645unlock_ref(lock);1646return-1;1647}1648 fd =get_lock_file_fd(lock->lk);1649if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1650write_in_full(fd, &term,1) !=1||1651close_ref(lock) <0) {1652strbuf_addf(err,1653"couldn't write '%s'",get_lock_file_path(lock->lk));1654unlock_ref(lock);1655return-1;1656}1657return0;1658}16591660/*1661 * Commit a change to a loose reference that has already been written1662 * to the loose reference lockfile. Also update the reflogs if1663 * necessary, using the specified lockmsg (which can be NULL).1664 */1665static intcommit_ref_update(struct files_ref_store *refs,1666struct ref_lock *lock,1667const struct object_id *oid,const char*logmsg,1668struct strbuf *err)1669{1670files_assert_main_repository(refs,"commit_ref_update");16711672clear_loose_ref_cache(refs);1673if(files_log_ref_write(refs, lock->ref_name,1674&lock->old_oid, oid,1675 logmsg,0, err)) {1676char*old_msg =strbuf_detach(err, NULL);1677strbuf_addf(err,"cannot update the ref '%s':%s",1678 lock->ref_name, old_msg);1679free(old_msg);1680unlock_ref(lock);1681return-1;1682}16831684if(strcmp(lock->ref_name,"HEAD") !=0) {1685/*1686 * Special hack: If a branch is updated directly and HEAD1687 * points to it (may happen on the remote side of a push1688 * for example) then logically the HEAD reflog should be1689 * updated too.1690 * A generic solution implies reverse symref information,1691 * but finding all symrefs pointing to the given branch1692 * would be rather costly for this rare event (the direct1693 * update of a branch) to be worth it. So let's cheat and1694 * check with HEAD only which should cover 99% of all usage1695 * scenarios (even 100% of the default ones).1696 */1697struct object_id head_oid;1698int head_flag;1699const char*head_ref;17001701 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1702 RESOLVE_REF_READING,1703 head_oid.hash, &head_flag);1704if(head_ref && (head_flag & REF_ISSYMREF) &&1705!strcmp(head_ref, lock->ref_name)) {1706struct strbuf log_err = STRBUF_INIT;1707if(files_log_ref_write(refs,"HEAD",1708&lock->old_oid, oid,1709 logmsg,0, &log_err)) {1710error("%s", log_err.buf);1711strbuf_release(&log_err);1712}1713}1714}17151716if(commit_ref(lock)) {1717strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1718unlock_ref(lock);1719return-1;1720}17211722unlock_ref(lock);1723return0;1724}17251726static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1727{1728int ret = -1;1729#ifndef NO_SYMLINK_HEAD1730char*ref_path =get_locked_file_path(lock->lk);1731unlink(ref_path);1732 ret =symlink(target, ref_path);1733free(ref_path);17341735if(ret)1736fprintf(stderr,"no symlink - falling back to symbolic ref\n");1737#endif1738return ret;1739}17401741static voidupdate_symref_reflog(struct files_ref_store *refs,1742struct ref_lock *lock,const char*refname,1743const char*target,const char*logmsg)1744{1745struct strbuf err = STRBUF_INIT;1746struct object_id new_oid;1747if(logmsg &&1748!refs_read_ref_full(&refs->base, target,1749 RESOLVE_REF_READING, new_oid.hash, NULL) &&1750files_log_ref_write(refs, refname, &lock->old_oid,1751&new_oid, logmsg,0, &err)) {1752error("%s", err.buf);1753strbuf_release(&err);1754}1755}17561757static intcreate_symref_locked(struct files_ref_store *refs,1758struct ref_lock *lock,const char*refname,1759const char*target,const char*logmsg)1760{1761if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1762update_symref_reflog(refs, lock, refname, target, logmsg);1763return0;1764}17651766if(!fdopen_lock_file(lock->lk,"w"))1767returnerror("unable to fdopen%s:%s",1768 lock->lk->tempfile.filename.buf,strerror(errno));17691770update_symref_reflog(refs, lock, refname, target, logmsg);17711772/* no error check; commit_ref will check ferror */1773fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1774if(commit_ref(lock) <0)1775returnerror("unable to write symref for%s:%s", refname,1776strerror(errno));1777return0;1778}17791780static intfiles_create_symref(struct ref_store *ref_store,1781const char*refname,const char*target,1782const char*logmsg)1783{1784struct files_ref_store *refs =1785files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1786struct strbuf err = STRBUF_INIT;1787struct ref_lock *lock;1788int ret;17891790 lock =lock_ref_sha1_basic(refs, refname, NULL,1791 NULL, NULL, REF_NODEREF, NULL,1792&err);1793if(!lock) {1794error("%s", err.buf);1795strbuf_release(&err);1796return-1;1797}17981799 ret =create_symref_locked(refs, lock, refname, target, logmsg);1800unlock_ref(lock);1801return ret;1802}18031804static intfiles_reflog_exists(struct ref_store *ref_store,1805const char*refname)1806{1807struct files_ref_store *refs =1808files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1809struct strbuf sb = STRBUF_INIT;1810struct stat st;1811int ret;18121813files_reflog_path(refs, &sb, refname);1814 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1815strbuf_release(&sb);1816return ret;1817}18181819static intfiles_delete_reflog(struct ref_store *ref_store,1820const char*refname)1821{1822struct files_ref_store *refs =1823files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1824struct strbuf sb = STRBUF_INIT;1825int ret;18261827files_reflog_path(refs, &sb, refname);1828 ret =remove_path(sb.buf);1829strbuf_release(&sb);1830return ret;1831}18321833static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1834{1835struct object_id ooid, noid;1836char*email_end, *message;1837 timestamp_t timestamp;1838int tz;1839const char*p = sb->buf;18401841/* old SP new SP name <email> SP time TAB msg LF */1842if(!sb->len || sb->buf[sb->len -1] !='\n'||1843parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1844parse_oid_hex(p, &noid, &p) || *p++ !=' '||1845!(email_end =strchr(p,'>')) ||1846 email_end[1] !=' '||1847!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1848!message || message[0] !=' '||1849(message[1] !='+'&& message[1] !='-') ||1850!isdigit(message[2]) || !isdigit(message[3]) ||1851!isdigit(message[4]) || !isdigit(message[5]))1852return0;/* corrupt? */1853 email_end[1] ='\0';1854 tz =strtol(message +1, NULL,10);1855if(message[6] !='\t')1856 message +=6;1857else1858 message +=7;1859returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1860}18611862static char*find_beginning_of_line(char*bob,char*scan)1863{1864while(bob < scan && *(--scan) !='\n')1865;/* keep scanning backwards */1866/*1867 * Return either beginning of the buffer, or LF at the end of1868 * the previous line.1869 */1870return scan;1871}18721873static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1874const char*refname,1875 each_reflog_ent_fn fn,1876void*cb_data)1877{1878struct files_ref_store *refs =1879files_downcast(ref_store, REF_STORE_READ,1880"for_each_reflog_ent_reverse");1881struct strbuf sb = STRBUF_INIT;1882FILE*logfp;1883long pos;1884int ret =0, at_tail =1;18851886files_reflog_path(refs, &sb, refname);1887 logfp =fopen(sb.buf,"r");1888strbuf_release(&sb);1889if(!logfp)1890return-1;18911892/* Jump to the end */1893if(fseek(logfp,0, SEEK_END) <0)1894 ret =error("cannot seek back reflog for%s:%s",1895 refname,strerror(errno));1896 pos =ftell(logfp);1897while(!ret &&0< pos) {1898int cnt;1899size_t nread;1900char buf[BUFSIZ];1901char*endp, *scanp;19021903/* Fill next block from the end */1904 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1905if(fseek(logfp, pos - cnt, SEEK_SET)) {1906 ret =error("cannot seek back reflog for%s:%s",1907 refname,strerror(errno));1908break;1909}1910 nread =fread(buf, cnt,1, logfp);1911if(nread !=1) {1912 ret =error("cannot read%dbytes from reflog for%s:%s",1913 cnt, refname,strerror(errno));1914break;1915}1916 pos -= cnt;19171918 scanp = endp = buf + cnt;1919if(at_tail && scanp[-1] =='\n')1920/* Looking at the final LF at the end of the file */1921 scanp--;1922 at_tail =0;19231924while(buf < scanp) {1925/*1926 * terminating LF of the previous line, or the beginning1927 * of the buffer.1928 */1929char*bp;19301931 bp =find_beginning_of_line(buf, scanp);19321933if(*bp =='\n') {1934/*1935 * The newline is the end of the previous line,1936 * so we know we have complete line starting1937 * at (bp + 1). Prefix it onto any prior data1938 * we collected for the line and process it.1939 */1940strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1941 scanp = bp;1942 endp = bp +1;1943 ret =show_one_reflog_ent(&sb, fn, cb_data);1944strbuf_reset(&sb);1945if(ret)1946break;1947}else if(!pos) {1948/*1949 * We are at the start of the buffer, and the1950 * start of the file; there is no previous1951 * line, and we have everything for this one.1952 * Process it, and we can end the loop.1953 */1954strbuf_splice(&sb,0,0, buf, endp - buf);1955 ret =show_one_reflog_ent(&sb, fn, cb_data);1956strbuf_reset(&sb);1957break;1958}19591960if(bp == buf) {1961/*1962 * We are at the start of the buffer, and there1963 * is more file to read backwards. Which means1964 * we are in the middle of a line. Note that we1965 * may get here even if *bp was a newline; that1966 * just means we are at the exact end of the1967 * previous line, rather than some spot in the1968 * middle.1969 *1970 * Save away what we have to be combined with1971 * the data from the next read.1972 */1973strbuf_splice(&sb,0,0, buf, endp - buf);1974break;1975}1976}19771978}1979if(!ret && sb.len)1980die("BUG: reverse reflog parser had leftover data");19811982fclose(logfp);1983strbuf_release(&sb);1984return ret;1985}19861987static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1988const char*refname,1989 each_reflog_ent_fn fn,void*cb_data)1990{1991struct files_ref_store *refs =1992files_downcast(ref_store, REF_STORE_READ,1993"for_each_reflog_ent");1994FILE*logfp;1995struct strbuf sb = STRBUF_INIT;1996int ret =0;19971998files_reflog_path(refs, &sb, refname);1999 logfp =fopen(sb.buf,"r");2000strbuf_release(&sb);2001if(!logfp)2002return-1;20032004while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2005 ret =show_one_reflog_ent(&sb, fn, cb_data);2006fclose(logfp);2007strbuf_release(&sb);2008return ret;2009}20102011struct files_reflog_iterator {2012struct ref_iterator base;20132014struct ref_store *ref_store;2015struct dir_iterator *dir_iterator;2016struct object_id oid;2017};20182019static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2020{2021struct files_reflog_iterator *iter =2022(struct files_reflog_iterator *)ref_iterator;2023struct dir_iterator *diter = iter->dir_iterator;2024int ok;20252026while((ok =dir_iterator_advance(diter)) == ITER_OK) {2027int flags;20282029if(!S_ISREG(diter->st.st_mode))2030continue;2031if(diter->basename[0] =='.')2032continue;2033if(ends_with(diter->basename,".lock"))2034continue;20352036if(refs_read_ref_full(iter->ref_store,2037 diter->relative_path,0,2038 iter->oid.hash, &flags)) {2039error("bad ref for%s", diter->path.buf);2040continue;2041}20422043 iter->base.refname = diter->relative_path;2044 iter->base.oid = &iter->oid;2045 iter->base.flags = flags;2046return ITER_OK;2047}20482049 iter->dir_iterator = NULL;2050if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2051 ok = ITER_ERROR;2052return ok;2053}20542055static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2056struct object_id *peeled)2057{2058die("BUG: ref_iterator_peel() called for reflog_iterator");2059}20602061static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2062{2063struct files_reflog_iterator *iter =2064(struct files_reflog_iterator *)ref_iterator;2065int ok = ITER_DONE;20662067if(iter->dir_iterator)2068 ok =dir_iterator_abort(iter->dir_iterator);20692070base_ref_iterator_free(ref_iterator);2071return ok;2072}20732074static struct ref_iterator_vtable files_reflog_iterator_vtable = {2075 files_reflog_iterator_advance,2076 files_reflog_iterator_peel,2077 files_reflog_iterator_abort2078};20792080static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2081{2082struct files_ref_store *refs =2083files_downcast(ref_store, REF_STORE_READ,2084"reflog_iterator_begin");2085struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2086struct ref_iterator *ref_iterator = &iter->base;2087struct strbuf sb = STRBUF_INIT;20882089base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable,0);2090files_reflog_path(refs, &sb, NULL);2091 iter->dir_iterator =dir_iterator_begin(sb.buf);2092 iter->ref_store = ref_store;2093strbuf_release(&sb);2094return ref_iterator;2095}20962097/*2098 * If update is a direct update of head_ref (the reference pointed to2099 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2100 */2101static intsplit_head_update(struct ref_update *update,2102struct ref_transaction *transaction,2103const char*head_ref,2104struct string_list *affected_refnames,2105struct strbuf *err)2106{2107struct string_list_item *item;2108struct ref_update *new_update;21092110if((update->flags & REF_LOG_ONLY) ||2111(update->flags & REF_ISPRUNING) ||2112(update->flags & REF_UPDATE_VIA_HEAD))2113return0;21142115if(strcmp(update->refname, head_ref))2116return0;21172118/*2119 * First make sure that HEAD is not already in the2120 * transaction. This insertion is O(N) in the transaction2121 * size, but it happens at most once per transaction.2122 */2123 item =string_list_insert(affected_refnames,"HEAD");2124if(item->util) {2125/* An entry already existed */2126strbuf_addf(err,2127"multiple updates for 'HEAD' (including one "2128"via its referent '%s') are not allowed",2129 update->refname);2130return TRANSACTION_NAME_CONFLICT;2131}21322133 new_update =ref_transaction_add_update(2134 transaction,"HEAD",2135 update->flags | REF_LOG_ONLY | REF_NODEREF,2136 update->new_oid.hash, update->old_oid.hash,2137 update->msg);21382139 item->util = new_update;21402141return0;2142}21432144/*2145 * update is for a symref that points at referent and doesn't have2146 * REF_NODEREF set. Split it into two updates:2147 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2148 * - A new, separate update for the referent reference2149 * Note that the new update will itself be subject to splitting when2150 * the iteration gets to it.2151 */2152static intsplit_symref_update(struct files_ref_store *refs,2153struct ref_update *update,2154const char*referent,2155struct ref_transaction *transaction,2156struct string_list *affected_refnames,2157struct strbuf *err)2158{2159struct string_list_item *item;2160struct ref_update *new_update;2161unsigned int new_flags;21622163/*2164 * First make sure that referent is not already in the2165 * transaction. This insertion is O(N) in the transaction2166 * size, but it happens at most once per symref in a2167 * transaction.2168 */2169 item =string_list_insert(affected_refnames, referent);2170if(item->util) {2171/* An entry already existed */2172strbuf_addf(err,2173"multiple updates for '%s' (including one "2174"via symref '%s') are not allowed",2175 referent, update->refname);2176return TRANSACTION_NAME_CONFLICT;2177}21782179 new_flags = update->flags;2180if(!strcmp(update->refname,"HEAD")) {2181/*2182 * Record that the new update came via HEAD, so that2183 * when we process it, split_head_update() doesn't try2184 * to add another reflog update for HEAD. Note that2185 * this bit will be propagated if the new_update2186 * itself needs to be split.2187 */2188 new_flags |= REF_UPDATE_VIA_HEAD;2189}21902191 new_update =ref_transaction_add_update(2192 transaction, referent, new_flags,2193 update->new_oid.hash, update->old_oid.hash,2194 update->msg);21952196 new_update->parent_update = update;21972198/*2199 * Change the symbolic ref update to log only. Also, it2200 * doesn't need to check its old SHA-1 value, as that will be2201 * done when new_update is processed.2202 */2203 update->flags |= REF_LOG_ONLY | REF_NODEREF;2204 update->flags &= ~REF_HAVE_OLD;22052206 item->util = new_update;22072208return0;2209}22102211/*2212 * Return the refname under which update was originally requested.2213 */2214static const char*original_update_refname(struct ref_update *update)2215{2216while(update->parent_update)2217 update = update->parent_update;22182219return update->refname;2220}22212222/*2223 * Check whether the REF_HAVE_OLD and old_oid values stored in update2224 * are consistent with oid, which is the reference's current value. If2225 * everything is OK, return 0; otherwise, write an error message to2226 * err and return -1.2227 */2228static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2229struct strbuf *err)2230{2231if(!(update->flags & REF_HAVE_OLD) ||2232!oidcmp(oid, &update->old_oid))2233return0;22342235if(is_null_oid(&update->old_oid))2236strbuf_addf(err,"cannot lock ref '%s': "2237"reference already exists",2238original_update_refname(update));2239else if(is_null_oid(oid))2240strbuf_addf(err,"cannot lock ref '%s': "2241"reference is missing but expected%s",2242original_update_refname(update),2243oid_to_hex(&update->old_oid));2244else2245strbuf_addf(err,"cannot lock ref '%s': "2246"is at%sbut expected%s",2247original_update_refname(update),2248oid_to_hex(oid),2249oid_to_hex(&update->old_oid));22502251return-1;2252}22532254/*2255 * Prepare for carrying out update:2256 * - Lock the reference referred to by update.2257 * - Read the reference under lock.2258 * - Check that its old SHA-1 value (if specified) is correct, and in2259 * any case record it in update->lock->old_oid for later use when2260 * writing the reflog.2261 * - If it is a symref update without REF_NODEREF, split it up into a2262 * REF_LOG_ONLY update of the symref and add a separate update for2263 * the referent to transaction.2264 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2265 * update of HEAD.2266 */2267static intlock_ref_for_update(struct files_ref_store *refs,2268struct ref_update *update,2269struct ref_transaction *transaction,2270const char*head_ref,2271struct string_list *affected_refnames,2272struct strbuf *err)2273{2274struct strbuf referent = STRBUF_INIT;2275int mustexist = (update->flags & REF_HAVE_OLD) &&2276!is_null_oid(&update->old_oid);2277int ret;2278struct ref_lock *lock;22792280files_assert_main_repository(refs,"lock_ref_for_update");22812282if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2283 update->flags |= REF_DELETING;22842285if(head_ref) {2286 ret =split_head_update(update, transaction, head_ref,2287 affected_refnames, err);2288if(ret)2289return ret;2290}22912292 ret =lock_raw_ref(refs, update->refname, mustexist,2293 affected_refnames, NULL,2294&lock, &referent,2295&update->type, err);2296if(ret) {2297char*reason;22982299 reason =strbuf_detach(err, NULL);2300strbuf_addf(err,"cannot lock ref '%s':%s",2301original_update_refname(update), reason);2302free(reason);2303return ret;2304}23052306 update->backend_data = lock;23072308if(update->type & REF_ISSYMREF) {2309if(update->flags & REF_NODEREF) {2310/*2311 * We won't be reading the referent as part of2312 * the transaction, so we have to read it here2313 * to record and possibly check old_sha1:2314 */2315if(refs_read_ref_full(&refs->base,2316 referent.buf,0,2317 lock->old_oid.hash, NULL)) {2318if(update->flags & REF_HAVE_OLD) {2319strbuf_addf(err,"cannot lock ref '%s': "2320"error reading reference",2321original_update_refname(update));2322return-1;2323}2324}else if(check_old_oid(update, &lock->old_oid, err)) {2325return TRANSACTION_GENERIC_ERROR;2326}2327}else{2328/*2329 * Create a new update for the reference this2330 * symref is pointing at. Also, we will record2331 * and verify old_sha1 for this update as part2332 * of processing the split-off update, so we2333 * don't have to do it here.2334 */2335 ret =split_symref_update(refs, update,2336 referent.buf, transaction,2337 affected_refnames, err);2338if(ret)2339return ret;2340}2341}else{2342struct ref_update *parent_update;23432344if(check_old_oid(update, &lock->old_oid, err))2345return TRANSACTION_GENERIC_ERROR;23462347/*2348 * If this update is happening indirectly because of a2349 * symref update, record the old SHA-1 in the parent2350 * update:2351 */2352for(parent_update = update->parent_update;2353 parent_update;2354 parent_update = parent_update->parent_update) {2355struct ref_lock *parent_lock = parent_update->backend_data;2356oidcpy(&parent_lock->old_oid, &lock->old_oid);2357}2358}23592360if((update->flags & REF_HAVE_NEW) &&2361!(update->flags & REF_DELETING) &&2362!(update->flags & REF_LOG_ONLY)) {2363if(!(update->type & REF_ISSYMREF) &&2364!oidcmp(&lock->old_oid, &update->new_oid)) {2365/*2366 * The reference already has the desired2367 * value, so we don't need to write it.2368 */2369}else if(write_ref_to_lockfile(lock, &update->new_oid,2370 err)) {2371char*write_err =strbuf_detach(err, NULL);23722373/*2374 * The lock was freed upon failure of2375 * write_ref_to_lockfile():2376 */2377 update->backend_data = NULL;2378strbuf_addf(err,2379"cannot update ref '%s':%s",2380 update->refname, write_err);2381free(write_err);2382return TRANSACTION_GENERIC_ERROR;2383}else{2384 update->flags |= REF_NEEDS_COMMIT;2385}2386}2387if(!(update->flags & REF_NEEDS_COMMIT)) {2388/*2389 * We didn't call write_ref_to_lockfile(), so2390 * the lockfile is still open. Close it to2391 * free up the file descriptor:2392 */2393if(close_ref(lock)) {2394strbuf_addf(err,"couldn't close '%s.lock'",2395 update->refname);2396return TRANSACTION_GENERIC_ERROR;2397}2398}2399return0;2400}24012402struct files_transaction_backend_data {2403struct ref_transaction *packed_transaction;2404int packed_refs_locked;2405};24062407/*2408 * Unlock any references in `transaction` that are still locked, and2409 * mark the transaction closed.2410 */2411static voidfiles_transaction_cleanup(struct files_ref_store *refs,2412struct ref_transaction *transaction)2413{2414size_t i;2415struct files_transaction_backend_data *backend_data =2416 transaction->backend_data;2417struct strbuf err = STRBUF_INIT;24182419for(i =0; i < transaction->nr; i++) {2420struct ref_update *update = transaction->updates[i];2421struct ref_lock *lock = update->backend_data;24222423if(lock) {2424unlock_ref(lock);2425 update->backend_data = NULL;2426}2427}24282429if(backend_data->packed_transaction &&2430ref_transaction_abort(backend_data->packed_transaction, &err)) {2431error("error aborting transaction:%s", err.buf);2432strbuf_release(&err);2433}24342435if(backend_data->packed_refs_locked)2436packed_refs_unlock(refs->packed_ref_store);24372438free(backend_data);24392440 transaction->state = REF_TRANSACTION_CLOSED;2441}24422443static intfiles_transaction_prepare(struct ref_store *ref_store,2444struct ref_transaction *transaction,2445struct strbuf *err)2446{2447struct files_ref_store *refs =2448files_downcast(ref_store, REF_STORE_WRITE,2449"ref_transaction_prepare");2450size_t i;2451int ret =0;2452struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2453char*head_ref = NULL;2454int head_type;2455struct object_id head_oid;2456struct files_transaction_backend_data *backend_data;2457struct ref_transaction *packed_transaction = NULL;24582459assert(err);24602461if(!transaction->nr)2462goto cleanup;24632464 backend_data =xcalloc(1,sizeof(*backend_data));2465 transaction->backend_data = backend_data;24662467/*2468 * Fail if a refname appears more than once in the2469 * transaction. (If we end up splitting up any updates using2470 * split_symref_update() or split_head_update(), those2471 * functions will check that the new updates don't have the2472 * same refname as any existing ones.)2473 */2474for(i =0; i < transaction->nr; i++) {2475struct ref_update *update = transaction->updates[i];2476struct string_list_item *item =2477string_list_append(&affected_refnames, update->refname);24782479/*2480 * We store a pointer to update in item->util, but at2481 * the moment we never use the value of this field2482 * except to check whether it is non-NULL.2483 */2484 item->util = update;2485}2486string_list_sort(&affected_refnames);2487if(ref_update_reject_duplicates(&affected_refnames, err)) {2488 ret = TRANSACTION_GENERIC_ERROR;2489goto cleanup;2490}24912492/*2493 * Special hack: If a branch is updated directly and HEAD2494 * points to it (may happen on the remote side of a push2495 * for example) then logically the HEAD reflog should be2496 * updated too.2497 *2498 * A generic solution would require reverse symref lookups,2499 * but finding all symrefs pointing to a given branch would be2500 * rather costly for this rare event (the direct update of a2501 * branch) to be worth it. So let's cheat and check with HEAD2502 * only, which should cover 99% of all usage scenarios (even2503 * 100% of the default ones).2504 *2505 * So if HEAD is a symbolic reference, then record the name of2506 * the reference that it points to. If we see an update of2507 * head_ref within the transaction, then split_head_update()2508 * arranges for the reflog of HEAD to be updated, too.2509 */2510 head_ref =refs_resolve_refdup(ref_store,"HEAD",2511 RESOLVE_REF_NO_RECURSE,2512 head_oid.hash, &head_type);25132514if(head_ref && !(head_type & REF_ISSYMREF)) {2515FREE_AND_NULL(head_ref);2516}25172518/*2519 * Acquire all locks, verify old values if provided, check2520 * that new values are valid, and write new values to the2521 * lockfiles, ready to be activated. Only keep one lockfile2522 * open at a time to avoid running out of file descriptors.2523 * Note that lock_ref_for_update() might append more updates2524 * to the transaction.2525 */2526for(i =0; i < transaction->nr; i++) {2527struct ref_update *update = transaction->updates[i];25282529 ret =lock_ref_for_update(refs, update, transaction,2530 head_ref, &affected_refnames, err);2531if(ret)2532break;25332534if(update->flags & REF_DELETING &&2535!(update->flags & REF_LOG_ONLY) &&2536!(update->flags & REF_ISPRUNING)) {2537/*2538 * This reference has to be deleted from2539 * packed-refs if it exists there.2540 */2541if(!packed_transaction) {2542 packed_transaction =ref_store_transaction_begin(2543 refs->packed_ref_store, err);2544if(!packed_transaction) {2545 ret = TRANSACTION_GENERIC_ERROR;2546goto cleanup;2547}25482549 backend_data->packed_transaction =2550 packed_transaction;2551}25522553ref_transaction_add_update(2554 packed_transaction, update->refname,2555 update->flags & ~REF_HAVE_OLD,2556 update->new_oid.hash, update->old_oid.hash,2557 NULL);2558}2559}25602561if(packed_transaction) {2562if(packed_refs_lock(refs->packed_ref_store,0, err)) {2563 ret = TRANSACTION_GENERIC_ERROR;2564goto cleanup;2565}2566 backend_data->packed_refs_locked =1;2567 ret =ref_transaction_prepare(packed_transaction, err);2568}25692570cleanup:2571free(head_ref);2572string_list_clear(&affected_refnames,0);25732574if(ret)2575files_transaction_cleanup(refs, transaction);2576else2577 transaction->state = REF_TRANSACTION_PREPARED;25782579return ret;2580}25812582static intfiles_transaction_finish(struct ref_store *ref_store,2583struct ref_transaction *transaction,2584struct strbuf *err)2585{2586struct files_ref_store *refs =2587files_downcast(ref_store,0,"ref_transaction_finish");2588size_t i;2589int ret =0;2590struct strbuf sb = STRBUF_INIT;2591struct files_transaction_backend_data *backend_data;2592struct ref_transaction *packed_transaction;259325942595assert(err);25962597if(!transaction->nr) {2598 transaction->state = REF_TRANSACTION_CLOSED;2599return0;2600}26012602 backend_data = transaction->backend_data;2603 packed_transaction = backend_data->packed_transaction;26042605/* Perform updates first so live commits remain referenced */2606for(i =0; i < transaction->nr; i++) {2607struct ref_update *update = transaction->updates[i];2608struct ref_lock *lock = update->backend_data;26092610if(update->flags & REF_NEEDS_COMMIT ||2611 update->flags & REF_LOG_ONLY) {2612if(files_log_ref_write(refs,2613 lock->ref_name,2614&lock->old_oid,2615&update->new_oid,2616 update->msg, update->flags,2617 err)) {2618char*old_msg =strbuf_detach(err, NULL);26192620strbuf_addf(err,"cannot update the ref '%s':%s",2621 lock->ref_name, old_msg);2622free(old_msg);2623unlock_ref(lock);2624 update->backend_data = NULL;2625 ret = TRANSACTION_GENERIC_ERROR;2626goto cleanup;2627}2628}2629if(update->flags & REF_NEEDS_COMMIT) {2630clear_loose_ref_cache(refs);2631if(commit_ref(lock)) {2632strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2633unlock_ref(lock);2634 update->backend_data = NULL;2635 ret = TRANSACTION_GENERIC_ERROR;2636goto cleanup;2637}2638}2639}26402641/*2642 * Now that updates are safely completed, we can perform2643 * deletes. First delete the reflogs of any references that2644 * will be deleted, since (in the unexpected event of an2645 * error) leaving a reference without a reflog is less bad2646 * than leaving a reflog without a reference (the latter is a2647 * mildly invalid repository state):2648 */2649for(i =0; i < transaction->nr; i++) {2650struct ref_update *update = transaction->updates[i];2651if(update->flags & REF_DELETING &&2652!(update->flags & REF_LOG_ONLY) &&2653!(update->flags & REF_ISPRUNING)) {2654strbuf_reset(&sb);2655files_reflog_path(refs, &sb, update->refname);2656if(!unlink_or_warn(sb.buf))2657try_remove_empty_parents(refs, update->refname,2658 REMOVE_EMPTY_PARENTS_REFLOG);2659}2660}26612662/*2663 * Perform deletes now that updates are safely completed.2664 *2665 * First delete any packed versions of the references, while2666 * retaining the packed-refs lock:2667 */2668if(packed_transaction) {2669 ret =ref_transaction_commit(packed_transaction, err);2670ref_transaction_free(packed_transaction);2671 packed_transaction = NULL;2672 backend_data->packed_transaction = NULL;2673if(ret)2674goto cleanup;2675}26762677/* Now delete the loose versions of the references: */2678for(i =0; i < transaction->nr; i++) {2679struct ref_update *update = transaction->updates[i];2680struct ref_lock *lock = update->backend_data;26812682if(update->flags & REF_DELETING &&2683!(update->flags & REF_LOG_ONLY)) {2684if(!(update->type & REF_ISPACKED) ||2685 update->type & REF_ISSYMREF) {2686/* It is a loose reference. */2687strbuf_reset(&sb);2688files_ref_path(refs, &sb, lock->ref_name);2689if(unlink_or_msg(sb.buf, err)) {2690 ret = TRANSACTION_GENERIC_ERROR;2691goto cleanup;2692}2693 update->flags |= REF_DELETED_LOOSE;2694}2695}2696}26972698clear_loose_ref_cache(refs);26992700cleanup:2701files_transaction_cleanup(refs, transaction);27022703for(i =0; i < transaction->nr; i++) {2704struct ref_update *update = transaction->updates[i];27052706if(update->flags & REF_DELETED_LOOSE) {2707/*2708 * The loose reference was deleted. Delete any2709 * empty parent directories. (Note that this2710 * can only work because we have already2711 * removed the lockfile.)2712 */2713try_remove_empty_parents(refs, update->refname,2714 REMOVE_EMPTY_PARENTS_REF);2715}2716}27172718strbuf_release(&sb);2719return ret;2720}27212722static intfiles_transaction_abort(struct ref_store *ref_store,2723struct ref_transaction *transaction,2724struct strbuf *err)2725{2726struct files_ref_store *refs =2727files_downcast(ref_store,0,"ref_transaction_abort");27282729files_transaction_cleanup(refs, transaction);2730return0;2731}27322733static intref_present(const char*refname,2734const struct object_id *oid,int flags,void*cb_data)2735{2736struct string_list *affected_refnames = cb_data;27372738returnstring_list_has_string(affected_refnames, refname);2739}27402741static intfiles_initial_transaction_commit(struct ref_store *ref_store,2742struct ref_transaction *transaction,2743struct strbuf *err)2744{2745struct files_ref_store *refs =2746files_downcast(ref_store, REF_STORE_WRITE,2747"initial_ref_transaction_commit");2748size_t i;2749int ret =0;2750struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2751struct ref_transaction *packed_transaction = NULL;27522753assert(err);27542755if(transaction->state != REF_TRANSACTION_OPEN)2756die("BUG: commit called for transaction that is not open");27572758/* Fail if a refname appears more than once in the transaction: */2759for(i =0; i < transaction->nr; i++)2760string_list_append(&affected_refnames,2761 transaction->updates[i]->refname);2762string_list_sort(&affected_refnames);2763if(ref_update_reject_duplicates(&affected_refnames, err)) {2764 ret = TRANSACTION_GENERIC_ERROR;2765goto cleanup;2766}27672768/*2769 * It's really undefined to call this function in an active2770 * repository or when there are existing references: we are2771 * only locking and changing packed-refs, so (1) any2772 * simultaneous processes might try to change a reference at2773 * the same time we do, and (2) any existing loose versions of2774 * the references that we are setting would have precedence2775 * over our values. But some remote helpers create the remote2776 * "HEAD" and "master" branches before calling this function,2777 * so here we really only check that none of the references2778 * that we are creating already exists.2779 */2780if(refs_for_each_rawref(&refs->base, ref_present,2781&affected_refnames))2782die("BUG: initial ref transaction called with existing refs");27832784 packed_transaction =ref_store_transaction_begin(refs->packed_ref_store, err);2785if(!packed_transaction) {2786 ret = TRANSACTION_GENERIC_ERROR;2787goto cleanup;2788}27892790for(i =0; i < transaction->nr; i++) {2791struct ref_update *update = transaction->updates[i];27922793if((update->flags & REF_HAVE_OLD) &&2794!is_null_oid(&update->old_oid))2795die("BUG: initial ref transaction with old_sha1 set");2796if(refs_verify_refname_available(&refs->base, update->refname,2797&affected_refnames, NULL,2798 err)) {2799 ret = TRANSACTION_NAME_CONFLICT;2800goto cleanup;2801}28022803/*2804 * Add a reference creation for this reference to the2805 * packed-refs transaction:2806 */2807ref_transaction_add_update(packed_transaction, update->refname,2808 update->flags & ~REF_HAVE_OLD,2809 update->new_oid.hash, update->old_oid.hash,2810 NULL);2811}28122813if(packed_refs_lock(refs->packed_ref_store,0, err)) {2814 ret = TRANSACTION_GENERIC_ERROR;2815goto cleanup;2816}28172818if(initial_ref_transaction_commit(packed_transaction, err)) {2819 ret = TRANSACTION_GENERIC_ERROR;2820goto cleanup;2821}28222823cleanup:2824if(packed_transaction)2825ref_transaction_free(packed_transaction);2826packed_refs_unlock(refs->packed_ref_store);2827 transaction->state = REF_TRANSACTION_CLOSED;2828string_list_clear(&affected_refnames,0);2829return ret;2830}28312832struct expire_reflog_cb {2833unsigned int flags;2834 reflog_expiry_should_prune_fn *should_prune_fn;2835void*policy_cb;2836FILE*newlog;2837struct object_id last_kept_oid;2838};28392840static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2841const char*email, timestamp_t timestamp,int tz,2842const char*message,void*cb_data)2843{2844struct expire_reflog_cb *cb = cb_data;2845struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;28462847if(cb->flags & EXPIRE_REFLOGS_REWRITE)2848 ooid = &cb->last_kept_oid;28492850if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2851 message, policy_cb)) {2852if(!cb->newlog)2853printf("would prune%s", message);2854else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2855printf("prune%s", message);2856}else{2857if(cb->newlog) {2858fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2859oid_to_hex(ooid),oid_to_hex(noid),2860 email, timestamp, tz, message);2861oidcpy(&cb->last_kept_oid, noid);2862}2863if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2864printf("keep%s", message);2865}2866return0;2867}28682869static intfiles_reflog_expire(struct ref_store *ref_store,2870const char*refname,const unsigned char*sha1,2871unsigned int flags,2872 reflog_expiry_prepare_fn prepare_fn,2873 reflog_expiry_should_prune_fn should_prune_fn,2874 reflog_expiry_cleanup_fn cleanup_fn,2875void*policy_cb_data)2876{2877struct files_ref_store *refs =2878files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2879static struct lock_file reflog_lock;2880struct expire_reflog_cb cb;2881struct ref_lock *lock;2882struct strbuf log_file_sb = STRBUF_INIT;2883char*log_file;2884int status =0;2885int type;2886struct strbuf err = STRBUF_INIT;2887struct object_id oid;28882889memset(&cb,0,sizeof(cb));2890 cb.flags = flags;2891 cb.policy_cb = policy_cb_data;2892 cb.should_prune_fn = should_prune_fn;28932894/*2895 * The reflog file is locked by holding the lock on the2896 * reference itself, plus we might need to update the2897 * reference if --updateref was specified:2898 */2899 lock =lock_ref_sha1_basic(refs, refname, sha1,2900 NULL, NULL, REF_NODEREF,2901&type, &err);2902if(!lock) {2903error("cannot lock ref '%s':%s", refname, err.buf);2904strbuf_release(&err);2905return-1;2906}2907if(!refs_reflog_exists(ref_store, refname)) {2908unlock_ref(lock);2909return0;2910}29112912files_reflog_path(refs, &log_file_sb, refname);2913 log_file =strbuf_detach(&log_file_sb, NULL);2914if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2915/*2916 * Even though holding $GIT_DIR/logs/$reflog.lock has2917 * no locking implications, we use the lock_file2918 * machinery here anyway because it does a lot of the2919 * work we need, including cleaning up if the program2920 * exits unexpectedly.2921 */2922if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2923struct strbuf err = STRBUF_INIT;2924unable_to_lock_message(log_file, errno, &err);2925error("%s", err.buf);2926strbuf_release(&err);2927goto failure;2928}2929 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2930if(!cb.newlog) {2931error("cannot fdopen%s(%s)",2932get_lock_file_path(&reflog_lock),strerror(errno));2933goto failure;2934}2935}29362937hashcpy(oid.hash, sha1);29382939(*prepare_fn)(refname, &oid, cb.policy_cb);2940refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2941(*cleanup_fn)(cb.policy_cb);29422943if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2944/*2945 * It doesn't make sense to adjust a reference pointed2946 * to by a symbolic ref based on expiring entries in2947 * the symbolic reference's reflog. Nor can we update2948 * a reference if there are no remaining reflog2949 * entries.2950 */2951int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2952!(type & REF_ISSYMREF) &&2953!is_null_oid(&cb.last_kept_oid);29542955if(close_lock_file(&reflog_lock)) {2956 status |=error("couldn't write%s:%s", log_file,2957strerror(errno));2958}else if(update &&2959(write_in_full(get_lock_file_fd(lock->lk),2960oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2961write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2962close_ref(lock) <0)) {2963 status |=error("couldn't write%s",2964get_lock_file_path(lock->lk));2965rollback_lock_file(&reflog_lock);2966}else if(commit_lock_file(&reflog_lock)) {2967 status |=error("unable to write reflog '%s' (%s)",2968 log_file,strerror(errno));2969}else if(update &&commit_ref(lock)) {2970 status |=error("couldn't set%s", lock->ref_name);2971}2972}2973free(log_file);2974unlock_ref(lock);2975return status;29762977 failure:2978rollback_lock_file(&reflog_lock);2979free(log_file);2980unlock_ref(lock);2981return-1;2982}29832984static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2985{2986struct files_ref_store *refs =2987files_downcast(ref_store, REF_STORE_WRITE,"init_db");2988struct strbuf sb = STRBUF_INIT;29892990/*2991 * Create .git/refs/{heads,tags}2992 */2993files_ref_path(refs, &sb,"refs/heads");2994safe_create_dir(sb.buf,1);29952996strbuf_reset(&sb);2997files_ref_path(refs, &sb,"refs/tags");2998safe_create_dir(sb.buf,1);29993000strbuf_release(&sb);3001return0;3002}30033004struct ref_storage_be refs_be_files = {3005 NULL,3006"files",3007 files_ref_store_create,3008 files_init_db,3009 files_transaction_prepare,3010 files_transaction_finish,3011 files_transaction_abort,3012 files_initial_transaction_commit,30133014 files_pack_refs,3015 files_peel_ref,3016 files_create_symref,3017 files_delete_refs,3018 files_rename_ref,30193020 files_ref_iterator_begin,3021 files_read_raw_ref,30223023 files_reflog_iterator_begin,3024 files_for_each_reflog_ent,3025 files_for_each_reflog_ent_reverse,3026 files_reflog_exists,3027 files_create_reflog,3028 files_delete_reflog,3029 files_reflog_expire3030};