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;1103struct ref_transaction *transaction;11041105 transaction =ref_store_transaction_begin(refs->packed_ref_store, &err);1106if(!transaction)1107return-1;11081109packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);11101111 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1112while((ok =ref_iterator_advance(iter)) == ITER_OK) {1113/*1114 * If the loose reference can be packed, add an entry1115 * in the packed ref cache. If the reference should be1116 * pruned, also add it to refs_to_prune.1117 */1118if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1119 flags))1120continue;11211122/*1123 * Add a reference creation for this reference to the1124 * packed-refs transaction:1125 */1126if(ref_transaction_update(transaction, iter->refname,1127 iter->oid->hash, NULL,1128 REF_NODEREF, NULL, &err))1129die("failure preparing to create packed reference%s:%s",1130 iter->refname, err.buf);11311132/* Schedule the loose reference for pruning if requested. */1133if((flags & PACK_REFS_PRUNE)) {1134struct ref_to_prune *n;1135FLEX_ALLOC_STR(n, name, iter->refname);1136hashcpy(n->sha1, iter->oid->hash);1137 n->next = refs_to_prune;1138 refs_to_prune = n;1139}1140}1141if(ok != ITER_DONE)1142die("error while iterating over references");11431144if(ref_transaction_commit(transaction, &err))1145die("unable to write new packed-refs:%s", err.buf);11461147ref_transaction_free(transaction);11481149packed_refs_unlock(refs->packed_ref_store);11501151prune_refs(refs, refs_to_prune);1152strbuf_release(&err);1153return0;1154}11551156static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1157struct string_list *refnames,unsigned int flags)1158{1159struct files_ref_store *refs =1160files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1161struct strbuf err = STRBUF_INIT;1162int i, result =0;11631164if(!refnames->nr)1165return0;11661167if(packed_refs_lock(refs->packed_ref_store,0, &err))1168goto error;11691170if(refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {1171packed_refs_unlock(refs->packed_ref_store);1172goto error;1173}11741175packed_refs_unlock(refs->packed_ref_store);11761177for(i =0; i < refnames->nr; i++) {1178const char*refname = refnames->items[i].string;11791180if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1181 result |=error(_("could not remove reference%s"), refname);1182}11831184strbuf_release(&err);1185return result;11861187error:1188/*1189 * If we failed to rewrite the packed-refs file, then it is1190 * unsafe to try to remove loose refs, because doing so might1191 * expose an obsolete packed value for a reference that might1192 * even point at an object that has been garbage collected.1193 */1194if(refnames->nr ==1)1195error(_("could not delete reference%s:%s"),1196 refnames->items[0].string, err.buf);1197else1198error(_("could not delete references:%s"), err.buf);11991200strbuf_release(&err);1201return-1;1202}12031204/*1205 * People using contrib's git-new-workdir have .git/logs/refs ->1206 * /some/other/path/.git/logs/refs, and that may live on another device.1207 *1208 * IOW, to avoid cross device rename errors, the temporary renamed log must1209 * live into logs/refs.1210 */1211#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"12121213struct rename_cb {1214const char*tmp_renamed_log;1215int true_errno;1216};12171218static intrename_tmp_log_callback(const char*path,void*cb_data)1219{1220struct rename_cb *cb = cb_data;12211222if(rename(cb->tmp_renamed_log, path)) {1223/*1224 * rename(a, b) when b is an existing directory ought1225 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1226 * Sheesh. Record the true errno for error reporting,1227 * but report EISDIR to raceproof_create_file() so1228 * that it knows to retry.1229 */1230 cb->true_errno = errno;1231if(errno == ENOTDIR)1232 errno = EISDIR;1233return-1;1234}else{1235return0;1236}1237}12381239static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1240{1241struct strbuf path = STRBUF_INIT;1242struct strbuf tmp = STRBUF_INIT;1243struct rename_cb cb;1244int ret;12451246files_reflog_path(refs, &path, newrefname);1247files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1248 cb.tmp_renamed_log = tmp.buf;1249 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1250if(ret) {1251if(errno == EISDIR)1252error("directory not empty:%s", path.buf);1253else1254error("unable to move logfile%sto%s:%s",1255 tmp.buf, path.buf,1256strerror(cb.true_errno));1257}12581259strbuf_release(&path);1260strbuf_release(&tmp);1261return ret;1262}12631264static intwrite_ref_to_lockfile(struct ref_lock *lock,1265const struct object_id *oid,struct strbuf *err);1266static intcommit_ref_update(struct files_ref_store *refs,1267struct ref_lock *lock,1268const struct object_id *oid,const char*logmsg,1269struct strbuf *err);12701271static intfiles_rename_ref(struct ref_store *ref_store,1272const char*oldrefname,const char*newrefname,1273const char*logmsg)1274{1275struct files_ref_store *refs =1276files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1277struct object_id oid, orig_oid;1278int flag =0, logmoved =0;1279struct ref_lock *lock;1280struct stat loginfo;1281struct strbuf sb_oldref = STRBUF_INIT;1282struct strbuf sb_newref = STRBUF_INIT;1283struct strbuf tmp_renamed_log = STRBUF_INIT;1284int log, ret;1285struct strbuf err = STRBUF_INIT;12861287files_reflog_path(refs, &sb_oldref, oldrefname);1288files_reflog_path(refs, &sb_newref, newrefname);1289files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12901291 log = !lstat(sb_oldref.buf, &loginfo);1292if(log &&S_ISLNK(loginfo.st_mode)) {1293 ret =error("reflog for%sis a symlink", oldrefname);1294goto out;1295}12961297if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1298 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1299 orig_oid.hash, &flag)) {1300 ret =error("refname%snot found", oldrefname);1301goto out;1302}13031304if(flag & REF_ISSYMREF) {1305 ret =error("refname%sis a symbolic ref, renaming it is not supported",1306 oldrefname);1307goto out;1308}1309if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1310 ret =1;1311goto out;1312}13131314if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1315 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1316 oldrefname,strerror(errno));1317goto out;1318}13191320if(refs_delete_ref(&refs->base, logmsg, oldrefname,1321 orig_oid.hash, REF_NODEREF)) {1322error("unable to delete old%s", oldrefname);1323goto rollback;1324}13251326/*1327 * Since we are doing a shallow lookup, oid is not the1328 * correct value to pass to delete_ref as old_oid. But that1329 * doesn't matter, because an old_oid check wouldn't add to1330 * the safety anyway; we want to delete the reference whatever1331 * its current value.1332 */1333if(!refs_read_ref_full(&refs->base, newrefname,1334 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1335 oid.hash, NULL) &&1336refs_delete_ref(&refs->base, NULL, newrefname,1337 NULL, REF_NODEREF)) {1338if(errno == EISDIR) {1339struct strbuf path = STRBUF_INIT;1340int result;13411342files_ref_path(refs, &path, newrefname);1343 result =remove_empty_directories(&path);1344strbuf_release(&path);13451346if(result) {1347error("Directory not empty:%s", newrefname);1348goto rollback;1349}1350}else{1351error("unable to delete existing%s", newrefname);1352goto rollback;1353}1354}13551356if(log &&rename_tmp_log(refs, newrefname))1357goto rollback;13581359 logmoved = log;13601361 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1362 REF_NODEREF, NULL, &err);1363if(!lock) {1364error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1365strbuf_release(&err);1366goto rollback;1367}1368oidcpy(&lock->old_oid, &orig_oid);13691370if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1371commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1372error("unable to write current sha1 into%s:%s", newrefname, err.buf);1373strbuf_release(&err);1374goto rollback;1375}13761377 ret =0;1378goto out;13791380 rollback:1381 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1382 REF_NODEREF, NULL, &err);1383if(!lock) {1384error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1385strbuf_release(&err);1386goto rollbacklog;1387}13881389 flag = log_all_ref_updates;1390 log_all_ref_updates = LOG_REFS_NONE;1391if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1392commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1393error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1394strbuf_release(&err);1395}1396 log_all_ref_updates = flag;13971398 rollbacklog:1399if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1400error("unable to restore logfile%sfrom%s:%s",1401 oldrefname, newrefname,strerror(errno));1402if(!logmoved && log &&1403rename(tmp_renamed_log.buf, sb_oldref.buf))1404error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1405 oldrefname,strerror(errno));1406 ret =1;1407 out:1408strbuf_release(&sb_newref);1409strbuf_release(&sb_oldref);1410strbuf_release(&tmp_renamed_log);14111412return ret;1413}14141415static intclose_ref(struct ref_lock *lock)1416{1417if(close_lock_file(lock->lk))1418return-1;1419return0;1420}14211422static intcommit_ref(struct ref_lock *lock)1423{1424char*path =get_locked_file_path(lock->lk);1425struct stat st;14261427if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1428/*1429 * There is a directory at the path we want to rename1430 * the lockfile to. Hopefully it is empty; try to1431 * delete it.1432 */1433size_t len =strlen(path);1434struct strbuf sb_path = STRBUF_INIT;14351436strbuf_attach(&sb_path, path, len, len);14371438/*1439 * If this fails, commit_lock_file() will also fail1440 * and will report the problem.1441 */1442remove_empty_directories(&sb_path);1443strbuf_release(&sb_path);1444}else{1445free(path);1446}14471448if(commit_lock_file(lock->lk))1449return-1;1450return0;1451}14521453static intopen_or_create_logfile(const char*path,void*cb)1454{1455int*fd = cb;14561457*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1458return(*fd <0) ? -1:0;1459}14601461/*1462 * Create a reflog for a ref. If force_create = 0, only create the1463 * reflog for certain refs (those for which should_autocreate_reflog1464 * returns non-zero). Otherwise, create it regardless of the reference1465 * name. If the logfile already existed or was created, return 0 and1466 * set *logfd to the file descriptor opened for appending to the file.1467 * If no logfile exists and we decided not to create one, return 0 and1468 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1469 * return -1.1470 */1471static intlog_ref_setup(struct files_ref_store *refs,1472const char*refname,int force_create,1473int*logfd,struct strbuf *err)1474{1475struct strbuf logfile_sb = STRBUF_INIT;1476char*logfile;14771478files_reflog_path(refs, &logfile_sb, refname);1479 logfile =strbuf_detach(&logfile_sb, NULL);14801481if(force_create ||should_autocreate_reflog(refname)) {1482if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1483if(errno == ENOENT)1484strbuf_addf(err,"unable to create directory for '%s': "1485"%s", logfile,strerror(errno));1486else if(errno == EISDIR)1487strbuf_addf(err,"there are still logs under '%s'",1488 logfile);1489else1490strbuf_addf(err,"unable to append to '%s':%s",1491 logfile,strerror(errno));14921493goto error;1494}1495}else{1496*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1497if(*logfd <0) {1498if(errno == ENOENT || errno == EISDIR) {1499/*1500 * The logfile doesn't already exist,1501 * but that is not an error; it only1502 * means that we won't write log1503 * entries to it.1504 */1505;1506}else{1507strbuf_addf(err,"unable to append to '%s':%s",1508 logfile,strerror(errno));1509goto error;1510}1511}1512}15131514if(*logfd >=0)1515adjust_shared_perm(logfile);15161517free(logfile);1518return0;15191520error:1521free(logfile);1522return-1;1523}15241525static intfiles_create_reflog(struct ref_store *ref_store,1526const char*refname,int force_create,1527struct strbuf *err)1528{1529struct files_ref_store *refs =1530files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1531int fd;15321533if(log_ref_setup(refs, refname, force_create, &fd, err))1534return-1;15351536if(fd >=0)1537close(fd);15381539return0;1540}15411542static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1543const struct object_id *new_oid,1544const char*committer,const char*msg)1545{1546int msglen, written;1547unsigned maxlen, len;1548char*logrec;15491550 msglen = msg ?strlen(msg) :0;1551 maxlen =strlen(committer) + msglen +100;1552 logrec =xmalloc(maxlen);1553 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1554oid_to_hex(old_oid),1555oid_to_hex(new_oid),1556 committer);1557if(msglen)1558 len +=copy_reflog_msg(logrec + len -1, msg) -1;15591560 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1561free(logrec);1562if(written != len)1563return-1;15641565return0;1566}15671568static intfiles_log_ref_write(struct files_ref_store *refs,1569const char*refname,const struct object_id *old_oid,1570const struct object_id *new_oid,const char*msg,1571int flags,struct strbuf *err)1572{1573int logfd, result;15741575if(log_all_ref_updates == LOG_REFS_UNSET)1576 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15771578 result =log_ref_setup(refs, refname,1579 flags & REF_FORCE_CREATE_REFLOG,1580&logfd, err);15811582if(result)1583return result;15841585if(logfd <0)1586return0;1587 result =log_ref_write_fd(logfd, old_oid, new_oid,1588git_committer_info(0), msg);1589if(result) {1590struct strbuf sb = STRBUF_INIT;1591int save_errno = errno;15921593files_reflog_path(refs, &sb, refname);1594strbuf_addf(err,"unable to append to '%s':%s",1595 sb.buf,strerror(save_errno));1596strbuf_release(&sb);1597close(logfd);1598return-1;1599}1600if(close(logfd)) {1601struct strbuf sb = STRBUF_INIT;1602int save_errno = errno;16031604files_reflog_path(refs, &sb, refname);1605strbuf_addf(err,"unable to append to '%s':%s",1606 sb.buf,strerror(save_errno));1607strbuf_release(&sb);1608return-1;1609}1610return0;1611}16121613/*1614 * Write sha1 into the open lockfile, then close the lockfile. On1615 * errors, rollback the lockfile, fill in *err and1616 * return -1.1617 */1618static intwrite_ref_to_lockfile(struct ref_lock *lock,1619const struct object_id *oid,struct strbuf *err)1620{1621static char term ='\n';1622struct object *o;1623int fd;16241625 o =parse_object(oid);1626if(!o) {1627strbuf_addf(err,1628"trying to write ref '%s' with nonexistent object%s",1629 lock->ref_name,oid_to_hex(oid));1630unlock_ref(lock);1631return-1;1632}1633if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1634strbuf_addf(err,1635"trying to write non-commit object%sto branch '%s'",1636oid_to_hex(oid), lock->ref_name);1637unlock_ref(lock);1638return-1;1639}1640 fd =get_lock_file_fd(lock->lk);1641if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1642write_in_full(fd, &term,1) !=1||1643close_ref(lock) <0) {1644strbuf_addf(err,1645"couldn't write '%s'",get_lock_file_path(lock->lk));1646unlock_ref(lock);1647return-1;1648}1649return0;1650}16511652/*1653 * Commit a change to a loose reference that has already been written1654 * to the loose reference lockfile. Also update the reflogs if1655 * necessary, using the specified lockmsg (which can be NULL).1656 */1657static intcommit_ref_update(struct files_ref_store *refs,1658struct ref_lock *lock,1659const struct object_id *oid,const char*logmsg,1660struct strbuf *err)1661{1662files_assert_main_repository(refs,"commit_ref_update");16631664clear_loose_ref_cache(refs);1665if(files_log_ref_write(refs, lock->ref_name,1666&lock->old_oid, oid,1667 logmsg,0, err)) {1668char*old_msg =strbuf_detach(err, NULL);1669strbuf_addf(err,"cannot update the ref '%s':%s",1670 lock->ref_name, old_msg);1671free(old_msg);1672unlock_ref(lock);1673return-1;1674}16751676if(strcmp(lock->ref_name,"HEAD") !=0) {1677/*1678 * Special hack: If a branch is updated directly and HEAD1679 * points to it (may happen on the remote side of a push1680 * for example) then logically the HEAD reflog should be1681 * updated too.1682 * A generic solution implies reverse symref information,1683 * but finding all symrefs pointing to the given branch1684 * would be rather costly for this rare event (the direct1685 * update of a branch) to be worth it. So let's cheat and1686 * check with HEAD only which should cover 99% of all usage1687 * scenarios (even 100% of the default ones).1688 */1689struct object_id head_oid;1690int head_flag;1691const char*head_ref;16921693 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1694 RESOLVE_REF_READING,1695 head_oid.hash, &head_flag);1696if(head_ref && (head_flag & REF_ISSYMREF) &&1697!strcmp(head_ref, lock->ref_name)) {1698struct strbuf log_err = STRBUF_INIT;1699if(files_log_ref_write(refs,"HEAD",1700&lock->old_oid, oid,1701 logmsg,0, &log_err)) {1702error("%s", log_err.buf);1703strbuf_release(&log_err);1704}1705}1706}17071708if(commit_ref(lock)) {1709strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1710unlock_ref(lock);1711return-1;1712}17131714unlock_ref(lock);1715return0;1716}17171718static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1719{1720int ret = -1;1721#ifndef NO_SYMLINK_HEAD1722char*ref_path =get_locked_file_path(lock->lk);1723unlink(ref_path);1724 ret =symlink(target, ref_path);1725free(ref_path);17261727if(ret)1728fprintf(stderr,"no symlink - falling back to symbolic ref\n");1729#endif1730return ret;1731}17321733static voidupdate_symref_reflog(struct files_ref_store *refs,1734struct ref_lock *lock,const char*refname,1735const char*target,const char*logmsg)1736{1737struct strbuf err = STRBUF_INIT;1738struct object_id new_oid;1739if(logmsg &&1740!refs_read_ref_full(&refs->base, target,1741 RESOLVE_REF_READING, new_oid.hash, NULL) &&1742files_log_ref_write(refs, refname, &lock->old_oid,1743&new_oid, logmsg,0, &err)) {1744error("%s", err.buf);1745strbuf_release(&err);1746}1747}17481749static intcreate_symref_locked(struct files_ref_store *refs,1750struct ref_lock *lock,const char*refname,1751const char*target,const char*logmsg)1752{1753if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1754update_symref_reflog(refs, lock, refname, target, logmsg);1755return0;1756}17571758if(!fdopen_lock_file(lock->lk,"w"))1759returnerror("unable to fdopen%s:%s",1760 lock->lk->tempfile.filename.buf,strerror(errno));17611762update_symref_reflog(refs, lock, refname, target, logmsg);17631764/* no error check; commit_ref will check ferror */1765fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1766if(commit_ref(lock) <0)1767returnerror("unable to write symref for%s:%s", refname,1768strerror(errno));1769return0;1770}17711772static intfiles_create_symref(struct ref_store *ref_store,1773const char*refname,const char*target,1774const char*logmsg)1775{1776struct files_ref_store *refs =1777files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1778struct strbuf err = STRBUF_INIT;1779struct ref_lock *lock;1780int ret;17811782 lock =lock_ref_sha1_basic(refs, refname, NULL,1783 NULL, NULL, REF_NODEREF, NULL,1784&err);1785if(!lock) {1786error("%s", err.buf);1787strbuf_release(&err);1788return-1;1789}17901791 ret =create_symref_locked(refs, lock, refname, target, logmsg);1792unlock_ref(lock);1793return ret;1794}17951796static intfiles_reflog_exists(struct ref_store *ref_store,1797const char*refname)1798{1799struct files_ref_store *refs =1800files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1801struct strbuf sb = STRBUF_INIT;1802struct stat st;1803int ret;18041805files_reflog_path(refs, &sb, refname);1806 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1807strbuf_release(&sb);1808return ret;1809}18101811static intfiles_delete_reflog(struct ref_store *ref_store,1812const char*refname)1813{1814struct files_ref_store *refs =1815files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1816struct strbuf sb = STRBUF_INIT;1817int ret;18181819files_reflog_path(refs, &sb, refname);1820 ret =remove_path(sb.buf);1821strbuf_release(&sb);1822return ret;1823}18241825static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1826{1827struct object_id ooid, noid;1828char*email_end, *message;1829 timestamp_t timestamp;1830int tz;1831const char*p = sb->buf;18321833/* old SP new SP name <email> SP time TAB msg LF */1834if(!sb->len || sb->buf[sb->len -1] !='\n'||1835parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1836parse_oid_hex(p, &noid, &p) || *p++ !=' '||1837!(email_end =strchr(p,'>')) ||1838 email_end[1] !=' '||1839!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1840!message || message[0] !=' '||1841(message[1] !='+'&& message[1] !='-') ||1842!isdigit(message[2]) || !isdigit(message[3]) ||1843!isdigit(message[4]) || !isdigit(message[5]))1844return0;/* corrupt? */1845 email_end[1] ='\0';1846 tz =strtol(message +1, NULL,10);1847if(message[6] !='\t')1848 message +=6;1849else1850 message +=7;1851returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1852}18531854static char*find_beginning_of_line(char*bob,char*scan)1855{1856while(bob < scan && *(--scan) !='\n')1857;/* keep scanning backwards */1858/*1859 * Return either beginning of the buffer, or LF at the end of1860 * the previous line.1861 */1862return scan;1863}18641865static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1866const char*refname,1867 each_reflog_ent_fn fn,1868void*cb_data)1869{1870struct files_ref_store *refs =1871files_downcast(ref_store, REF_STORE_READ,1872"for_each_reflog_ent_reverse");1873struct strbuf sb = STRBUF_INIT;1874FILE*logfp;1875long pos;1876int ret =0, at_tail =1;18771878files_reflog_path(refs, &sb, refname);1879 logfp =fopen(sb.buf,"r");1880strbuf_release(&sb);1881if(!logfp)1882return-1;18831884/* Jump to the end */1885if(fseek(logfp,0, SEEK_END) <0)1886 ret =error("cannot seek back reflog for%s:%s",1887 refname,strerror(errno));1888 pos =ftell(logfp);1889while(!ret &&0< pos) {1890int cnt;1891size_t nread;1892char buf[BUFSIZ];1893char*endp, *scanp;18941895/* Fill next block from the end */1896 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1897if(fseek(logfp, pos - cnt, SEEK_SET)) {1898 ret =error("cannot seek back reflog for%s:%s",1899 refname,strerror(errno));1900break;1901}1902 nread =fread(buf, cnt,1, logfp);1903if(nread !=1) {1904 ret =error("cannot read%dbytes from reflog for%s:%s",1905 cnt, refname,strerror(errno));1906break;1907}1908 pos -= cnt;19091910 scanp = endp = buf + cnt;1911if(at_tail && scanp[-1] =='\n')1912/* Looking at the final LF at the end of the file */1913 scanp--;1914 at_tail =0;19151916while(buf < scanp) {1917/*1918 * terminating LF of the previous line, or the beginning1919 * of the buffer.1920 */1921char*bp;19221923 bp =find_beginning_of_line(buf, scanp);19241925if(*bp =='\n') {1926/*1927 * The newline is the end of the previous line,1928 * so we know we have complete line starting1929 * at (bp + 1). Prefix it onto any prior data1930 * we collected for the line and process it.1931 */1932strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1933 scanp = bp;1934 endp = bp +1;1935 ret =show_one_reflog_ent(&sb, fn, cb_data);1936strbuf_reset(&sb);1937if(ret)1938break;1939}else if(!pos) {1940/*1941 * We are at the start of the buffer, and the1942 * start of the file; there is no previous1943 * line, and we have everything for this one.1944 * Process it, and we can end the loop.1945 */1946strbuf_splice(&sb,0,0, buf, endp - buf);1947 ret =show_one_reflog_ent(&sb, fn, cb_data);1948strbuf_reset(&sb);1949break;1950}19511952if(bp == buf) {1953/*1954 * We are at the start of the buffer, and there1955 * is more file to read backwards. Which means1956 * we are in the middle of a line. Note that we1957 * may get here even if *bp was a newline; that1958 * just means we are at the exact end of the1959 * previous line, rather than some spot in the1960 * middle.1961 *1962 * Save away what we have to be combined with1963 * the data from the next read.1964 */1965strbuf_splice(&sb,0,0, buf, endp - buf);1966break;1967}1968}19691970}1971if(!ret && sb.len)1972die("BUG: reverse reflog parser had leftover data");19731974fclose(logfp);1975strbuf_release(&sb);1976return ret;1977}19781979static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1980const char*refname,1981 each_reflog_ent_fn fn,void*cb_data)1982{1983struct files_ref_store *refs =1984files_downcast(ref_store, REF_STORE_READ,1985"for_each_reflog_ent");1986FILE*logfp;1987struct strbuf sb = STRBUF_INIT;1988int ret =0;19891990files_reflog_path(refs, &sb, refname);1991 logfp =fopen(sb.buf,"r");1992strbuf_release(&sb);1993if(!logfp)1994return-1;19951996while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1997 ret =show_one_reflog_ent(&sb, fn, cb_data);1998fclose(logfp);1999strbuf_release(&sb);2000return ret;2001}20022003struct files_reflog_iterator {2004struct ref_iterator base;20052006struct ref_store *ref_store;2007struct dir_iterator *dir_iterator;2008struct object_id oid;2009};20102011static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2012{2013struct files_reflog_iterator *iter =2014(struct files_reflog_iterator *)ref_iterator;2015struct dir_iterator *diter = iter->dir_iterator;2016int ok;20172018while((ok =dir_iterator_advance(diter)) == ITER_OK) {2019int flags;20202021if(!S_ISREG(diter->st.st_mode))2022continue;2023if(diter->basename[0] =='.')2024continue;2025if(ends_with(diter->basename,".lock"))2026continue;20272028if(refs_read_ref_full(iter->ref_store,2029 diter->relative_path,0,2030 iter->oid.hash, &flags)) {2031error("bad ref for%s", diter->path.buf);2032continue;2033}20342035 iter->base.refname = diter->relative_path;2036 iter->base.oid = &iter->oid;2037 iter->base.flags = flags;2038return ITER_OK;2039}20402041 iter->dir_iterator = NULL;2042if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2043 ok = ITER_ERROR;2044return ok;2045}20462047static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2048struct object_id *peeled)2049{2050die("BUG: ref_iterator_peel() called for reflog_iterator");2051}20522053static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2054{2055struct files_reflog_iterator *iter =2056(struct files_reflog_iterator *)ref_iterator;2057int ok = ITER_DONE;20582059if(iter->dir_iterator)2060 ok =dir_iterator_abort(iter->dir_iterator);20612062base_ref_iterator_free(ref_iterator);2063return ok;2064}20652066static struct ref_iterator_vtable files_reflog_iterator_vtable = {2067 files_reflog_iterator_advance,2068 files_reflog_iterator_peel,2069 files_reflog_iterator_abort2070};20712072static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2073{2074struct files_ref_store *refs =2075files_downcast(ref_store, REF_STORE_READ,2076"reflog_iterator_begin");2077struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2078struct ref_iterator *ref_iterator = &iter->base;2079struct strbuf sb = STRBUF_INIT;20802081base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2082files_reflog_path(refs, &sb, NULL);2083 iter->dir_iterator =dir_iterator_begin(sb.buf);2084 iter->ref_store = ref_store;2085strbuf_release(&sb);2086return ref_iterator;2087}20882089/*2090 * If update is a direct update of head_ref (the reference pointed to2091 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2092 */2093static intsplit_head_update(struct ref_update *update,2094struct ref_transaction *transaction,2095const char*head_ref,2096struct string_list *affected_refnames,2097struct strbuf *err)2098{2099struct string_list_item *item;2100struct ref_update *new_update;21012102if((update->flags & REF_LOG_ONLY) ||2103(update->flags & REF_ISPRUNING) ||2104(update->flags & REF_UPDATE_VIA_HEAD))2105return0;21062107if(strcmp(update->refname, head_ref))2108return0;21092110/*2111 * First make sure that HEAD is not already in the2112 * transaction. This insertion is O(N) in the transaction2113 * size, but it happens at most once per transaction.2114 */2115 item =string_list_insert(affected_refnames,"HEAD");2116if(item->util) {2117/* An entry already existed */2118strbuf_addf(err,2119"multiple updates for 'HEAD' (including one "2120"via its referent '%s') are not allowed",2121 update->refname);2122return TRANSACTION_NAME_CONFLICT;2123}21242125 new_update =ref_transaction_add_update(2126 transaction,"HEAD",2127 update->flags | REF_LOG_ONLY | REF_NODEREF,2128 update->new_oid.hash, update->old_oid.hash,2129 update->msg);21302131 item->util = new_update;21322133return0;2134}21352136/*2137 * update is for a symref that points at referent and doesn't have2138 * REF_NODEREF set. Split it into two updates:2139 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2140 * - A new, separate update for the referent reference2141 * Note that the new update will itself be subject to splitting when2142 * the iteration gets to it.2143 */2144static intsplit_symref_update(struct files_ref_store *refs,2145struct ref_update *update,2146const char*referent,2147struct ref_transaction *transaction,2148struct string_list *affected_refnames,2149struct strbuf *err)2150{2151struct string_list_item *item;2152struct ref_update *new_update;2153unsigned int new_flags;21542155/*2156 * First make sure that referent is not already in the2157 * transaction. This insertion is O(N) in the transaction2158 * size, but it happens at most once per symref in a2159 * transaction.2160 */2161 item =string_list_insert(affected_refnames, referent);2162if(item->util) {2163/* An entry already existed */2164strbuf_addf(err,2165"multiple updates for '%s' (including one "2166"via symref '%s') are not allowed",2167 referent, update->refname);2168return TRANSACTION_NAME_CONFLICT;2169}21702171 new_flags = update->flags;2172if(!strcmp(update->refname,"HEAD")) {2173/*2174 * Record that the new update came via HEAD, so that2175 * when we process it, split_head_update() doesn't try2176 * to add another reflog update for HEAD. Note that2177 * this bit will be propagated if the new_update2178 * itself needs to be split.2179 */2180 new_flags |= REF_UPDATE_VIA_HEAD;2181}21822183 new_update =ref_transaction_add_update(2184 transaction, referent, new_flags,2185 update->new_oid.hash, update->old_oid.hash,2186 update->msg);21872188 new_update->parent_update = update;21892190/*2191 * Change the symbolic ref update to log only. Also, it2192 * doesn't need to check its old SHA-1 value, as that will be2193 * done when new_update is processed.2194 */2195 update->flags |= REF_LOG_ONLY | REF_NODEREF;2196 update->flags &= ~REF_HAVE_OLD;21972198 item->util = new_update;21992200return0;2201}22022203/*2204 * Return the refname under which update was originally requested.2205 */2206static const char*original_update_refname(struct ref_update *update)2207{2208while(update->parent_update)2209 update = update->parent_update;22102211return update->refname;2212}22132214/*2215 * Check whether the REF_HAVE_OLD and old_oid values stored in update2216 * are consistent with oid, which is the reference's current value. If2217 * everything is OK, return 0; otherwise, write an error message to2218 * err and return -1.2219 */2220static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2221struct strbuf *err)2222{2223if(!(update->flags & REF_HAVE_OLD) ||2224!oidcmp(oid, &update->old_oid))2225return0;22262227if(is_null_oid(&update->old_oid))2228strbuf_addf(err,"cannot lock ref '%s': "2229"reference already exists",2230original_update_refname(update));2231else if(is_null_oid(oid))2232strbuf_addf(err,"cannot lock ref '%s': "2233"reference is missing but expected%s",2234original_update_refname(update),2235oid_to_hex(&update->old_oid));2236else2237strbuf_addf(err,"cannot lock ref '%s': "2238"is at%sbut expected%s",2239original_update_refname(update),2240oid_to_hex(oid),2241oid_to_hex(&update->old_oid));22422243return-1;2244}22452246/*2247 * Prepare for carrying out update:2248 * - Lock the reference referred to by update.2249 * - Read the reference under lock.2250 * - Check that its old SHA-1 value (if specified) is correct, and in2251 * any case record it in update->lock->old_oid for later use when2252 * writing the reflog.2253 * - If it is a symref update without REF_NODEREF, split it up into a2254 * REF_LOG_ONLY update of the symref and add a separate update for2255 * the referent to transaction.2256 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2257 * update of HEAD.2258 */2259static intlock_ref_for_update(struct files_ref_store *refs,2260struct ref_update *update,2261struct ref_transaction *transaction,2262const char*head_ref,2263struct string_list *affected_refnames,2264struct strbuf *err)2265{2266struct strbuf referent = STRBUF_INIT;2267int mustexist = (update->flags & REF_HAVE_OLD) &&2268!is_null_oid(&update->old_oid);2269int ret;2270struct ref_lock *lock;22712272files_assert_main_repository(refs,"lock_ref_for_update");22732274if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2275 update->flags |= REF_DELETING;22762277if(head_ref) {2278 ret =split_head_update(update, transaction, head_ref,2279 affected_refnames, err);2280if(ret)2281return ret;2282}22832284 ret =lock_raw_ref(refs, update->refname, mustexist,2285 affected_refnames, NULL,2286&lock, &referent,2287&update->type, err);2288if(ret) {2289char*reason;22902291 reason =strbuf_detach(err, NULL);2292strbuf_addf(err,"cannot lock ref '%s':%s",2293original_update_refname(update), reason);2294free(reason);2295return ret;2296}22972298 update->backend_data = lock;22992300if(update->type & REF_ISSYMREF) {2301if(update->flags & REF_NODEREF) {2302/*2303 * We won't be reading the referent as part of2304 * the transaction, so we have to read it here2305 * to record and possibly check old_sha1:2306 */2307if(refs_read_ref_full(&refs->base,2308 referent.buf,0,2309 lock->old_oid.hash, NULL)) {2310if(update->flags & REF_HAVE_OLD) {2311strbuf_addf(err,"cannot lock ref '%s': "2312"error reading reference",2313original_update_refname(update));2314return-1;2315}2316}else if(check_old_oid(update, &lock->old_oid, err)) {2317return TRANSACTION_GENERIC_ERROR;2318}2319}else{2320/*2321 * Create a new update for the reference this2322 * symref is pointing at. Also, we will record2323 * and verify old_sha1 for this update as part2324 * of processing the split-off update, so we2325 * don't have to do it here.2326 */2327 ret =split_symref_update(refs, update,2328 referent.buf, transaction,2329 affected_refnames, err);2330if(ret)2331return ret;2332}2333}else{2334struct ref_update *parent_update;23352336if(check_old_oid(update, &lock->old_oid, err))2337return TRANSACTION_GENERIC_ERROR;23382339/*2340 * If this update is happening indirectly because of a2341 * symref update, record the old SHA-1 in the parent2342 * update:2343 */2344for(parent_update = update->parent_update;2345 parent_update;2346 parent_update = parent_update->parent_update) {2347struct ref_lock *parent_lock = parent_update->backend_data;2348oidcpy(&parent_lock->old_oid, &lock->old_oid);2349}2350}23512352if((update->flags & REF_HAVE_NEW) &&2353!(update->flags & REF_DELETING) &&2354!(update->flags & REF_LOG_ONLY)) {2355if(!(update->type & REF_ISSYMREF) &&2356!oidcmp(&lock->old_oid, &update->new_oid)) {2357/*2358 * The reference already has the desired2359 * value, so we don't need to write it.2360 */2361}else if(write_ref_to_lockfile(lock, &update->new_oid,2362 err)) {2363char*write_err =strbuf_detach(err, NULL);23642365/*2366 * The lock was freed upon failure of2367 * write_ref_to_lockfile():2368 */2369 update->backend_data = NULL;2370strbuf_addf(err,2371"cannot update ref '%s':%s",2372 update->refname, write_err);2373free(write_err);2374return TRANSACTION_GENERIC_ERROR;2375}else{2376 update->flags |= REF_NEEDS_COMMIT;2377}2378}2379if(!(update->flags & REF_NEEDS_COMMIT)) {2380/*2381 * We didn't call write_ref_to_lockfile(), so2382 * the lockfile is still open. Close it to2383 * free up the file descriptor:2384 */2385if(close_ref(lock)) {2386strbuf_addf(err,"couldn't close '%s.lock'",2387 update->refname);2388return TRANSACTION_GENERIC_ERROR;2389}2390}2391return0;2392}23932394/*2395 * Unlock any references in `transaction` that are still locked, and2396 * mark the transaction closed.2397 */2398static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2399{2400size_t i;24012402for(i =0; i < transaction->nr; i++) {2403struct ref_update *update = transaction->updates[i];2404struct ref_lock *lock = update->backend_data;24052406if(lock) {2407unlock_ref(lock);2408 update->backend_data = NULL;2409}2410}24112412 transaction->state = REF_TRANSACTION_CLOSED;2413}24142415static intfiles_transaction_prepare(struct ref_store *ref_store,2416struct ref_transaction *transaction,2417struct strbuf *err)2418{2419struct files_ref_store *refs =2420files_downcast(ref_store, REF_STORE_WRITE,2421"ref_transaction_prepare");2422size_t i;2423int ret =0;2424struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2425char*head_ref = NULL;2426int head_type;2427struct object_id head_oid;24282429assert(err);24302431if(!transaction->nr)2432goto cleanup;24332434/*2435 * Fail if a refname appears more than once in the2436 * transaction. (If we end up splitting up any updates using2437 * split_symref_update() or split_head_update(), those2438 * functions will check that the new updates don't have the2439 * same refname as any existing ones.)2440 */2441for(i =0; i < transaction->nr; i++) {2442struct ref_update *update = transaction->updates[i];2443struct string_list_item *item =2444string_list_append(&affected_refnames, update->refname);24452446/*2447 * We store a pointer to update in item->util, but at2448 * the moment we never use the value of this field2449 * except to check whether it is non-NULL.2450 */2451 item->util = update;2452}2453string_list_sort(&affected_refnames);2454if(ref_update_reject_duplicates(&affected_refnames, err)) {2455 ret = TRANSACTION_GENERIC_ERROR;2456goto cleanup;2457}24582459/*2460 * Special hack: If a branch is updated directly and HEAD2461 * points to it (may happen on the remote side of a push2462 * for example) then logically the HEAD reflog should be2463 * updated too.2464 *2465 * A generic solution would require reverse symref lookups,2466 * but finding all symrefs pointing to a given branch would be2467 * rather costly for this rare event (the direct update of a2468 * branch) to be worth it. So let's cheat and check with HEAD2469 * only, which should cover 99% of all usage scenarios (even2470 * 100% of the default ones).2471 *2472 * So if HEAD is a symbolic reference, then record the name of2473 * the reference that it points to. If we see an update of2474 * head_ref within the transaction, then split_head_update()2475 * arranges for the reflog of HEAD to be updated, too.2476 */2477 head_ref =refs_resolve_refdup(ref_store,"HEAD",2478 RESOLVE_REF_NO_RECURSE,2479 head_oid.hash, &head_type);24802481if(head_ref && !(head_type & REF_ISSYMREF)) {2482FREE_AND_NULL(head_ref);2483}24842485/*2486 * Acquire all locks, verify old values if provided, check2487 * that new values are valid, and write new values to the2488 * lockfiles, ready to be activated. Only keep one lockfile2489 * open at a time to avoid running out of file descriptors.2490 * Note that lock_ref_for_update() might append more updates2491 * to the transaction.2492 */2493for(i =0; i < transaction->nr; i++) {2494struct ref_update *update = transaction->updates[i];24952496 ret =lock_ref_for_update(refs, update, transaction,2497 head_ref, &affected_refnames, err);2498if(ret)2499break;2500}25012502cleanup:2503free(head_ref);2504string_list_clear(&affected_refnames,0);25052506if(ret)2507files_transaction_cleanup(transaction);2508else2509 transaction->state = REF_TRANSACTION_PREPARED;25102511return ret;2512}25132514static intfiles_transaction_finish(struct ref_store *ref_store,2515struct ref_transaction *transaction,2516struct strbuf *err)2517{2518struct files_ref_store *refs =2519files_downcast(ref_store,0,"ref_transaction_finish");2520size_t i;2521int ret =0;2522struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2523struct string_list_item *ref_to_delete;2524struct strbuf sb = STRBUF_INIT;25252526assert(err);25272528if(!transaction->nr) {2529 transaction->state = REF_TRANSACTION_CLOSED;2530return0;2531}25322533/* Perform updates first so live commits remain referenced */2534for(i =0; i < transaction->nr; i++) {2535struct ref_update *update = transaction->updates[i];2536struct ref_lock *lock = update->backend_data;25372538if(update->flags & REF_NEEDS_COMMIT ||2539 update->flags & REF_LOG_ONLY) {2540if(files_log_ref_write(refs,2541 lock->ref_name,2542&lock->old_oid,2543&update->new_oid,2544 update->msg, update->flags,2545 err)) {2546char*old_msg =strbuf_detach(err, NULL);25472548strbuf_addf(err,"cannot update the ref '%s':%s",2549 lock->ref_name, old_msg);2550free(old_msg);2551unlock_ref(lock);2552 update->backend_data = NULL;2553 ret = TRANSACTION_GENERIC_ERROR;2554goto cleanup;2555}2556}2557if(update->flags & REF_NEEDS_COMMIT) {2558clear_loose_ref_cache(refs);2559if(commit_ref(lock)) {2560strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2561unlock_ref(lock);2562 update->backend_data = NULL;2563 ret = TRANSACTION_GENERIC_ERROR;2564goto cleanup;2565}2566}2567}2568/* Perform deletes now that updates are safely completed */2569for(i =0; i < transaction->nr; i++) {2570struct ref_update *update = transaction->updates[i];2571struct ref_lock *lock = update->backend_data;25722573if(update->flags & REF_DELETING &&2574!(update->flags & REF_LOG_ONLY)) {2575if(!(update->type & REF_ISPACKED) ||2576 update->type & REF_ISSYMREF) {2577/* It is a loose reference. */2578strbuf_reset(&sb);2579files_ref_path(refs, &sb, lock->ref_name);2580if(unlink_or_msg(sb.buf, err)) {2581 ret = TRANSACTION_GENERIC_ERROR;2582goto cleanup;2583}2584 update->flags |= REF_DELETED_LOOSE;2585}25862587if(!(update->flags & REF_ISPRUNING))2588string_list_append(&refs_to_delete,2589 lock->ref_name);2590}2591}25922593if(packed_refs_lock(refs->packed_ref_store,0, err)) {2594 ret = TRANSACTION_GENERIC_ERROR;2595goto cleanup;2596}25972598if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2599 ret = TRANSACTION_GENERIC_ERROR;2600packed_refs_unlock(refs->packed_ref_store);2601goto cleanup;2602}26032604packed_refs_unlock(refs->packed_ref_store);26052606/* Delete the reflogs of any references that were deleted: */2607for_each_string_list_item(ref_to_delete, &refs_to_delete) {2608strbuf_reset(&sb);2609files_reflog_path(refs, &sb, ref_to_delete->string);2610if(!unlink_or_warn(sb.buf))2611try_remove_empty_parents(refs, ref_to_delete->string,2612 REMOVE_EMPTY_PARENTS_REFLOG);2613}26142615clear_loose_ref_cache(refs);26162617cleanup:2618files_transaction_cleanup(transaction);26192620for(i =0; i < transaction->nr; i++) {2621struct ref_update *update = transaction->updates[i];26222623if(update->flags & REF_DELETED_LOOSE) {2624/*2625 * The loose reference was deleted. Delete any2626 * empty parent directories. (Note that this2627 * can only work because we have already2628 * removed the lockfile.)2629 */2630try_remove_empty_parents(refs, update->refname,2631 REMOVE_EMPTY_PARENTS_REF);2632}2633}26342635strbuf_release(&sb);2636string_list_clear(&refs_to_delete,0);2637return ret;2638}26392640static intfiles_transaction_abort(struct ref_store *ref_store,2641struct ref_transaction *transaction,2642struct strbuf *err)2643{2644files_transaction_cleanup(transaction);2645return0;2646}26472648static intref_present(const char*refname,2649const struct object_id *oid,int flags,void*cb_data)2650{2651struct string_list *affected_refnames = cb_data;26522653returnstring_list_has_string(affected_refnames, refname);2654}26552656static intfiles_initial_transaction_commit(struct ref_store *ref_store,2657struct ref_transaction *transaction,2658struct strbuf *err)2659{2660struct files_ref_store *refs =2661files_downcast(ref_store, REF_STORE_WRITE,2662"initial_ref_transaction_commit");2663size_t i;2664int ret =0;2665struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26662667assert(err);26682669if(transaction->state != REF_TRANSACTION_OPEN)2670die("BUG: commit called for transaction that is not open");26712672/* Fail if a refname appears more than once in the transaction: */2673for(i =0; i < transaction->nr; i++)2674string_list_append(&affected_refnames,2675 transaction->updates[i]->refname);2676string_list_sort(&affected_refnames);2677if(ref_update_reject_duplicates(&affected_refnames, err)) {2678 ret = TRANSACTION_GENERIC_ERROR;2679goto cleanup;2680}26812682/*2683 * It's really undefined to call this function in an active2684 * repository or when there are existing references: we are2685 * only locking and changing packed-refs, so (1) any2686 * simultaneous processes might try to change a reference at2687 * the same time we do, and (2) any existing loose versions of2688 * the references that we are setting would have precedence2689 * over our values. But some remote helpers create the remote2690 * "HEAD" and "master" branches before calling this function,2691 * so here we really only check that none of the references2692 * that we are creating already exists.2693 */2694if(refs_for_each_rawref(&refs->base, ref_present,2695&affected_refnames))2696die("BUG: initial ref transaction called with existing refs");26972698for(i =0; i < transaction->nr; i++) {2699struct ref_update *update = transaction->updates[i];27002701if((update->flags & REF_HAVE_OLD) &&2702!is_null_oid(&update->old_oid))2703die("BUG: initial ref transaction with old_sha1 set");2704if(refs_verify_refname_available(&refs->base, update->refname,2705&affected_refnames, NULL,2706 err)) {2707 ret = TRANSACTION_NAME_CONFLICT;2708goto cleanup;2709}2710}27112712if(packed_refs_lock(refs->packed_ref_store,0, err)) {2713 ret = TRANSACTION_GENERIC_ERROR;2714goto cleanup;2715}27162717for(i =0; i < transaction->nr; i++) {2718struct ref_update *update = transaction->updates[i];27192720if((update->flags & REF_HAVE_NEW) &&2721!is_null_oid(&update->new_oid))2722add_packed_ref(refs->packed_ref_store, update->refname,2723&update->new_oid);2724}27252726if(commit_packed_refs(refs->packed_ref_store, err)) {2727 ret = TRANSACTION_GENERIC_ERROR;2728goto cleanup;2729}27302731cleanup:2732packed_refs_unlock(refs->packed_ref_store);2733 transaction->state = REF_TRANSACTION_CLOSED;2734string_list_clear(&affected_refnames,0);2735return ret;2736}27372738struct expire_reflog_cb {2739unsigned int flags;2740 reflog_expiry_should_prune_fn *should_prune_fn;2741void*policy_cb;2742FILE*newlog;2743struct object_id last_kept_oid;2744};27452746static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2747const char*email, timestamp_t timestamp,int tz,2748const char*message,void*cb_data)2749{2750struct expire_reflog_cb *cb = cb_data;2751struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27522753if(cb->flags & EXPIRE_REFLOGS_REWRITE)2754 ooid = &cb->last_kept_oid;27552756if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2757 message, policy_cb)) {2758if(!cb->newlog)2759printf("would prune%s", message);2760else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2761printf("prune%s", message);2762}else{2763if(cb->newlog) {2764fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2765oid_to_hex(ooid),oid_to_hex(noid),2766 email, timestamp, tz, message);2767oidcpy(&cb->last_kept_oid, noid);2768}2769if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2770printf("keep%s", message);2771}2772return0;2773}27742775static intfiles_reflog_expire(struct ref_store *ref_store,2776const char*refname,const unsigned char*sha1,2777unsigned int flags,2778 reflog_expiry_prepare_fn prepare_fn,2779 reflog_expiry_should_prune_fn should_prune_fn,2780 reflog_expiry_cleanup_fn cleanup_fn,2781void*policy_cb_data)2782{2783struct files_ref_store *refs =2784files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2785static struct lock_file reflog_lock;2786struct expire_reflog_cb cb;2787struct ref_lock *lock;2788struct strbuf log_file_sb = STRBUF_INIT;2789char*log_file;2790int status =0;2791int type;2792struct strbuf err = STRBUF_INIT;2793struct object_id oid;27942795memset(&cb,0,sizeof(cb));2796 cb.flags = flags;2797 cb.policy_cb = policy_cb_data;2798 cb.should_prune_fn = should_prune_fn;27992800/*2801 * The reflog file is locked by holding the lock on the2802 * reference itself, plus we might need to update the2803 * reference if --updateref was specified:2804 */2805 lock =lock_ref_sha1_basic(refs, refname, sha1,2806 NULL, NULL, REF_NODEREF,2807&type, &err);2808if(!lock) {2809error("cannot lock ref '%s':%s", refname, err.buf);2810strbuf_release(&err);2811return-1;2812}2813if(!refs_reflog_exists(ref_store, refname)) {2814unlock_ref(lock);2815return0;2816}28172818files_reflog_path(refs, &log_file_sb, refname);2819 log_file =strbuf_detach(&log_file_sb, NULL);2820if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2821/*2822 * Even though holding $GIT_DIR/logs/$reflog.lock has2823 * no locking implications, we use the lock_file2824 * machinery here anyway because it does a lot of the2825 * work we need, including cleaning up if the program2826 * exits unexpectedly.2827 */2828if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2829struct strbuf err = STRBUF_INIT;2830unable_to_lock_message(log_file, errno, &err);2831error("%s", err.buf);2832strbuf_release(&err);2833goto failure;2834}2835 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2836if(!cb.newlog) {2837error("cannot fdopen%s(%s)",2838get_lock_file_path(&reflog_lock),strerror(errno));2839goto failure;2840}2841}28422843hashcpy(oid.hash, sha1);28442845(*prepare_fn)(refname, &oid, cb.policy_cb);2846refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2847(*cleanup_fn)(cb.policy_cb);28482849if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2850/*2851 * It doesn't make sense to adjust a reference pointed2852 * to by a symbolic ref based on expiring entries in2853 * the symbolic reference's reflog. Nor can we update2854 * a reference if there are no remaining reflog2855 * entries.2856 */2857int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2858!(type & REF_ISSYMREF) &&2859!is_null_oid(&cb.last_kept_oid);28602861if(close_lock_file(&reflog_lock)) {2862 status |=error("couldn't write%s:%s", log_file,2863strerror(errno));2864}else if(update &&2865(write_in_full(get_lock_file_fd(lock->lk),2866oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2867write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2868close_ref(lock) <0)) {2869 status |=error("couldn't write%s",2870get_lock_file_path(lock->lk));2871rollback_lock_file(&reflog_lock);2872}else if(commit_lock_file(&reflog_lock)) {2873 status |=error("unable to write reflog '%s' (%s)",2874 log_file,strerror(errno));2875}else if(update &&commit_ref(lock)) {2876 status |=error("couldn't set%s", lock->ref_name);2877}2878}2879free(log_file);2880unlock_ref(lock);2881return status;28822883 failure:2884rollback_lock_file(&reflog_lock);2885free(log_file);2886unlock_ref(lock);2887return-1;2888}28892890static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2891{2892struct files_ref_store *refs =2893files_downcast(ref_store, REF_STORE_WRITE,"init_db");2894struct strbuf sb = STRBUF_INIT;28952896/*2897 * Create .git/refs/{heads,tags}2898 */2899files_ref_path(refs, &sb,"refs/heads");2900safe_create_dir(sb.buf,1);29012902strbuf_reset(&sb);2903files_ref_path(refs, &sb,"refs/tags");2904safe_create_dir(sb.buf,1);29052906strbuf_release(&sb);2907return0;2908}29092910struct ref_storage_be refs_be_files = {2911 NULL,2912"files",2913 files_ref_store_create,2914 files_init_db,2915 files_transaction_prepare,2916 files_transaction_finish,2917 files_transaction_abort,2918 files_initial_transaction_commit,29192920 files_pack_refs,2921 files_peel_ref,2922 files_create_symref,2923 files_delete_refs,2924 files_rename_ref,29252926 files_ref_iterator_begin,2927 files_read_raw_ref,29282929 files_reflog_iterator_begin,2930 files_for_each_reflog_ent,2931 files_for_each_reflog_ent_reverse,2932 files_reflog_exists,2933 files_create_reflog,2934 files_delete_reflog,2935 files_reflog_expire2936};