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; 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 iter =xcalloc(1,sizeof(*iter)); 776 ref_iterator = &iter->base; 777base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 778 779/* 780 * We must make sure that all loose refs are read before 781 * accessing the packed-refs file; this avoids a race 782 * condition if loose refs are migrated to the packed-refs 783 * file by a simultaneous process, but our in-memory view is 784 * from before the migration. We ensure this as follows: 785 * First, we call start the loose refs iteration with its 786 * `prime_ref` argument set to true. This causes the loose 787 * references in the subtree to be pre-read into the cache. 788 * (If they've already been read, that's OK; we only need to 789 * guarantee that they're read before the packed refs, not 790 * *how much* before.) After that, we call 791 * packed_ref_iterator_begin(), which internally checks 792 * whether the packed-ref cache is up to date with what is on 793 * disk, and re-reads it if not. 794 */ 795 796 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 797 prefix,1); 798 799/* 800 * The packed-refs file might contain broken references, for 801 * example an old version of a reference that points at an 802 * object that has since been garbage-collected. This is OK as 803 * long as there is a corresponding loose reference that 804 * overrides it, and we don't want to emit an error message in 805 * this case. So ask the packed_ref_store for all of its 806 * references, and (if needed) do our own check for broken 807 * ones in files_ref_iterator_advance(), after we have merged 808 * the packed and loose references. 809 */ 810 packed_iter =refs_ref_iterator_begin( 811 refs->packed_ref_store, prefix,0, 812 DO_FOR_EACH_INCLUDE_BROKEN); 813 814 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 815 iter->flags = flags; 816 817return ref_iterator; 818} 819 820/* 821 * Verify that the reference locked by lock has the value old_sha1. 822 * Fail if the reference doesn't exist and mustexist is set. Return 0 823 * on success. On error, write an error message to err, set errno, and 824 * return a negative value. 825 */ 826static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 827const unsigned char*old_sha1,int mustexist, 828struct strbuf *err) 829{ 830assert(err); 831 832if(refs_read_ref_full(ref_store, lock->ref_name, 833 mustexist ? RESOLVE_REF_READING :0, 834 lock->old_oid.hash, NULL)) { 835if(old_sha1) { 836int save_errno = errno; 837strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 838 errno = save_errno; 839return-1; 840}else{ 841oidclr(&lock->old_oid); 842return0; 843} 844} 845if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 846strbuf_addf(err,"ref '%s' is at%sbut expected%s", 847 lock->ref_name, 848oid_to_hex(&lock->old_oid), 849sha1_to_hex(old_sha1)); 850 errno = EBUSY; 851return-1; 852} 853return0; 854} 855 856static intremove_empty_directories(struct strbuf *path) 857{ 858/* 859 * we want to create a file but there is a directory there; 860 * if that is an empty directory (or a directory that contains 861 * only empty directories), remove them. 862 */ 863returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 864} 865 866static intcreate_reflock(const char*path,void*cb) 867{ 868struct lock_file *lk = cb; 869 870returnhold_lock_file_for_update_timeout( 871 lk, path, LOCK_NO_DEREF, 872get_files_ref_lock_timeout_ms()) <0? -1:0; 873} 874 875/* 876 * Locks a ref returning the lock on success and NULL on failure. 877 * On failure errno is set to something meaningful. 878 */ 879static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 880const char*refname, 881const unsigned char*old_sha1, 882const struct string_list *extras, 883const struct string_list *skip, 884unsigned int flags,int*type, 885struct strbuf *err) 886{ 887struct strbuf ref_file = STRBUF_INIT; 888struct ref_lock *lock; 889int last_errno =0; 890int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 891int resolve_flags = RESOLVE_REF_NO_RECURSE; 892int resolved; 893 894files_assert_main_repository(refs,"lock_ref_sha1_basic"); 895assert(err); 896 897 lock =xcalloc(1,sizeof(struct ref_lock)); 898 899if(mustexist) 900 resolve_flags |= RESOLVE_REF_READING; 901if(flags & REF_DELETING) 902 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 903 904files_ref_path(refs, &ref_file, refname); 905 resolved = !!refs_resolve_ref_unsafe(&refs->base, 906 refname, resolve_flags, 907 lock->old_oid.hash, type); 908if(!resolved && errno == EISDIR) { 909/* 910 * we are trying to lock foo but we used to 911 * have foo/bar which now does not exist; 912 * it is normal for the empty directory 'foo' 913 * to remain. 914 */ 915if(remove_empty_directories(&ref_file)) { 916 last_errno = errno; 917if(!refs_verify_refname_available( 918&refs->base, 919 refname, extras, skip, err)) 920strbuf_addf(err,"there are still refs under '%s'", 921 refname); 922goto error_return; 923} 924 resolved = !!refs_resolve_ref_unsafe(&refs->base, 925 refname, resolve_flags, 926 lock->old_oid.hash, type); 927} 928if(!resolved) { 929 last_errno = errno; 930if(last_errno != ENOTDIR || 931!refs_verify_refname_available(&refs->base, refname, 932 extras, skip, err)) 933strbuf_addf(err,"unable to resolve reference '%s':%s", 934 refname,strerror(last_errno)); 935 936goto error_return; 937} 938 939/* 940 * If the ref did not exist and we are creating it, make sure 941 * there is no existing packed ref whose name begins with our 942 * refname, nor a packed ref whose name is a proper prefix of 943 * our refname. 944 */ 945if(is_null_oid(&lock->old_oid) && 946refs_verify_refname_available(refs->packed_ref_store, refname, 947 extras, skip, err)) { 948 last_errno = ENOTDIR; 949goto error_return; 950} 951 952 lock->lk =xcalloc(1,sizeof(struct lock_file)); 953 954 lock->ref_name =xstrdup(refname); 955 956if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 957 last_errno = errno; 958unable_to_lock_message(ref_file.buf, errno, err); 959goto error_return; 960} 961 962if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 963 last_errno = errno; 964goto error_return; 965} 966goto out; 967 968 error_return: 969unlock_ref(lock); 970 lock = NULL; 971 972 out: 973strbuf_release(&ref_file); 974 errno = last_errno; 975return lock; 976} 977 978struct ref_to_prune { 979struct ref_to_prune *next; 980unsigned char sha1[20]; 981char name[FLEX_ARRAY]; 982}; 983 984enum{ 985 REMOVE_EMPTY_PARENTS_REF =0x01, 986 REMOVE_EMPTY_PARENTS_REFLOG =0x02 987}; 988 989/* 990 * Remove empty parent directories associated with the specified 991 * reference and/or its reflog, but spare [logs/]refs/ and immediate 992 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 993 * REMOVE_EMPTY_PARENTS_REFLOG. 994 */ 995static voidtry_remove_empty_parents(struct files_ref_store *refs, 996const char*refname, 997unsigned int flags) 998{ 999struct strbuf buf = STRBUF_INIT;1000struct strbuf sb = STRBUF_INIT;1001char*p, *q;1002int i;10031004strbuf_addstr(&buf, refname);1005 p = buf.buf;1006for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1007while(*p && *p !='/')1008 p++;1009/* tolerate duplicate slashes; see check_refname_format() */1010while(*p =='/')1011 p++;1012}1013 q = buf.buf + buf.len;1014while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1015while(q > p && *q !='/')1016 q--;1017while(q > p && *(q-1) =='/')1018 q--;1019if(q == p)1020break;1021strbuf_setlen(&buf, q - buf.buf);10221023strbuf_reset(&sb);1024files_ref_path(refs, &sb, buf.buf);1025if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1026 flags &= ~REMOVE_EMPTY_PARENTS_REF;10271028strbuf_reset(&sb);1029files_reflog_path(refs, &sb, buf.buf);1030if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1031 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1032}1033strbuf_release(&buf);1034strbuf_release(&sb);1035}10361037/* make sure nobody touched the ref, and unlink */1038static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1039{1040struct ref_transaction *transaction;1041struct strbuf err = STRBUF_INIT;10421043if(check_refname_format(r->name,0))1044return;10451046 transaction =ref_store_transaction_begin(&refs->base, &err);1047if(!transaction ||1048ref_transaction_delete(transaction, r->name, r->sha1,1049 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1050ref_transaction_commit(transaction, &err)) {1051ref_transaction_free(transaction);1052error("%s", err.buf);1053strbuf_release(&err);1054return;1055}1056ref_transaction_free(transaction);1057strbuf_release(&err);1058}10591060static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1061{1062while(r) {1063prune_ref(refs, r);1064 r = r->next;1065}1066}10671068/*1069 * Return true if the specified reference should be packed.1070 */1071static intshould_pack_ref(const char*refname,1072const struct object_id *oid,unsigned int ref_flags,1073unsigned int pack_flags)1074{1075/* Do not pack per-worktree refs: */1076if(ref_type(refname) != REF_TYPE_NORMAL)1077return0;10781079/* Do not pack non-tags unless PACK_REFS_ALL is set: */1080if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1081return0;10821083/* Do not pack symbolic refs: */1084if(ref_flags & REF_ISSYMREF)1085return0;10861087/* Do not pack broken refs: */1088if(!ref_resolves_to_object(refname, oid, ref_flags))1089return0;10901091return1;1092}10931094static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1095{1096struct files_ref_store *refs =1097files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1098"pack_refs");1099struct ref_iterator *iter;1100int ok;1101struct ref_to_prune *refs_to_prune = NULL;1102struct strbuf err = STRBUF_INIT;11031104packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);11051106 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1107while((ok =ref_iterator_advance(iter)) == ITER_OK) {1108/*1109 * If the loose reference can be packed, add an entry1110 * in the packed ref cache. If the reference should be1111 * pruned, also add it to refs_to_prune.1112 */1113if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1114 flags))1115continue;11161117/*1118 * Create an entry in the packed-refs cache equivalent1119 * to the one from the loose ref cache, except that1120 * we don't copy the peeled status, because we want it1121 * to be re-peeled.1122 */1123add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11241125/* Schedule the loose reference for pruning if requested. */1126if((flags & PACK_REFS_PRUNE)) {1127struct ref_to_prune *n;1128FLEX_ALLOC_STR(n, name, iter->refname);1129hashcpy(n->sha1, iter->oid->hash);1130 n->next = refs_to_prune;1131 refs_to_prune = n;1132}1133}1134if(ok != ITER_DONE)1135die("error while iterating over references");11361137if(commit_packed_refs(refs->packed_ref_store, &err))1138die("unable to overwrite old ref-pack file:%s", err.buf);1139packed_refs_unlock(refs->packed_ref_store);11401141prune_refs(refs, refs_to_prune);1142strbuf_release(&err);1143return0;1144}11451146static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1147struct string_list *refnames,unsigned int flags)1148{1149struct files_ref_store *refs =1150files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1151struct strbuf err = STRBUF_INIT;1152int i, result =0;11531154if(!refnames->nr)1155return0;11561157if(packed_refs_lock(refs->packed_ref_store,0, &err))1158goto error;11591160if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1161packed_refs_unlock(refs->packed_ref_store);1162goto error;1163}11641165packed_refs_unlock(refs->packed_ref_store);11661167for(i =0; i < refnames->nr; i++) {1168const char*refname = refnames->items[i].string;11691170if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1171 result |=error(_("could not remove reference%s"), refname);1172}11731174strbuf_release(&err);1175return result;11761177error:1178/*1179 * If we failed to rewrite the packed-refs file, then it is1180 * unsafe to try to remove loose refs, because doing so might1181 * expose an obsolete packed value for a reference that might1182 * even point at an object that has been garbage collected.1183 */1184if(refnames->nr ==1)1185error(_("could not delete reference%s:%s"),1186 refnames->items[0].string, err.buf);1187else1188error(_("could not delete references:%s"), err.buf);11891190strbuf_release(&err);1191return-1;1192}11931194/*1195 * People using contrib's git-new-workdir have .git/logs/refs ->1196 * /some/other/path/.git/logs/refs, and that may live on another device.1197 *1198 * IOW, to avoid cross device rename errors, the temporary renamed log must1199 * live into logs/refs.1200 */1201#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"12021203struct rename_cb {1204const char*tmp_renamed_log;1205int true_errno;1206};12071208static intrename_tmp_log_callback(const char*path,void*cb_data)1209{1210struct rename_cb *cb = cb_data;12111212if(rename(cb->tmp_renamed_log, path)) {1213/*1214 * rename(a, b) when b is an existing directory ought1215 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1216 * Sheesh. Record the true errno for error reporting,1217 * but report EISDIR to raceproof_create_file() so1218 * that it knows to retry.1219 */1220 cb->true_errno = errno;1221if(errno == ENOTDIR)1222 errno = EISDIR;1223return-1;1224}else{1225return0;1226}1227}12281229static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1230{1231struct strbuf path = STRBUF_INIT;1232struct strbuf tmp = STRBUF_INIT;1233struct rename_cb cb;1234int ret;12351236files_reflog_path(refs, &path, newrefname);1237files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1238 cb.tmp_renamed_log = tmp.buf;1239 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1240if(ret) {1241if(errno == EISDIR)1242error("directory not empty:%s", path.buf);1243else1244error("unable to move logfile%sto%s:%s",1245 tmp.buf, path.buf,1246strerror(cb.true_errno));1247}12481249strbuf_release(&path);1250strbuf_release(&tmp);1251return ret;1252}12531254static intwrite_ref_to_lockfile(struct ref_lock *lock,1255const struct object_id *oid,struct strbuf *err);1256static intcommit_ref_update(struct files_ref_store *refs,1257struct ref_lock *lock,1258const struct object_id *oid,const char*logmsg,1259struct strbuf *err);12601261static intfiles_rename_ref(struct ref_store *ref_store,1262const char*oldrefname,const char*newrefname,1263const char*logmsg)1264{1265struct files_ref_store *refs =1266files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1267struct object_id oid, orig_oid;1268int flag =0, logmoved =0;1269struct ref_lock *lock;1270struct stat loginfo;1271struct strbuf sb_oldref = STRBUF_INIT;1272struct strbuf sb_newref = STRBUF_INIT;1273struct strbuf tmp_renamed_log = STRBUF_INIT;1274int log, ret;1275struct strbuf err = STRBUF_INIT;12761277files_reflog_path(refs, &sb_oldref, oldrefname);1278files_reflog_path(refs, &sb_newref, newrefname);1279files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12801281 log = !lstat(sb_oldref.buf, &loginfo);1282if(log &&S_ISLNK(loginfo.st_mode)) {1283 ret =error("reflog for%sis a symlink", oldrefname);1284goto out;1285}12861287if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1288 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1289 orig_oid.hash, &flag)) {1290 ret =error("refname%snot found", oldrefname);1291goto out;1292}12931294if(flag & REF_ISSYMREF) {1295 ret =error("refname%sis a symbolic ref, renaming it is not supported",1296 oldrefname);1297goto out;1298}1299if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1300 ret =1;1301goto out;1302}13031304if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1305 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1306 oldrefname,strerror(errno));1307goto out;1308}13091310if(refs_delete_ref(&refs->base, logmsg, oldrefname,1311 orig_oid.hash, REF_NODEREF)) {1312error("unable to delete old%s", oldrefname);1313goto rollback;1314}13151316/*1317 * Since we are doing a shallow lookup, oid is not the1318 * correct value to pass to delete_ref as old_oid. But that1319 * doesn't matter, because an old_oid check wouldn't add to1320 * the safety anyway; we want to delete the reference whatever1321 * its current value.1322 */1323if(!refs_read_ref_full(&refs->base, newrefname,1324 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1325 oid.hash, NULL) &&1326refs_delete_ref(&refs->base, NULL, newrefname,1327 NULL, REF_NODEREF)) {1328if(errno == EISDIR) {1329struct strbuf path = STRBUF_INIT;1330int result;13311332files_ref_path(refs, &path, newrefname);1333 result =remove_empty_directories(&path);1334strbuf_release(&path);13351336if(result) {1337error("Directory not empty:%s", newrefname);1338goto rollback;1339}1340}else{1341error("unable to delete existing%s", newrefname);1342goto rollback;1343}1344}13451346if(log &&rename_tmp_log(refs, newrefname))1347goto rollback;13481349 logmoved = log;13501351 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1352 REF_NODEREF, NULL, &err);1353if(!lock) {1354error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1355strbuf_release(&err);1356goto rollback;1357}1358oidcpy(&lock->old_oid, &orig_oid);13591360if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1361commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1362error("unable to write current sha1 into%s:%s", newrefname, err.buf);1363strbuf_release(&err);1364goto rollback;1365}13661367 ret =0;1368goto out;13691370 rollback:1371 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1372 REF_NODEREF, NULL, &err);1373if(!lock) {1374error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1375strbuf_release(&err);1376goto rollbacklog;1377}13781379 flag = log_all_ref_updates;1380 log_all_ref_updates = LOG_REFS_NONE;1381if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1382commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1383error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1384strbuf_release(&err);1385}1386 log_all_ref_updates = flag;13871388 rollbacklog:1389if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1390error("unable to restore logfile%sfrom%s:%s",1391 oldrefname, newrefname,strerror(errno));1392if(!logmoved && log &&1393rename(tmp_renamed_log.buf, sb_oldref.buf))1394error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1395 oldrefname,strerror(errno));1396 ret =1;1397 out:1398strbuf_release(&sb_newref);1399strbuf_release(&sb_oldref);1400strbuf_release(&tmp_renamed_log);14011402return ret;1403}14041405static intclose_ref(struct ref_lock *lock)1406{1407if(close_lock_file(lock->lk))1408return-1;1409return0;1410}14111412static intcommit_ref(struct ref_lock *lock)1413{1414char*path =get_locked_file_path(lock->lk);1415struct stat st;14161417if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1418/*1419 * There is a directory at the path we want to rename1420 * the lockfile to. Hopefully it is empty; try to1421 * delete it.1422 */1423size_t len =strlen(path);1424struct strbuf sb_path = STRBUF_INIT;14251426strbuf_attach(&sb_path, path, len, len);14271428/*1429 * If this fails, commit_lock_file() will also fail1430 * and will report the problem.1431 */1432remove_empty_directories(&sb_path);1433strbuf_release(&sb_path);1434}else{1435free(path);1436}14371438if(commit_lock_file(lock->lk))1439return-1;1440return0;1441}14421443static intopen_or_create_logfile(const char*path,void*cb)1444{1445int*fd = cb;14461447*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1448return(*fd <0) ? -1:0;1449}14501451/*1452 * Create a reflog for a ref. If force_create = 0, only create the1453 * reflog for certain refs (those for which should_autocreate_reflog1454 * returns non-zero). Otherwise, create it regardless of the reference1455 * name. If the logfile already existed or was created, return 0 and1456 * set *logfd to the file descriptor opened for appending to the file.1457 * If no logfile exists and we decided not to create one, return 0 and1458 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1459 * return -1.1460 */1461static intlog_ref_setup(struct files_ref_store *refs,1462const char*refname,int force_create,1463int*logfd,struct strbuf *err)1464{1465struct strbuf logfile_sb = STRBUF_INIT;1466char*logfile;14671468files_reflog_path(refs, &logfile_sb, refname);1469 logfile =strbuf_detach(&logfile_sb, NULL);14701471if(force_create ||should_autocreate_reflog(refname)) {1472if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1473if(errno == ENOENT)1474strbuf_addf(err,"unable to create directory for '%s': "1475"%s", logfile,strerror(errno));1476else if(errno == EISDIR)1477strbuf_addf(err,"there are still logs under '%s'",1478 logfile);1479else1480strbuf_addf(err,"unable to append to '%s':%s",1481 logfile,strerror(errno));14821483goto error;1484}1485}else{1486*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1487if(*logfd <0) {1488if(errno == ENOENT || errno == EISDIR) {1489/*1490 * The logfile doesn't already exist,1491 * but that is not an error; it only1492 * means that we won't write log1493 * entries to it.1494 */1495;1496}else{1497strbuf_addf(err,"unable to append to '%s':%s",1498 logfile,strerror(errno));1499goto error;1500}1501}1502}15031504if(*logfd >=0)1505adjust_shared_perm(logfile);15061507free(logfile);1508return0;15091510error:1511free(logfile);1512return-1;1513}15141515static intfiles_create_reflog(struct ref_store *ref_store,1516const char*refname,int force_create,1517struct strbuf *err)1518{1519struct files_ref_store *refs =1520files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1521int fd;15221523if(log_ref_setup(refs, refname, force_create, &fd, err))1524return-1;15251526if(fd >=0)1527close(fd);15281529return0;1530}15311532static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1533const struct object_id *new_oid,1534const char*committer,const char*msg)1535{1536int msglen, written;1537unsigned maxlen, len;1538char*logrec;15391540 msglen = msg ?strlen(msg) :0;1541 maxlen =strlen(committer) + msglen +100;1542 logrec =xmalloc(maxlen);1543 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1544oid_to_hex(old_oid),1545oid_to_hex(new_oid),1546 committer);1547if(msglen)1548 len +=copy_reflog_msg(logrec + len -1, msg) -1;15491550 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1551free(logrec);1552if(written != len)1553return-1;15541555return0;1556}15571558static intfiles_log_ref_write(struct files_ref_store *refs,1559const char*refname,const struct object_id *old_oid,1560const struct object_id *new_oid,const char*msg,1561int flags,struct strbuf *err)1562{1563int logfd, result;15641565if(log_all_ref_updates == LOG_REFS_UNSET)1566 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15671568 result =log_ref_setup(refs, refname,1569 flags & REF_FORCE_CREATE_REFLOG,1570&logfd, err);15711572if(result)1573return result;15741575if(logfd <0)1576return0;1577 result =log_ref_write_fd(logfd, old_oid, new_oid,1578git_committer_info(0), msg);1579if(result) {1580struct strbuf sb = STRBUF_INIT;1581int save_errno = errno;15821583files_reflog_path(refs, &sb, refname);1584strbuf_addf(err,"unable to append to '%s':%s",1585 sb.buf,strerror(save_errno));1586strbuf_release(&sb);1587close(logfd);1588return-1;1589}1590if(close(logfd)) {1591struct strbuf sb = STRBUF_INIT;1592int save_errno = errno;15931594files_reflog_path(refs, &sb, refname);1595strbuf_addf(err,"unable to append to '%s':%s",1596 sb.buf,strerror(save_errno));1597strbuf_release(&sb);1598return-1;1599}1600return0;1601}16021603/*1604 * Write sha1 into the open lockfile, then close the lockfile. On1605 * errors, rollback the lockfile, fill in *err and1606 * return -1.1607 */1608static intwrite_ref_to_lockfile(struct ref_lock *lock,1609const struct object_id *oid,struct strbuf *err)1610{1611static char term ='\n';1612struct object *o;1613int fd;16141615 o =parse_object(oid);1616if(!o) {1617strbuf_addf(err,1618"trying to write ref '%s' with nonexistent object%s",1619 lock->ref_name,oid_to_hex(oid));1620unlock_ref(lock);1621return-1;1622}1623if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1624strbuf_addf(err,1625"trying to write non-commit object%sto branch '%s'",1626oid_to_hex(oid), lock->ref_name);1627unlock_ref(lock);1628return-1;1629}1630 fd =get_lock_file_fd(lock->lk);1631if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1632write_in_full(fd, &term,1) !=1||1633close_ref(lock) <0) {1634strbuf_addf(err,1635"couldn't write '%s'",get_lock_file_path(lock->lk));1636unlock_ref(lock);1637return-1;1638}1639return0;1640}16411642/*1643 * Commit a change to a loose reference that has already been written1644 * to the loose reference lockfile. Also update the reflogs if1645 * necessary, using the specified lockmsg (which can be NULL).1646 */1647static intcommit_ref_update(struct files_ref_store *refs,1648struct ref_lock *lock,1649const struct object_id *oid,const char*logmsg,1650struct strbuf *err)1651{1652files_assert_main_repository(refs,"commit_ref_update");16531654clear_loose_ref_cache(refs);1655if(files_log_ref_write(refs, lock->ref_name,1656&lock->old_oid, oid,1657 logmsg,0, err)) {1658char*old_msg =strbuf_detach(err, NULL);1659strbuf_addf(err,"cannot update the ref '%s':%s",1660 lock->ref_name, old_msg);1661free(old_msg);1662unlock_ref(lock);1663return-1;1664}16651666if(strcmp(lock->ref_name,"HEAD") !=0) {1667/*1668 * Special hack: If a branch is updated directly and HEAD1669 * points to it (may happen on the remote side of a push1670 * for example) then logically the HEAD reflog should be1671 * updated too.1672 * A generic solution implies reverse symref information,1673 * but finding all symrefs pointing to the given branch1674 * would be rather costly for this rare event (the direct1675 * update of a branch) to be worth it. So let's cheat and1676 * check with HEAD only which should cover 99% of all usage1677 * scenarios (even 100% of the default ones).1678 */1679struct object_id head_oid;1680int head_flag;1681const char*head_ref;16821683 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1684 RESOLVE_REF_READING,1685 head_oid.hash, &head_flag);1686if(head_ref && (head_flag & REF_ISSYMREF) &&1687!strcmp(head_ref, lock->ref_name)) {1688struct strbuf log_err = STRBUF_INIT;1689if(files_log_ref_write(refs,"HEAD",1690&lock->old_oid, oid,1691 logmsg,0, &log_err)) {1692error("%s", log_err.buf);1693strbuf_release(&log_err);1694}1695}1696}16971698if(commit_ref(lock)) {1699strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1700unlock_ref(lock);1701return-1;1702}17031704unlock_ref(lock);1705return0;1706}17071708static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1709{1710int ret = -1;1711#ifndef NO_SYMLINK_HEAD1712char*ref_path =get_locked_file_path(lock->lk);1713unlink(ref_path);1714 ret =symlink(target, ref_path);1715free(ref_path);17161717if(ret)1718fprintf(stderr,"no symlink - falling back to symbolic ref\n");1719#endif1720return ret;1721}17221723static voidupdate_symref_reflog(struct files_ref_store *refs,1724struct ref_lock *lock,const char*refname,1725const char*target,const char*logmsg)1726{1727struct strbuf err = STRBUF_INIT;1728struct object_id new_oid;1729if(logmsg &&1730!refs_read_ref_full(&refs->base, target,1731 RESOLVE_REF_READING, new_oid.hash, NULL) &&1732files_log_ref_write(refs, refname, &lock->old_oid,1733&new_oid, logmsg,0, &err)) {1734error("%s", err.buf);1735strbuf_release(&err);1736}1737}17381739static intcreate_symref_locked(struct files_ref_store *refs,1740struct ref_lock *lock,const char*refname,1741const char*target,const char*logmsg)1742{1743if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1744update_symref_reflog(refs, lock, refname, target, logmsg);1745return0;1746}17471748if(!fdopen_lock_file(lock->lk,"w"))1749returnerror("unable to fdopen%s:%s",1750 lock->lk->tempfile.filename.buf,strerror(errno));17511752update_symref_reflog(refs, lock, refname, target, logmsg);17531754/* no error check; commit_ref will check ferror */1755fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1756if(commit_ref(lock) <0)1757returnerror("unable to write symref for%s:%s", refname,1758strerror(errno));1759return0;1760}17611762static intfiles_create_symref(struct ref_store *ref_store,1763const char*refname,const char*target,1764const char*logmsg)1765{1766struct files_ref_store *refs =1767files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1768struct strbuf err = STRBUF_INIT;1769struct ref_lock *lock;1770int ret;17711772 lock =lock_ref_sha1_basic(refs, refname, NULL,1773 NULL, NULL, REF_NODEREF, NULL,1774&err);1775if(!lock) {1776error("%s", err.buf);1777strbuf_release(&err);1778return-1;1779}17801781 ret =create_symref_locked(refs, lock, refname, target, logmsg);1782unlock_ref(lock);1783return ret;1784}17851786static intfiles_reflog_exists(struct ref_store *ref_store,1787const char*refname)1788{1789struct files_ref_store *refs =1790files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1791struct strbuf sb = STRBUF_INIT;1792struct stat st;1793int ret;17941795files_reflog_path(refs, &sb, refname);1796 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1797strbuf_release(&sb);1798return ret;1799}18001801static intfiles_delete_reflog(struct ref_store *ref_store,1802const char*refname)1803{1804struct files_ref_store *refs =1805files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1806struct strbuf sb = STRBUF_INIT;1807int ret;18081809files_reflog_path(refs, &sb, refname);1810 ret =remove_path(sb.buf);1811strbuf_release(&sb);1812return ret;1813}18141815static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1816{1817struct object_id ooid, noid;1818char*email_end, *message;1819 timestamp_t timestamp;1820int tz;1821const char*p = sb->buf;18221823/* old SP new SP name <email> SP time TAB msg LF */1824if(!sb->len || sb->buf[sb->len -1] !='\n'||1825parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1826parse_oid_hex(p, &noid, &p) || *p++ !=' '||1827!(email_end =strchr(p,'>')) ||1828 email_end[1] !=' '||1829!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1830!message || message[0] !=' '||1831(message[1] !='+'&& message[1] !='-') ||1832!isdigit(message[2]) || !isdigit(message[3]) ||1833!isdigit(message[4]) || !isdigit(message[5]))1834return0;/* corrupt? */1835 email_end[1] ='\0';1836 tz =strtol(message +1, NULL,10);1837if(message[6] !='\t')1838 message +=6;1839else1840 message +=7;1841returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1842}18431844static char*find_beginning_of_line(char*bob,char*scan)1845{1846while(bob < scan && *(--scan) !='\n')1847;/* keep scanning backwards */1848/*1849 * Return either beginning of the buffer, or LF at the end of1850 * the previous line.1851 */1852return scan;1853}18541855static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1856const char*refname,1857 each_reflog_ent_fn fn,1858void*cb_data)1859{1860struct files_ref_store *refs =1861files_downcast(ref_store, REF_STORE_READ,1862"for_each_reflog_ent_reverse");1863struct strbuf sb = STRBUF_INIT;1864FILE*logfp;1865long pos;1866int ret =0, at_tail =1;18671868files_reflog_path(refs, &sb, refname);1869 logfp =fopen(sb.buf,"r");1870strbuf_release(&sb);1871if(!logfp)1872return-1;18731874/* Jump to the end */1875if(fseek(logfp,0, SEEK_END) <0)1876 ret =error("cannot seek back reflog for%s:%s",1877 refname,strerror(errno));1878 pos =ftell(logfp);1879while(!ret &&0< pos) {1880int cnt;1881size_t nread;1882char buf[BUFSIZ];1883char*endp, *scanp;18841885/* Fill next block from the end */1886 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1887if(fseek(logfp, pos - cnt, SEEK_SET)) {1888 ret =error("cannot seek back reflog for%s:%s",1889 refname,strerror(errno));1890break;1891}1892 nread =fread(buf, cnt,1, logfp);1893if(nread !=1) {1894 ret =error("cannot read%dbytes from reflog for%s:%s",1895 cnt, refname,strerror(errno));1896break;1897}1898 pos -= cnt;18991900 scanp = endp = buf + cnt;1901if(at_tail && scanp[-1] =='\n')1902/* Looking at the final LF at the end of the file */1903 scanp--;1904 at_tail =0;19051906while(buf < scanp) {1907/*1908 * terminating LF of the previous line, or the beginning1909 * of the buffer.1910 */1911char*bp;19121913 bp =find_beginning_of_line(buf, scanp);19141915if(*bp =='\n') {1916/*1917 * The newline is the end of the previous line,1918 * so we know we have complete line starting1919 * at (bp + 1). Prefix it onto any prior data1920 * we collected for the line and process it.1921 */1922strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1923 scanp = bp;1924 endp = bp +1;1925 ret =show_one_reflog_ent(&sb, fn, cb_data);1926strbuf_reset(&sb);1927if(ret)1928break;1929}else if(!pos) {1930/*1931 * We are at the start of the buffer, and the1932 * start of the file; there is no previous1933 * line, and we have everything for this one.1934 * Process it, and we can end the loop.1935 */1936strbuf_splice(&sb,0,0, buf, endp - buf);1937 ret =show_one_reflog_ent(&sb, fn, cb_data);1938strbuf_reset(&sb);1939break;1940}19411942if(bp == buf) {1943/*1944 * We are at the start of the buffer, and there1945 * is more file to read backwards. Which means1946 * we are in the middle of a line. Note that we1947 * may get here even if *bp was a newline; that1948 * just means we are at the exact end of the1949 * previous line, rather than some spot in the1950 * middle.1951 *1952 * Save away what we have to be combined with1953 * the data from the next read.1954 */1955strbuf_splice(&sb,0,0, buf, endp - buf);1956break;1957}1958}19591960}1961if(!ret && sb.len)1962die("BUG: reverse reflog parser had leftover data");19631964fclose(logfp);1965strbuf_release(&sb);1966return ret;1967}19681969static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1970const char*refname,1971 each_reflog_ent_fn fn,void*cb_data)1972{1973struct files_ref_store *refs =1974files_downcast(ref_store, REF_STORE_READ,1975"for_each_reflog_ent");1976FILE*logfp;1977struct strbuf sb = STRBUF_INIT;1978int ret =0;19791980files_reflog_path(refs, &sb, refname);1981 logfp =fopen(sb.buf,"r");1982strbuf_release(&sb);1983if(!logfp)1984return-1;19851986while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1987 ret =show_one_reflog_ent(&sb, fn, cb_data);1988fclose(logfp);1989strbuf_release(&sb);1990return ret;1991}19921993struct files_reflog_iterator {1994struct ref_iterator base;19951996struct ref_store *ref_store;1997struct dir_iterator *dir_iterator;1998struct object_id oid;1999};20002001static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2002{2003struct files_reflog_iterator *iter =2004(struct files_reflog_iterator *)ref_iterator;2005struct dir_iterator *diter = iter->dir_iterator;2006int ok;20072008while((ok =dir_iterator_advance(diter)) == ITER_OK) {2009int flags;20102011if(!S_ISREG(diter->st.st_mode))2012continue;2013if(diter->basename[0] =='.')2014continue;2015if(ends_with(diter->basename,".lock"))2016continue;20172018if(refs_read_ref_full(iter->ref_store,2019 diter->relative_path,0,2020 iter->oid.hash, &flags)) {2021error("bad ref for%s", diter->path.buf);2022continue;2023}20242025 iter->base.refname = diter->relative_path;2026 iter->base.oid = &iter->oid;2027 iter->base.flags = flags;2028return ITER_OK;2029}20302031 iter->dir_iterator = NULL;2032if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2033 ok = ITER_ERROR;2034return ok;2035}20362037static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2038struct object_id *peeled)2039{2040die("BUG: ref_iterator_peel() called for reflog_iterator");2041}20422043static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2044{2045struct files_reflog_iterator *iter =2046(struct files_reflog_iterator *)ref_iterator;2047int ok = ITER_DONE;20482049if(iter->dir_iterator)2050 ok =dir_iterator_abort(iter->dir_iterator);20512052base_ref_iterator_free(ref_iterator);2053return ok;2054}20552056static struct ref_iterator_vtable files_reflog_iterator_vtable = {2057 files_reflog_iterator_advance,2058 files_reflog_iterator_peel,2059 files_reflog_iterator_abort2060};20612062static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2063{2064struct files_ref_store *refs =2065files_downcast(ref_store, REF_STORE_READ,2066"reflog_iterator_begin");2067struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2068struct ref_iterator *ref_iterator = &iter->base;2069struct strbuf sb = STRBUF_INIT;20702071base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2072files_reflog_path(refs, &sb, NULL);2073 iter->dir_iterator =dir_iterator_begin(sb.buf);2074 iter->ref_store = ref_store;2075strbuf_release(&sb);2076return ref_iterator;2077}20782079/*2080 * If update is a direct update of head_ref (the reference pointed to2081 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2082 */2083static intsplit_head_update(struct ref_update *update,2084struct ref_transaction *transaction,2085const char*head_ref,2086struct string_list *affected_refnames,2087struct strbuf *err)2088{2089struct string_list_item *item;2090struct ref_update *new_update;20912092if((update->flags & REF_LOG_ONLY) ||2093(update->flags & REF_ISPRUNING) ||2094(update->flags & REF_UPDATE_VIA_HEAD))2095return0;20962097if(strcmp(update->refname, head_ref))2098return0;20992100/*2101 * First make sure that HEAD is not already in the2102 * transaction. This insertion is O(N) in the transaction2103 * size, but it happens at most once per transaction.2104 */2105 item =string_list_insert(affected_refnames,"HEAD");2106if(item->util) {2107/* An entry already existed */2108strbuf_addf(err,2109"multiple updates for 'HEAD' (including one "2110"via its referent '%s') are not allowed",2111 update->refname);2112return TRANSACTION_NAME_CONFLICT;2113}21142115 new_update =ref_transaction_add_update(2116 transaction,"HEAD",2117 update->flags | REF_LOG_ONLY | REF_NODEREF,2118 update->new_oid.hash, update->old_oid.hash,2119 update->msg);21202121 item->util = new_update;21222123return0;2124}21252126/*2127 * update is for a symref that points at referent and doesn't have2128 * REF_NODEREF set. Split it into two updates:2129 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2130 * - A new, separate update for the referent reference2131 * Note that the new update will itself be subject to splitting when2132 * the iteration gets to it.2133 */2134static intsplit_symref_update(struct files_ref_store *refs,2135struct ref_update *update,2136const char*referent,2137struct ref_transaction *transaction,2138struct string_list *affected_refnames,2139struct strbuf *err)2140{2141struct string_list_item *item;2142struct ref_update *new_update;2143unsigned int new_flags;21442145/*2146 * First make sure that referent is not already in the2147 * transaction. This insertion is O(N) in the transaction2148 * size, but it happens at most once per symref in a2149 * transaction.2150 */2151 item =string_list_insert(affected_refnames, referent);2152if(item->util) {2153/* An entry already existed */2154strbuf_addf(err,2155"multiple updates for '%s' (including one "2156"via symref '%s') are not allowed",2157 referent, update->refname);2158return TRANSACTION_NAME_CONFLICT;2159}21602161 new_flags = update->flags;2162if(!strcmp(update->refname,"HEAD")) {2163/*2164 * Record that the new update came via HEAD, so that2165 * when we process it, split_head_update() doesn't try2166 * to add another reflog update for HEAD. Note that2167 * this bit will be propagated if the new_update2168 * itself needs to be split.2169 */2170 new_flags |= REF_UPDATE_VIA_HEAD;2171}21722173 new_update =ref_transaction_add_update(2174 transaction, referent, new_flags,2175 update->new_oid.hash, update->old_oid.hash,2176 update->msg);21772178 new_update->parent_update = update;21792180/*2181 * Change the symbolic ref update to log only. Also, it2182 * doesn't need to check its old SHA-1 value, as that will be2183 * done when new_update is processed.2184 */2185 update->flags |= REF_LOG_ONLY | REF_NODEREF;2186 update->flags &= ~REF_HAVE_OLD;21872188 item->util = new_update;21892190return0;2191}21922193/*2194 * Return the refname under which update was originally requested.2195 */2196static const char*original_update_refname(struct ref_update *update)2197{2198while(update->parent_update)2199 update = update->parent_update;22002201return update->refname;2202}22032204/*2205 * Check whether the REF_HAVE_OLD and old_oid values stored in update2206 * are consistent with oid, which is the reference's current value. If2207 * everything is OK, return 0; otherwise, write an error message to2208 * err and return -1.2209 */2210static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2211struct strbuf *err)2212{2213if(!(update->flags & REF_HAVE_OLD) ||2214!oidcmp(oid, &update->old_oid))2215return0;22162217if(is_null_oid(&update->old_oid))2218strbuf_addf(err,"cannot lock ref '%s': "2219"reference already exists",2220original_update_refname(update));2221else if(is_null_oid(oid))2222strbuf_addf(err,"cannot lock ref '%s': "2223"reference is missing but expected%s",2224original_update_refname(update),2225oid_to_hex(&update->old_oid));2226else2227strbuf_addf(err,"cannot lock ref '%s': "2228"is at%sbut expected%s",2229original_update_refname(update),2230oid_to_hex(oid),2231oid_to_hex(&update->old_oid));22322233return-1;2234}22352236/*2237 * Prepare for carrying out update:2238 * - Lock the reference referred to by update.2239 * - Read the reference under lock.2240 * - Check that its old SHA-1 value (if specified) is correct, and in2241 * any case record it in update->lock->old_oid for later use when2242 * writing the reflog.2243 * - If it is a symref update without REF_NODEREF, split it up into a2244 * REF_LOG_ONLY update of the symref and add a separate update for2245 * the referent to transaction.2246 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2247 * update of HEAD.2248 */2249static intlock_ref_for_update(struct files_ref_store *refs,2250struct ref_update *update,2251struct ref_transaction *transaction,2252const char*head_ref,2253struct string_list *affected_refnames,2254struct strbuf *err)2255{2256struct strbuf referent = STRBUF_INIT;2257int mustexist = (update->flags & REF_HAVE_OLD) &&2258!is_null_oid(&update->old_oid);2259int ret;2260struct ref_lock *lock;22612262files_assert_main_repository(refs,"lock_ref_for_update");22632264if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2265 update->flags |= REF_DELETING;22662267if(head_ref) {2268 ret =split_head_update(update, transaction, head_ref,2269 affected_refnames, err);2270if(ret)2271return ret;2272}22732274 ret =lock_raw_ref(refs, update->refname, mustexist,2275 affected_refnames, NULL,2276&lock, &referent,2277&update->type, err);2278if(ret) {2279char*reason;22802281 reason =strbuf_detach(err, NULL);2282strbuf_addf(err,"cannot lock ref '%s':%s",2283original_update_refname(update), reason);2284free(reason);2285return ret;2286}22872288 update->backend_data = lock;22892290if(update->type & REF_ISSYMREF) {2291if(update->flags & REF_NODEREF) {2292/*2293 * We won't be reading the referent as part of2294 * the transaction, so we have to read it here2295 * to record and possibly check old_sha1:2296 */2297if(refs_read_ref_full(&refs->base,2298 referent.buf,0,2299 lock->old_oid.hash, NULL)) {2300if(update->flags & REF_HAVE_OLD) {2301strbuf_addf(err,"cannot lock ref '%s': "2302"error reading reference",2303original_update_refname(update));2304return-1;2305}2306}else if(check_old_oid(update, &lock->old_oid, err)) {2307return TRANSACTION_GENERIC_ERROR;2308}2309}else{2310/*2311 * Create a new update for the reference this2312 * symref is pointing at. Also, we will record2313 * and verify old_sha1 for this update as part2314 * of processing the split-off update, so we2315 * don't have to do it here.2316 */2317 ret =split_symref_update(refs, update,2318 referent.buf, transaction,2319 affected_refnames, err);2320if(ret)2321return ret;2322}2323}else{2324struct ref_update *parent_update;23252326if(check_old_oid(update, &lock->old_oid, err))2327return TRANSACTION_GENERIC_ERROR;23282329/*2330 * If this update is happening indirectly because of a2331 * symref update, record the old SHA-1 in the parent2332 * update:2333 */2334for(parent_update = update->parent_update;2335 parent_update;2336 parent_update = parent_update->parent_update) {2337struct ref_lock *parent_lock = parent_update->backend_data;2338oidcpy(&parent_lock->old_oid, &lock->old_oid);2339}2340}23412342if((update->flags & REF_HAVE_NEW) &&2343!(update->flags & REF_DELETING) &&2344!(update->flags & REF_LOG_ONLY)) {2345if(!(update->type & REF_ISSYMREF) &&2346!oidcmp(&lock->old_oid, &update->new_oid)) {2347/*2348 * The reference already has the desired2349 * value, so we don't need to write it.2350 */2351}else if(write_ref_to_lockfile(lock, &update->new_oid,2352 err)) {2353char*write_err =strbuf_detach(err, NULL);23542355/*2356 * The lock was freed upon failure of2357 * write_ref_to_lockfile():2358 */2359 update->backend_data = NULL;2360strbuf_addf(err,2361"cannot update ref '%s':%s",2362 update->refname, write_err);2363free(write_err);2364return TRANSACTION_GENERIC_ERROR;2365}else{2366 update->flags |= REF_NEEDS_COMMIT;2367}2368}2369if(!(update->flags & REF_NEEDS_COMMIT)) {2370/*2371 * We didn't call write_ref_to_lockfile(), so2372 * the lockfile is still open. Close it to2373 * free up the file descriptor:2374 */2375if(close_ref(lock)) {2376strbuf_addf(err,"couldn't close '%s.lock'",2377 update->refname);2378return TRANSACTION_GENERIC_ERROR;2379}2380}2381return0;2382}23832384/*2385 * Unlock any references in `transaction` that are still locked, and2386 * mark the transaction closed.2387 */2388static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2389{2390size_t i;23912392for(i =0; i < transaction->nr; i++) {2393struct ref_update *update = transaction->updates[i];2394struct ref_lock *lock = update->backend_data;23952396if(lock) {2397unlock_ref(lock);2398 update->backend_data = NULL;2399}2400}24012402 transaction->state = REF_TRANSACTION_CLOSED;2403}24042405static intfiles_transaction_prepare(struct ref_store *ref_store,2406struct ref_transaction *transaction,2407struct strbuf *err)2408{2409struct files_ref_store *refs =2410files_downcast(ref_store, REF_STORE_WRITE,2411"ref_transaction_prepare");2412size_t i;2413int ret =0;2414struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2415char*head_ref = NULL;2416int head_type;2417struct object_id head_oid;24182419assert(err);24202421if(!transaction->nr)2422goto cleanup;24232424/*2425 * Fail if a refname appears more than once in the2426 * transaction. (If we end up splitting up any updates using2427 * split_symref_update() or split_head_update(), those2428 * functions will check that the new updates don't have the2429 * same refname as any existing ones.)2430 */2431for(i =0; i < transaction->nr; i++) {2432struct ref_update *update = transaction->updates[i];2433struct string_list_item *item =2434string_list_append(&affected_refnames, update->refname);24352436/*2437 * We store a pointer to update in item->util, but at2438 * the moment we never use the value of this field2439 * except to check whether it is non-NULL.2440 */2441 item->util = update;2442}2443string_list_sort(&affected_refnames);2444if(ref_update_reject_duplicates(&affected_refnames, err)) {2445 ret = TRANSACTION_GENERIC_ERROR;2446goto cleanup;2447}24482449/*2450 * Special hack: If a branch is updated directly and HEAD2451 * points to it (may happen on the remote side of a push2452 * for example) then logically the HEAD reflog should be2453 * updated too.2454 *2455 * A generic solution would require reverse symref lookups,2456 * but finding all symrefs pointing to a given branch would be2457 * rather costly for this rare event (the direct update of a2458 * branch) to be worth it. So let's cheat and check with HEAD2459 * only, which should cover 99% of all usage scenarios (even2460 * 100% of the default ones).2461 *2462 * So if HEAD is a symbolic reference, then record the name of2463 * the reference that it points to. If we see an update of2464 * head_ref within the transaction, then split_head_update()2465 * arranges for the reflog of HEAD to be updated, too.2466 */2467 head_ref =refs_resolve_refdup(ref_store,"HEAD",2468 RESOLVE_REF_NO_RECURSE,2469 head_oid.hash, &head_type);24702471if(head_ref && !(head_type & REF_ISSYMREF)) {2472FREE_AND_NULL(head_ref);2473}24742475/*2476 * Acquire all locks, verify old values if provided, check2477 * that new values are valid, and write new values to the2478 * lockfiles, ready to be activated. Only keep one lockfile2479 * open at a time to avoid running out of file descriptors.2480 * Note that lock_ref_for_update() might append more updates2481 * to the transaction.2482 */2483for(i =0; i < transaction->nr; i++) {2484struct ref_update *update = transaction->updates[i];24852486 ret =lock_ref_for_update(refs, update, transaction,2487 head_ref, &affected_refnames, err);2488if(ret)2489break;2490}24912492cleanup:2493free(head_ref);2494string_list_clear(&affected_refnames,0);24952496if(ret)2497files_transaction_cleanup(transaction);2498else2499 transaction->state = REF_TRANSACTION_PREPARED;25002501return ret;2502}25032504static intfiles_transaction_finish(struct ref_store *ref_store,2505struct ref_transaction *transaction,2506struct strbuf *err)2507{2508struct files_ref_store *refs =2509files_downcast(ref_store,0,"ref_transaction_finish");2510size_t i;2511int ret =0;2512struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2513struct string_list_item *ref_to_delete;2514struct strbuf sb = STRBUF_INIT;25152516assert(err);25172518if(!transaction->nr) {2519 transaction->state = REF_TRANSACTION_CLOSED;2520return0;2521}25222523/* Perform updates first so live commits remain referenced */2524for(i =0; i < transaction->nr; i++) {2525struct ref_update *update = transaction->updates[i];2526struct ref_lock *lock = update->backend_data;25272528if(update->flags & REF_NEEDS_COMMIT ||2529 update->flags & REF_LOG_ONLY) {2530if(files_log_ref_write(refs,2531 lock->ref_name,2532&lock->old_oid,2533&update->new_oid,2534 update->msg, update->flags,2535 err)) {2536char*old_msg =strbuf_detach(err, NULL);25372538strbuf_addf(err,"cannot update the ref '%s':%s",2539 lock->ref_name, old_msg);2540free(old_msg);2541unlock_ref(lock);2542 update->backend_data = NULL;2543 ret = TRANSACTION_GENERIC_ERROR;2544goto cleanup;2545}2546}2547if(update->flags & REF_NEEDS_COMMIT) {2548clear_loose_ref_cache(refs);2549if(commit_ref(lock)) {2550strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2551unlock_ref(lock);2552 update->backend_data = NULL;2553 ret = TRANSACTION_GENERIC_ERROR;2554goto cleanup;2555}2556}2557}2558/* Perform deletes now that updates are safely completed */2559for(i =0; i < transaction->nr; i++) {2560struct ref_update *update = transaction->updates[i];2561struct ref_lock *lock = update->backend_data;25622563if(update->flags & REF_DELETING &&2564!(update->flags & REF_LOG_ONLY)) {2565if(!(update->type & REF_ISPACKED) ||2566 update->type & REF_ISSYMREF) {2567/* It is a loose reference. */2568strbuf_reset(&sb);2569files_ref_path(refs, &sb, lock->ref_name);2570if(unlink_or_msg(sb.buf, err)) {2571 ret = TRANSACTION_GENERIC_ERROR;2572goto cleanup;2573}2574 update->flags |= REF_DELETED_LOOSE;2575}25762577if(!(update->flags & REF_ISPRUNING))2578string_list_append(&refs_to_delete,2579 lock->ref_name);2580}2581}25822583if(packed_refs_lock(refs->packed_ref_store,0, err)) {2584 ret = TRANSACTION_GENERIC_ERROR;2585goto cleanup;2586}25872588if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2589 ret = TRANSACTION_GENERIC_ERROR;2590packed_refs_unlock(refs->packed_ref_store);2591goto cleanup;2592}25932594packed_refs_unlock(refs->packed_ref_store);25952596/* Delete the reflogs of any references that were deleted: */2597for_each_string_list_item(ref_to_delete, &refs_to_delete) {2598strbuf_reset(&sb);2599files_reflog_path(refs, &sb, ref_to_delete->string);2600if(!unlink_or_warn(sb.buf))2601try_remove_empty_parents(refs, ref_to_delete->string,2602 REMOVE_EMPTY_PARENTS_REFLOG);2603}26042605clear_loose_ref_cache(refs);26062607cleanup:2608files_transaction_cleanup(transaction);26092610for(i =0; i < transaction->nr; i++) {2611struct ref_update *update = transaction->updates[i];26122613if(update->flags & REF_DELETED_LOOSE) {2614/*2615 * The loose reference was deleted. Delete any2616 * empty parent directories. (Note that this2617 * can only work because we have already2618 * removed the lockfile.)2619 */2620try_remove_empty_parents(refs, update->refname,2621 REMOVE_EMPTY_PARENTS_REF);2622}2623}26242625strbuf_release(&sb);2626string_list_clear(&refs_to_delete,0);2627return ret;2628}26292630static intfiles_transaction_abort(struct ref_store *ref_store,2631struct ref_transaction *transaction,2632struct strbuf *err)2633{2634files_transaction_cleanup(transaction);2635return0;2636}26372638static intref_present(const char*refname,2639const struct object_id *oid,int flags,void*cb_data)2640{2641struct string_list *affected_refnames = cb_data;26422643returnstring_list_has_string(affected_refnames, refname);2644}26452646static intfiles_initial_transaction_commit(struct ref_store *ref_store,2647struct ref_transaction *transaction,2648struct strbuf *err)2649{2650struct files_ref_store *refs =2651files_downcast(ref_store, REF_STORE_WRITE,2652"initial_ref_transaction_commit");2653size_t i;2654int ret =0;2655struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26562657assert(err);26582659if(transaction->state != REF_TRANSACTION_OPEN)2660die("BUG: commit called for transaction that is not open");26612662/* Fail if a refname appears more than once in the transaction: */2663for(i =0; i < transaction->nr; i++)2664string_list_append(&affected_refnames,2665 transaction->updates[i]->refname);2666string_list_sort(&affected_refnames);2667if(ref_update_reject_duplicates(&affected_refnames, err)) {2668 ret = TRANSACTION_GENERIC_ERROR;2669goto cleanup;2670}26712672/*2673 * It's really undefined to call this function in an active2674 * repository or when there are existing references: we are2675 * only locking and changing packed-refs, so (1) any2676 * simultaneous processes might try to change a reference at2677 * the same time we do, and (2) any existing loose versions of2678 * the references that we are setting would have precedence2679 * over our values. But some remote helpers create the remote2680 * "HEAD" and "master" branches before calling this function,2681 * so here we really only check that none of the references2682 * that we are creating already exists.2683 */2684if(refs_for_each_rawref(&refs->base, ref_present,2685&affected_refnames))2686die("BUG: initial ref transaction called with existing refs");26872688for(i =0; i < transaction->nr; i++) {2689struct ref_update *update = transaction->updates[i];26902691if((update->flags & REF_HAVE_OLD) &&2692!is_null_oid(&update->old_oid))2693die("BUG: initial ref transaction with old_sha1 set");2694if(refs_verify_refname_available(&refs->base, update->refname,2695&affected_refnames, NULL,2696 err)) {2697 ret = TRANSACTION_NAME_CONFLICT;2698goto cleanup;2699}2700}27012702if(packed_refs_lock(refs->packed_ref_store,0, err)) {2703 ret = TRANSACTION_GENERIC_ERROR;2704goto cleanup;2705}27062707for(i =0; i < transaction->nr; i++) {2708struct ref_update *update = transaction->updates[i];27092710if((update->flags & REF_HAVE_NEW) &&2711!is_null_oid(&update->new_oid))2712add_packed_ref(refs->packed_ref_store, update->refname,2713&update->new_oid);2714}27152716if(commit_packed_refs(refs->packed_ref_store, err)) {2717 ret = TRANSACTION_GENERIC_ERROR;2718goto cleanup;2719}27202721cleanup:2722packed_refs_unlock(refs->packed_ref_store);2723 transaction->state = REF_TRANSACTION_CLOSED;2724string_list_clear(&affected_refnames,0);2725return ret;2726}27272728struct expire_reflog_cb {2729unsigned int flags;2730 reflog_expiry_should_prune_fn *should_prune_fn;2731void*policy_cb;2732FILE*newlog;2733struct object_id last_kept_oid;2734};27352736static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2737const char*email, timestamp_t timestamp,int tz,2738const char*message,void*cb_data)2739{2740struct expire_reflog_cb *cb = cb_data;2741struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27422743if(cb->flags & EXPIRE_REFLOGS_REWRITE)2744 ooid = &cb->last_kept_oid;27452746if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2747 message, policy_cb)) {2748if(!cb->newlog)2749printf("would prune%s", message);2750else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2751printf("prune%s", message);2752}else{2753if(cb->newlog) {2754fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2755oid_to_hex(ooid),oid_to_hex(noid),2756 email, timestamp, tz, message);2757oidcpy(&cb->last_kept_oid, noid);2758}2759if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2760printf("keep%s", message);2761}2762return0;2763}27642765static intfiles_reflog_expire(struct ref_store *ref_store,2766const char*refname,const unsigned char*sha1,2767unsigned int flags,2768 reflog_expiry_prepare_fn prepare_fn,2769 reflog_expiry_should_prune_fn should_prune_fn,2770 reflog_expiry_cleanup_fn cleanup_fn,2771void*policy_cb_data)2772{2773struct files_ref_store *refs =2774files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2775static struct lock_file reflog_lock;2776struct expire_reflog_cb cb;2777struct ref_lock *lock;2778struct strbuf log_file_sb = STRBUF_INIT;2779char*log_file;2780int status =0;2781int type;2782struct strbuf err = STRBUF_INIT;2783struct object_id oid;27842785memset(&cb,0,sizeof(cb));2786 cb.flags = flags;2787 cb.policy_cb = policy_cb_data;2788 cb.should_prune_fn = should_prune_fn;27892790/*2791 * The reflog file is locked by holding the lock on the2792 * reference itself, plus we might need to update the2793 * reference if --updateref was specified:2794 */2795 lock =lock_ref_sha1_basic(refs, refname, sha1,2796 NULL, NULL, REF_NODEREF,2797&type, &err);2798if(!lock) {2799error("cannot lock ref '%s':%s", refname, err.buf);2800strbuf_release(&err);2801return-1;2802}2803if(!refs_reflog_exists(ref_store, refname)) {2804unlock_ref(lock);2805return0;2806}28072808files_reflog_path(refs, &log_file_sb, refname);2809 log_file =strbuf_detach(&log_file_sb, NULL);2810if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2811/*2812 * Even though holding $GIT_DIR/logs/$reflog.lock has2813 * no locking implications, we use the lock_file2814 * machinery here anyway because it does a lot of the2815 * work we need, including cleaning up if the program2816 * exits unexpectedly.2817 */2818if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2819struct strbuf err = STRBUF_INIT;2820unable_to_lock_message(log_file, errno, &err);2821error("%s", err.buf);2822strbuf_release(&err);2823goto failure;2824}2825 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2826if(!cb.newlog) {2827error("cannot fdopen%s(%s)",2828get_lock_file_path(&reflog_lock),strerror(errno));2829goto failure;2830}2831}28322833hashcpy(oid.hash, sha1);28342835(*prepare_fn)(refname, &oid, cb.policy_cb);2836refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2837(*cleanup_fn)(cb.policy_cb);28382839if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2840/*2841 * It doesn't make sense to adjust a reference pointed2842 * to by a symbolic ref based on expiring entries in2843 * the symbolic reference's reflog. Nor can we update2844 * a reference if there are no remaining reflog2845 * entries.2846 */2847int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2848!(type & REF_ISSYMREF) &&2849!is_null_oid(&cb.last_kept_oid);28502851if(close_lock_file(&reflog_lock)) {2852 status |=error("couldn't write%s:%s", log_file,2853strerror(errno));2854}else if(update &&2855(write_in_full(get_lock_file_fd(lock->lk),2856oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2857write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2858close_ref(lock) <0)) {2859 status |=error("couldn't write%s",2860get_lock_file_path(lock->lk));2861rollback_lock_file(&reflog_lock);2862}else if(commit_lock_file(&reflog_lock)) {2863 status |=error("unable to write reflog '%s' (%s)",2864 log_file,strerror(errno));2865}else if(update &&commit_ref(lock)) {2866 status |=error("couldn't set%s", lock->ref_name);2867}2868}2869free(log_file);2870unlock_ref(lock);2871return status;28722873 failure:2874rollback_lock_file(&reflog_lock);2875free(log_file);2876unlock_ref(lock);2877return-1;2878}28792880static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2881{2882struct files_ref_store *refs =2883files_downcast(ref_store, REF_STORE_WRITE,"init_db");2884struct strbuf sb = STRBUF_INIT;28852886/*2887 * Create .git/refs/{heads,tags}2888 */2889files_ref_path(refs, &sb,"refs/heads");2890safe_create_dir(sb.buf,1);28912892strbuf_reset(&sb);2893files_ref_path(refs, &sb,"refs/tags");2894safe_create_dir(sb.buf,1);28952896strbuf_release(&sb);2897return0;2898}28992900struct ref_storage_be refs_be_files = {2901 NULL,2902"files",2903 files_ref_store_create,2904 files_init_db,2905 files_transaction_prepare,2906 files_transaction_finish,2907 files_transaction_abort,2908 files_initial_transaction_commit,29092910 files_pack_refs,2911 files_peel_ref,2912 files_create_symref,2913 files_delete_refs,2914 files_rename_ref,29152916 files_ref_iterator_begin,2917 files_read_raw_ref,29182919 files_reflog_iterator_begin,2920 files_for_each_reflog_ent,2921 files_for_each_reflog_ent_reverse,2922 files_reflog_exists,2923 files_create_reflog,2924 files_delete_reflog,2925 files_reflog_expire2926};