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#include "../chdir-notify.h" 13#include "worktree.h" 14 15/* 16 * This backend uses the following flags in `ref_update::flags` for 17 * internal bookkeeping purposes. Their numerical values must not 18 * conflict with REF_NO_DEREF, REF_FORCE_CREATE_REFLOG, REF_HAVE_NEW, 19 * REF_HAVE_OLD, or REF_IS_PRUNING, which are also stored in 20 * `ref_update::flags`. 21 */ 22 23/* 24 * Used as a flag in ref_update::flags when a loose ref is being 25 * pruned. This flag must only be used when REF_NO_DEREF is set. 26 */ 27#define REF_IS_PRUNING (1 << 4) 28 29/* 30 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 31 * refs (i.e., because the reference is about to be deleted anyway). 32 */ 33#define REF_DELETING (1 << 5) 34 35/* 36 * Used as a flag in ref_update::flags when the lockfile needs to be 37 * committed. 38 */ 39#define REF_NEEDS_COMMIT (1 << 6) 40 41/* 42 * Used as a flag in ref_update::flags when we want to log a ref 43 * update but not actually perform it. This is used when a symbolic 44 * ref update is split up. 45 */ 46#define REF_LOG_ONLY (1 << 7) 47 48/* 49 * Used as a flag in ref_update::flags when the ref_update was via an 50 * update to HEAD. 51 */ 52#define REF_UPDATE_VIA_HEAD (1 << 8) 53 54/* 55 * Used as a flag in ref_update::flags when the loose reference has 56 * been deleted. 57 */ 58#define REF_DELETED_LOOSE (1 << 9) 59 60struct ref_lock { 61 char *ref_name; 62 struct lock_file lk; 63 struct object_id old_oid; 64}; 65 66struct files_ref_store { 67 struct ref_store base; 68 unsigned int store_flags; 69 70 char *gitdir; 71 char *gitcommondir; 72 73 struct ref_cache *loose; 74 75 struct ref_store *packed_ref_store; 76}; 77 78static void clear_loose_ref_cache(struct files_ref_store *refs) 79{ 80 if (refs->loose) { 81 free_ref_cache(refs->loose); 82 refs->loose = NULL; 83 } 84} 85 86/* 87 * Create a new submodule ref cache and add it to the internal 88 * set of caches. 89 */ 90static struct ref_store *files_ref_store_create(const char *gitdir, 91 unsigned int flags) 92{ 93 struct files_ref_store *refs = xcalloc(1, sizeof(*refs)); 94 struct ref_store *ref_store = (struct ref_store *)refs; 95 struct strbuf sb = STRBUF_INIT; 96 97 base_ref_store_init(ref_store, &refs_be_files); 98 refs->store_flags = flags; 99 100 refs->gitdir = xstrdup(gitdir); 101 get_common_dir_noenv(&sb, gitdir); 102 refs->gitcommondir = strbuf_detach(&sb, NULL); 103 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir); 104 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags); 105 strbuf_release(&sb); 106 107 chdir_notify_reparent("files-backend $GIT_DIR", 108 &refs->gitdir); 109 chdir_notify_reparent("files-backend $GIT_COMMONDIR", 110 &refs->gitcommondir); 111 112 return ref_store; 113} 114 115/* 116 * Die if refs is not the main ref store. caller is used in any 117 * necessary error messages. 118 */ 119static void files_assert_main_repository(struct files_ref_store *refs, 120 const char *caller) 121{ 122 if (refs->store_flags & REF_STORE_MAIN) 123 return; 124 125 BUG("operation %s only allowed for main ref store", caller); 126} 127 128/* 129 * Downcast ref_store to files_ref_store. Die if ref_store is not a 130 * files_ref_store. required_flags is compared with ref_store's 131 * store_flags to ensure the ref_store has all required capabilities. 132 * "caller" is used in any necessary error messages. 133 */ 134static struct files_ref_store *files_downcast(struct ref_store *ref_store, 135 unsigned int required_flags, 136 const char *caller) 137{ 138 struct files_ref_store *refs; 139 140 if (ref_store->be != &refs_be_files) 141 BUG("ref_store is type \"%s\" not \"files\" in %s", 142 ref_store->be->name, caller); 143 144 refs = (struct files_ref_store *)ref_store; 145 146 if ((refs->store_flags & required_flags) != required_flags) 147 BUG("operation %s requires abilities 0x%x, but only have 0x%x", 148 caller, required_flags, refs->store_flags); 149 150 return refs; 151} 152 153static void files_reflog_path_other_worktrees(struct files_ref_store *refs, 154 struct strbuf *sb, 155 const char *refname) 156{ 157 const char *real_ref; 158 const char *worktree_name; 159 int length; 160 161 if (parse_worktree_ref(refname, &worktree_name, &length, &real_ref)) 162 BUG("refname %s is not a other-worktree ref", refname); 163 164 if (worktree_name) 165 strbuf_addf(sb, "%s/worktrees/%.*s/logs/%s", refs->gitcommondir, 166 length, worktree_name, real_ref); 167 else 168 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, 169 real_ref); 170} 171 172static void files_reflog_path(struct files_ref_store *refs, 173 struct strbuf *sb, 174 const char *refname) 175{ 176 switch (ref_type(refname)) { 177 case REF_TYPE_PER_WORKTREE: 178 case REF_TYPE_PSEUDOREF: 179 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname); 180 break; 181 case REF_TYPE_OTHER_PSEUDOREF: 182 case REF_TYPE_MAIN_PSEUDOREF: 183 files_reflog_path_other_worktrees(refs, sb, refname); 184 break; 185 case REF_TYPE_NORMAL: 186 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname); 187 break; 188 default: 189 BUG("unknown ref type %d of ref %s", 190 ref_type(refname), refname); 191 } 192} 193 194static void files_ref_path(struct files_ref_store *refs, 195 struct strbuf *sb, 196 const char *refname) 197{ 198 switch (ref_type(refname)) { 199 case REF_TYPE_PER_WORKTREE: 200 case REF_TYPE_PSEUDOREF: 201 strbuf_addf(sb, "%s/%s", refs->gitdir, refname); 202 break; 203 case REF_TYPE_MAIN_PSEUDOREF: 204 if (!skip_prefix(refname, "main-worktree/", &refname)) 205 BUG("ref %s is not a main pseudoref", refname); 206 /* fallthrough */ 207 case REF_TYPE_OTHER_PSEUDOREF: 208 case REF_TYPE_NORMAL: 209 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname); 210 break; 211 default: 212 BUG("unknown ref type %d of ref %s", 213 ref_type(refname), refname); 214 } 215} 216 217/* 218 * Read the loose references from the namespace dirname into dir 219 * (without recursing). dirname must end with '/'. dir must be the 220 * directory entry corresponding to dirname. 221 */ 222static void loose_fill_ref_dir(struct ref_store *ref_store, 223 struct ref_dir *dir, const char *dirname) 224{ 225 struct files_ref_store *refs = 226 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir"); 227 DIR *d; 228 struct dirent *de; 229 int dirnamelen = strlen(dirname); 230 struct strbuf refname; 231 struct strbuf path = STRBUF_INIT; 232 size_t path_baselen; 233 234 files_ref_path(refs, &path, dirname); 235 path_baselen = path.len; 236 237 d = opendir(path.buf); 238 if (!d) { 239 strbuf_release(&path); 240 return; 241 } 242 243 strbuf_init(&refname, dirnamelen + 257); 244 strbuf_add(&refname, dirname, dirnamelen); 245 246 while ((de = readdir(d)) != NULL) { 247 struct object_id oid; 248 struct stat st; 249 int flag; 250 251 if (de->d_name[0] == '.') 252 continue; 253 if (ends_with(de->d_name, ".lock")) 254 continue; 255 strbuf_addstr(&refname, de->d_name); 256 strbuf_addstr(&path, de->d_name); 257 if (stat(path.buf, &st) < 0) { 258 ; /* silently ignore */ 259 } else if (S_ISDIR(st.st_mode)) { 260 strbuf_addch(&refname, '/'); 261 add_entry_to_dir(dir, 262 create_dir_entry(dir->cache, refname.buf, 263 refname.len, 1)); 264 } else { 265 if (!refs_resolve_ref_unsafe(&refs->base, 266 refname.buf, 267 RESOLVE_REF_READING, 268 &oid, &flag)) { 269 oidclr(&oid); 270 flag |= REF_ISBROKEN; 271 } else if (is_null_oid(&oid)) { 272 /* 273 * It is so astronomically unlikely 274 * that null_oid is the OID of an 275 * actual object that we consider its 276 * appearance in a loose reference 277 * file to be repo corruption 278 * (probably due to a software bug). 279 */ 280 flag |= REF_ISBROKEN; 281 } 282 283 if (check_refname_format(refname.buf, 284 REFNAME_ALLOW_ONELEVEL)) { 285 if (!refname_is_safe(refname.buf)) 286 die("loose refname is dangerous: %s", refname.buf); 287 oidclr(&oid); 288 flag |= REF_BAD_NAME | REF_ISBROKEN; 289 } 290 add_entry_to_dir(dir, 291 create_ref_entry(refname.buf, &oid, flag)); 292 } 293 strbuf_setlen(&refname, dirnamelen); 294 strbuf_setlen(&path, path_baselen); 295 } 296 strbuf_release(&refname); 297 strbuf_release(&path); 298 closedir(d); 299 300 /* 301 * Manually add refs/bisect and refs/worktree, which, being 302 * per-worktree, might not appear in the directory listing for 303 * refs/ in the main repo. 304 */ 305 if (!strcmp(dirname, "refs/")) { 306 int pos = search_ref_dir(dir, "refs/bisect/", 12); 307 308 if (pos < 0) { 309 struct ref_entry *child_entry = create_dir_entry( 310 dir->cache, "refs/bisect/", 12, 1); 311 add_entry_to_dir(dir, child_entry); 312 } 313 314 pos = search_ref_dir(dir, "refs/worktree/", 11); 315 316 if (pos < 0) { 317 struct ref_entry *child_entry = create_dir_entry( 318 dir->cache, "refs/worktree/", 11, 1); 319 add_entry_to_dir(dir, child_entry); 320 } 321 } 322} 323 324static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 325{ 326 if (!refs->loose) { 327 /* 328 * Mark the top-level directory complete because we 329 * are about to read the only subdirectory that can 330 * hold references: 331 */ 332 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir); 333 334 /* We're going to fill the top level ourselves: */ 335 refs->loose->root->flag &= ~REF_INCOMPLETE; 336 337 /* 338 * Add an incomplete entry for "refs/" (to be filled 339 * lazily): 340 */ 341 add_entry_to_dir(get_ref_dir(refs->loose->root), 342 create_dir_entry(refs->loose, "refs/", 5, 1)); 343 } 344 return refs->loose; 345} 346 347static int files_read_raw_ref(struct ref_store *ref_store, 348 const char *refname, struct object_id *oid, 349 struct strbuf *referent, unsigned int *type) 350{ 351 struct files_ref_store *refs = 352 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref"); 353 struct strbuf sb_contents = STRBUF_INIT; 354 struct strbuf sb_path = STRBUF_INIT; 355 const char *path; 356 const char *buf; 357 const char *p; 358 struct stat st; 359 int fd; 360 int ret = -1; 361 int save_errno; 362 int remaining_retries = 3; 363 364 *type = 0; 365 strbuf_reset(&sb_path); 366 367 files_ref_path(refs, &sb_path, refname); 368 369 path = sb_path.buf; 370 371stat_ref: 372 /* 373 * We might have to loop back here to avoid a race 374 * condition: first we lstat() the file, then we try 375 * to read it as a link or as a file. But if somebody 376 * changes the type of the file (file <-> directory 377 * <-> symlink) between the lstat() and reading, then 378 * we don't want to report that as an error but rather 379 * try again starting with the lstat(). 380 * 381 * We'll keep a count of the retries, though, just to avoid 382 * any confusing situation sending us into an infinite loop. 383 */ 384 385 if (remaining_retries-- <= 0) 386 goto out; 387 388 if (lstat(path, &st) < 0) { 389 if (errno != ENOENT) 390 goto out; 391 if (refs_read_raw_ref(refs->packed_ref_store, refname, 392 oid, referent, type)) { 393 errno = ENOENT; 394 goto out; 395 } 396 ret = 0; 397 goto out; 398 } 399 400 /* Follow "normalized" - ie "refs/.." symlinks by hand */ 401 if (S_ISLNK(st.st_mode)) { 402 strbuf_reset(&sb_contents); 403 if (strbuf_readlink(&sb_contents, path, st.st_size) < 0) { 404 if (errno == ENOENT || errno == EINVAL) 405 /* inconsistent with lstat; retry */ 406 goto stat_ref; 407 else 408 goto out; 409 } 410 if (starts_with(sb_contents.buf, "refs/") && 411 !check_refname_format(sb_contents.buf, 0)) { 412 strbuf_swap(&sb_contents, referent); 413 *type |= REF_ISSYMREF; 414 ret = 0; 415 goto out; 416 } 417 /* 418 * It doesn't look like a refname; fall through to just 419 * treating it like a non-symlink, and reading whatever it 420 * points to. 421 */ 422 } 423 424 /* Is it a directory? */ 425 if (S_ISDIR(st.st_mode)) { 426 /* 427 * Even though there is a directory where the loose 428 * ref is supposed to be, there could still be a 429 * packed ref: 430 */ 431 if (refs_read_raw_ref(refs->packed_ref_store, refname, 432 oid, referent, type)) { 433 errno = EISDIR; 434 goto out; 435 } 436 ret = 0; 437 goto out; 438 } 439 440 /* 441 * Anything else, just open it and try to use it as 442 * a ref 443 */ 444 fd = open(path, O_RDONLY); 445 if (fd < 0) { 446 if (errno == ENOENT && !S_ISLNK(st.st_mode)) 447 /* inconsistent with lstat; retry */ 448 goto stat_ref; 449 else 450 goto out; 451 } 452 strbuf_reset(&sb_contents); 453 if (strbuf_read(&sb_contents, fd, 256) < 0) { 454 int save_errno = errno; 455 close(fd); 456 errno = save_errno; 457 goto out; 458 } 459 close(fd); 460 strbuf_rtrim(&sb_contents); 461 buf = sb_contents.buf; 462 if (starts_with(buf, "ref:")) { 463 buf += 4; 464 while (isspace(*buf)) 465 buf++; 466 467 strbuf_reset(referent); 468 strbuf_addstr(referent, buf); 469 *type |= REF_ISSYMREF; 470 ret = 0; 471 goto out; 472 } 473 474 /* 475 * Please note that FETCH_HEAD has additional 476 * data after the sha. 477 */ 478 if (parse_oid_hex(buf, oid, &p) || 479 (*p != '\0' && !isspace(*p))) { 480 *type |= REF_ISBROKEN; 481 errno = EINVAL; 482 goto out; 483 } 484 485 ret = 0; 486 487out: 488 save_errno = errno; 489 strbuf_release(&sb_path); 490 strbuf_release(&sb_contents); 491 errno = save_errno; 492 return ret; 493} 494 495static void unlock_ref(struct ref_lock *lock) 496{ 497 rollback_lock_file(&lock->lk); 498 free(lock->ref_name); 499 free(lock); 500} 501 502/* 503 * Lock refname, without following symrefs, and set *lock_p to point 504 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 505 * and type similarly to read_raw_ref(). 506 * 507 * The caller must verify that refname is a "safe" reference name (in 508 * the sense of refname_is_safe()) before calling this function. 509 * 510 * If the reference doesn't already exist, verify that refname doesn't 511 * have a D/F conflict with any existing references. extras and skip 512 * are passed to refs_verify_refname_available() for this check. 513 * 514 * If mustexist is not set and the reference is not found or is 515 * broken, lock the reference anyway but clear old_oid. 516 * 517 * Return 0 on success. On failure, write an error message to err and 518 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 519 * 520 * Implementation note: This function is basically 521 * 522 * lock reference 523 * read_raw_ref() 524 * 525 * but it includes a lot more code to 526 * - Deal with possible races with other processes 527 * - Avoid calling refs_verify_refname_available() when it can be 528 * avoided, namely if we were successfully able to read the ref 529 * - Generate informative error messages in the case of failure 530 */ 531static int lock_raw_ref(struct files_ref_store *refs, 532 const char *refname, int mustexist, 533 const struct string_list *extras, 534 const struct string_list *skip, 535 struct ref_lock **lock_p, 536 struct strbuf *referent, 537 unsigned int *type, 538 struct strbuf *err) 539{ 540 struct ref_lock *lock; 541 struct strbuf ref_file = STRBUF_INIT; 542 int attempts_remaining = 3; 543 int ret = TRANSACTION_GENERIC_ERROR; 544 545 assert(err); 546 files_assert_main_repository(refs, "lock_raw_ref"); 547 548 *type = 0; 549 550 /* First lock the file so it can't change out from under us. */ 551 552 *lock_p = lock = xcalloc(1, sizeof(*lock)); 553 554 lock->ref_name = xstrdup(refname); 555 files_ref_path(refs, &ref_file, refname); 556 557retry: 558 switch (safe_create_leading_directories(ref_file.buf)) { 559 case SCLD_OK: 560 break; /* success */ 561 case SCLD_EXISTS: 562 /* 563 * Suppose refname is "refs/foo/bar". We just failed 564 * to create the containing directory, "refs/foo", 565 * because there was a non-directory in the way. This 566 * indicates a D/F conflict, probably because of 567 * another reference such as "refs/foo". There is no 568 * reason to expect this error to be transitory. 569 */ 570 if (refs_verify_refname_available(&refs->base, refname, 571 extras, skip, err)) { 572 if (mustexist) { 573 /* 574 * To the user the relevant error is 575 * that the "mustexist" reference is 576 * missing: 577 */ 578 strbuf_reset(err); 579 strbuf_addf(err, "unable to resolve reference '%s'", 580 refname); 581 } else { 582 /* 583 * The error message set by 584 * refs_verify_refname_available() is 585 * OK. 586 */ 587 ret = TRANSACTION_NAME_CONFLICT; 588 } 589 } else { 590 /* 591 * The file that is in the way isn't a loose 592 * reference. Report it as a low-level 593 * failure. 594 */ 595 strbuf_addf(err, "unable to create lock file %s.lock; " 596 "non-directory in the way", 597 ref_file.buf); 598 } 599 goto error_return; 600 case SCLD_VANISHED: 601 /* Maybe another process was tidying up. Try again. */ 602 if (--attempts_remaining > 0) 603 goto retry; 604 /* fall through */ 605 default: 606 strbuf_addf(err, "unable to create directory for %s", 607 ref_file.buf); 608 goto error_return; 609 } 610 611 if (hold_lock_file_for_update_timeout( 612 &lock->lk, ref_file.buf, LOCK_NO_DEREF, 613 get_files_ref_lock_timeout_ms()) < 0) { 614 if (errno == ENOENT && --attempts_remaining > 0) { 615 /* 616 * Maybe somebody just deleted one of the 617 * directories leading to ref_file. Try 618 * again: 619 */ 620 goto retry; 621 } else { 622 unable_to_lock_message(ref_file.buf, errno, err); 623 goto error_return; 624 } 625 } 626 627 /* 628 * Now we hold the lock and can read the reference without 629 * fear that its value will change. 630 */ 631 632 if (files_read_raw_ref(&refs->base, refname, 633 &lock->old_oid, referent, type)) { 634 if (errno == ENOENT) { 635 if (mustexist) { 636 /* Garden variety missing reference. */ 637 strbuf_addf(err, "unable to resolve reference '%s'", 638 refname); 639 goto error_return; 640 } else { 641 /* 642 * Reference is missing, but that's OK. We 643 * know that there is not a conflict with 644 * another loose reference because 645 * (supposing that we are trying to lock 646 * reference "refs/foo/bar"): 647 * 648 * - We were successfully able to create 649 * the lockfile refs/foo/bar.lock, so we 650 * know there cannot be a loose reference 651 * named "refs/foo". 652 * 653 * - We got ENOENT and not EISDIR, so we 654 * know that there cannot be a loose 655 * reference named "refs/foo/bar/baz". 656 */ 657 } 658 } else if (errno == EISDIR) { 659 /* 660 * There is a directory in the way. It might have 661 * contained references that have been deleted. If 662 * we don't require that the reference already 663 * exists, try to remove the directory so that it 664 * doesn't cause trouble when we want to rename the 665 * lockfile into place later. 666 */ 667 if (mustexist) { 668 /* Garden variety missing reference. */ 669 strbuf_addf(err, "unable to resolve reference '%s'", 670 refname); 671 goto error_return; 672 } else if (remove_dir_recursively(&ref_file, 673 REMOVE_DIR_EMPTY_ONLY)) { 674 if (refs_verify_refname_available( 675 &refs->base, refname, 676 extras, skip, err)) { 677 /* 678 * The error message set by 679 * verify_refname_available() is OK. 680 */ 681 ret = TRANSACTION_NAME_CONFLICT; 682 goto error_return; 683 } else { 684 /* 685 * We can't delete the directory, 686 * but we also don't know of any 687 * references that it should 688 * contain. 689 */ 690 strbuf_addf(err, "there is a non-empty directory '%s' " 691 "blocking reference '%s'", 692 ref_file.buf, refname); 693 goto error_return; 694 } 695 } 696 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) { 697 strbuf_addf(err, "unable to resolve reference '%s': " 698 "reference broken", refname); 699 goto error_return; 700 } else { 701 strbuf_addf(err, "unable to resolve reference '%s': %s", 702 refname, strerror(errno)); 703 goto error_return; 704 } 705 706 /* 707 * If the ref did not exist and we are creating it, 708 * make sure there is no existing packed ref that 709 * conflicts with refname: 710 */ 711 if (refs_verify_refname_available( 712 refs->packed_ref_store, refname, 713 extras, skip, err)) 714 goto error_return; 715 } 716 717 ret = 0; 718 goto out; 719 720error_return: 721 unlock_ref(lock); 722 *lock_p = NULL; 723 724out: 725 strbuf_release(&ref_file); 726 return ret; 727} 728 729struct files_ref_iterator { 730 struct ref_iterator base; 731 732 struct ref_iterator *iter0; 733 unsigned int flags; 734}; 735 736static int files_ref_iterator_advance(struct ref_iterator *ref_iterator) 737{ 738 struct files_ref_iterator *iter = 739 (struct files_ref_iterator *)ref_iterator; 740 int ok; 741 742 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) { 743 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 744 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 745 continue; 746 747 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 748 !ref_resolves_to_object(iter->iter0->refname, 749 iter->iter0->oid, 750 iter->iter0->flags)) 751 continue; 752 753 iter->base.refname = iter->iter0->refname; 754 iter->base.oid = iter->iter0->oid; 755 iter->base.flags = iter->iter0->flags; 756 return ITER_OK; 757 } 758 759 iter->iter0 = NULL; 760 if (ref_iterator_abort(ref_iterator) != ITER_DONE) 761 ok = ITER_ERROR; 762 763 return ok; 764} 765 766static int files_ref_iterator_peel(struct ref_iterator *ref_iterator, 767 struct object_id *peeled) 768{ 769 struct files_ref_iterator *iter = 770 (struct files_ref_iterator *)ref_iterator; 771 772 return ref_iterator_peel(iter->iter0, peeled); 773} 774 775static int files_ref_iterator_abort(struct ref_iterator *ref_iterator) 776{ 777 struct files_ref_iterator *iter = 778 (struct files_ref_iterator *)ref_iterator; 779 int ok = ITER_DONE; 780 781 if (iter->iter0) 782 ok = ref_iterator_abort(iter->iter0); 783 784 base_ref_iterator_free(ref_iterator); 785 return ok; 786} 787 788static struct ref_iterator_vtable files_ref_iterator_vtable = { 789 files_ref_iterator_advance, 790 files_ref_iterator_peel, 791 files_ref_iterator_abort 792}; 793 794static struct ref_iterator *files_ref_iterator_begin( 795 struct ref_store *ref_store, 796 const char *prefix, unsigned int flags) 797{ 798 struct files_ref_store *refs; 799 struct ref_iterator *loose_iter, *packed_iter, *overlay_iter; 800 struct files_ref_iterator *iter; 801 struct ref_iterator *ref_iterator; 802 unsigned int required_flags = REF_STORE_READ; 803 804 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 805 required_flags |= REF_STORE_ODB; 806 807 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin"); 808 809 /* 810 * We must make sure that all loose refs are read before 811 * accessing the packed-refs file; this avoids a race 812 * condition if loose refs are migrated to the packed-refs 813 * file by a simultaneous process, but our in-memory view is 814 * from before the migration. We ensure this as follows: 815 * First, we call start the loose refs iteration with its 816 * `prime_ref` argument set to true. This causes the loose 817 * references in the subtree to be pre-read into the cache. 818 * (If they've already been read, that's OK; we only need to 819 * guarantee that they're read before the packed refs, not 820 * *how much* before.) After that, we call 821 * packed_ref_iterator_begin(), which internally checks 822 * whether the packed-ref cache is up to date with what is on 823 * disk, and re-reads it if not. 824 */ 825 826 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), 827 prefix, 1); 828 829 /* 830 * The packed-refs file might contain broken references, for 831 * example an old version of a reference that points at an 832 * object that has since been garbage-collected. This is OK as 833 * long as there is a corresponding loose reference that 834 * overrides it, and we don't want to emit an error message in 835 * this case. So ask the packed_ref_store for all of its 836 * references, and (if needed) do our own check for broken 837 * ones in files_ref_iterator_advance(), after we have merged 838 * the packed and loose references. 839 */ 840 packed_iter = refs_ref_iterator_begin( 841 refs->packed_ref_store, prefix, 0, 842 DO_FOR_EACH_INCLUDE_BROKEN); 843 844 overlay_iter = overlay_ref_iterator_begin(loose_iter, packed_iter); 845 846 iter = xcalloc(1, sizeof(*iter)); 847 ref_iterator = &iter->base; 848 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable, 849 overlay_iter->ordered); 850 iter->iter0 = overlay_iter; 851 iter->flags = flags; 852 853 return ref_iterator; 854} 855 856/* 857 * Verify that the reference locked by lock has the value old_oid 858 * (unless it is NULL). Fail if the reference doesn't exist and 859 * mustexist is set. Return 0 on success. On error, write an error 860 * message to err, set errno, and return a negative value. 861 */ 862static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock, 863 const struct object_id *old_oid, int mustexist, 864 struct strbuf *err) 865{ 866 assert(err); 867 868 if (refs_read_ref_full(ref_store, lock->ref_name, 869 mustexist ? RESOLVE_REF_READING : 0, 870 &lock->old_oid, NULL)) { 871 if (old_oid) { 872 int save_errno = errno; 873 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name); 874 errno = save_errno; 875 return -1; 876 } else { 877 oidclr(&lock->old_oid); 878 return 0; 879 } 880 } 881 if (old_oid && !oideq(&lock->old_oid, old_oid)) { 882 strbuf_addf(err, "ref '%s' is at %s but expected %s", 883 lock->ref_name, 884 oid_to_hex(&lock->old_oid), 885 oid_to_hex(old_oid)); 886 errno = EBUSY; 887 return -1; 888 } 889 return 0; 890} 891 892static int remove_empty_directories(struct strbuf *path) 893{ 894 /* 895 * we want to create a file but there is a directory there; 896 * if that is an empty directory (or a directory that contains 897 * only empty directories), remove them. 898 */ 899 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 900} 901 902static int create_reflock(const char *path, void *cb) 903{ 904 struct lock_file *lk = cb; 905 906 return hold_lock_file_for_update_timeout( 907 lk, path, LOCK_NO_DEREF, 908 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0; 909} 910 911/* 912 * Locks a ref returning the lock on success and NULL on failure. 913 * On failure errno is set to something meaningful. 914 */ 915static struct ref_lock *lock_ref_oid_basic(struct files_ref_store *refs, 916 const char *refname, 917 const struct object_id *old_oid, 918 const struct string_list *extras, 919 const struct string_list *skip, 920 unsigned int flags, int *type, 921 struct strbuf *err) 922{ 923 struct strbuf ref_file = STRBUF_INIT; 924 struct ref_lock *lock; 925 int last_errno = 0; 926 int mustexist = (old_oid && !is_null_oid(old_oid)); 927 int resolve_flags = RESOLVE_REF_NO_RECURSE; 928 int resolved; 929 930 files_assert_main_repository(refs, "lock_ref_oid_basic"); 931 assert(err); 932 933 lock = xcalloc(1, sizeof(struct ref_lock)); 934 935 if (mustexist) 936 resolve_flags |= RESOLVE_REF_READING; 937 if (flags & REF_DELETING) 938 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 939 940 files_ref_path(refs, &ref_file, refname); 941 resolved = !!refs_resolve_ref_unsafe(&refs->base, 942 refname, resolve_flags, 943 &lock->old_oid, type); 944 if (!resolved && errno == EISDIR) { 945 /* 946 * we are trying to lock foo but we used to 947 * have foo/bar which now does not exist; 948 * it is normal for the empty directory 'foo' 949 * to remain. 950 */ 951 if (remove_empty_directories(&ref_file)) { 952 last_errno = errno; 953 if (!refs_verify_refname_available( 954 &refs->base, 955 refname, extras, skip, err)) 956 strbuf_addf(err, "there are still refs under '%s'", 957 refname); 958 goto error_return; 959 } 960 resolved = !!refs_resolve_ref_unsafe(&refs->base, 961 refname, resolve_flags, 962 &lock->old_oid, type); 963 } 964 if (!resolved) { 965 last_errno = errno; 966 if (last_errno != ENOTDIR || 967 !refs_verify_refname_available(&refs->base, refname, 968 extras, skip, err)) 969 strbuf_addf(err, "unable to resolve reference '%s': %s", 970 refname, strerror(last_errno)); 971 972 goto error_return; 973 } 974 975 /* 976 * If the ref did not exist and we are creating it, make sure 977 * there is no existing packed ref whose name begins with our 978 * refname, nor a packed ref whose name is a proper prefix of 979 * our refname. 980 */ 981 if (is_null_oid(&lock->old_oid) && 982 refs_verify_refname_available(refs->packed_ref_store, refname, 983 extras, skip, err)) { 984 last_errno = ENOTDIR; 985 goto error_return; 986 } 987 988 lock->ref_name = xstrdup(refname); 989 990 if (raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) { 991 last_errno = errno; 992 unable_to_lock_message(ref_file.buf, errno, err); 993 goto error_return; 994 } 995 996 if (verify_lock(&refs->base, lock, old_oid, mustexist, err)) { 997 last_errno = errno; 998 goto error_return; 999 }1000 goto out;10011002 error_return:1003 unlock_ref(lock);1004 lock = NULL;10051006 out:1007 strbuf_release(&ref_file);1008 errno = last_errno;1009 return lock;1010}10111012struct ref_to_prune {1013 struct ref_to_prune *next;1014 struct object_id oid;1015 char name[FLEX_ARRAY];1016};10171018enum {1019 REMOVE_EMPTY_PARENTS_REF = 0x01,1020 REMOVE_EMPTY_PARENTS_REFLOG = 0x021021};10221023/*1024 * Remove empty parent directories associated with the specified1025 * reference and/or its reflog, but spare [logs/]refs/ and immediate1026 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1027 * REMOVE_EMPTY_PARENTS_REFLOG.1028 */1029static void try_remove_empty_parents(struct files_ref_store *refs,1030 const char *refname,1031 unsigned int flags)1032{1033 struct strbuf buf = STRBUF_INIT;1034 struct strbuf sb = STRBUF_INIT;1035 char *p, *q;1036 int i;10371038 strbuf_addstr(&buf, refname);1039 p = buf.buf;1040 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */1041 while (*p && *p != '/')1042 p++;1043 /* tolerate duplicate slashes; see check_refname_format() */1044 while (*p == '/')1045 p++;1046 }1047 q = buf.buf + buf.len;1048 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1049 while (q > p && *q != '/')1050 q--;1051 while (q > p && *(q-1) == '/')1052 q--;1053 if (q == p)1054 break;1055 strbuf_setlen(&buf, q - buf.buf);10561057 strbuf_reset(&sb);1058 files_ref_path(refs, &sb, buf.buf);1059 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))1060 flags &= ~REMOVE_EMPTY_PARENTS_REF;10611062 strbuf_reset(&sb);1063 files_reflog_path(refs, &sb, buf.buf);1064 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))1065 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1066 }1067 strbuf_release(&buf);1068 strbuf_release(&sb);1069}10701071/* make sure nobody touched the ref, and unlink */1072static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)1073{1074 struct ref_transaction *transaction;1075 struct strbuf err = STRBUF_INIT;1076 int ret = -1;10771078 if (check_refname_format(r->name, 0))1079 return;10801081 transaction = ref_store_transaction_begin(&refs->base, &err);1082 if (!transaction)1083 goto cleanup;1084 ref_transaction_add_update(1085 transaction, r->name,1086 REF_NO_DEREF | REF_HAVE_NEW | REF_HAVE_OLD | REF_IS_PRUNING,1087 &null_oid, &r->oid, NULL);1088 if (ref_transaction_commit(transaction, &err))1089 goto cleanup;10901091 ret = 0;10921093cleanup:1094 if (ret)1095 error("%s", err.buf);1096 strbuf_release(&err);1097 ref_transaction_free(transaction);1098 return;1099}11001101/*1102 * Prune the loose versions of the references in the linked list1103 * `*refs_to_prune`, freeing the entries in the list as we go.1104 */1105static void prune_refs(struct files_ref_store *refs, struct ref_to_prune **refs_to_prune)1106{1107 while (*refs_to_prune) {1108 struct ref_to_prune *r = *refs_to_prune;1109 *refs_to_prune = r->next;1110 prune_ref(refs, r);1111 free(r);1112 }1113}11141115/*1116 * Return true if the specified reference should be packed.1117 */1118static int should_pack_ref(const char *refname,1119 const struct object_id *oid, unsigned int ref_flags,1120 unsigned int pack_flags)1121{1122 /* Do not pack per-worktree refs: */1123 if (ref_type(refname) != REF_TYPE_NORMAL)1124 return 0;11251126 /* Do not pack non-tags unless PACK_REFS_ALL is set: */1127 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))1128 return 0;11291130 /* Do not pack symbolic refs: */1131 if (ref_flags & REF_ISSYMREF)1132 return 0;11331134 /* Do not pack broken refs: */1135 if (!ref_resolves_to_object(refname, oid, ref_flags))1136 return 0;11371138 return 1;1139}11401141static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)1142{1143 struct files_ref_store *refs =1144 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1145 "pack_refs");1146 struct ref_iterator *iter;1147 int ok;1148 struct ref_to_prune *refs_to_prune = NULL;1149 struct strbuf err = STRBUF_INIT;1150 struct ref_transaction *transaction;11511152 transaction = ref_store_transaction_begin(refs->packed_ref_store, &err);1153 if (!transaction)1154 return -1;11551156 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);11571158 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);1159 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {1160 /*1161 * If the loose reference can be packed, add an entry1162 * in the packed ref cache. If the reference should be1163 * pruned, also add it to refs_to_prune.1164 */1165 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,1166 flags))1167 continue;11681169 /*1170 * Add a reference creation for this reference to the1171 * packed-refs transaction:1172 */1173 if (ref_transaction_update(transaction, iter->refname,1174 iter->oid, NULL,1175 REF_NO_DEREF, NULL, &err))1176 die("failure preparing to create packed reference %s: %s",1177 iter->refname, err.buf);11781179 /* Schedule the loose reference for pruning if requested. */1180 if ((flags & PACK_REFS_PRUNE)) {1181 struct ref_to_prune *n;1182 FLEX_ALLOC_STR(n, name, iter->refname);1183 oidcpy(&n->oid, iter->oid);1184 n->next = refs_to_prune;1185 refs_to_prune = n;1186 }1187 }1188 if (ok != ITER_DONE)1189 die("error while iterating over references");11901191 if (ref_transaction_commit(transaction, &err))1192 die("unable to write new packed-refs: %s", err.buf);11931194 ref_transaction_free(transaction);11951196 packed_refs_unlock(refs->packed_ref_store);11971198 prune_refs(refs, &refs_to_prune);1199 strbuf_release(&err);1200 return 0;1201}12021203static int files_delete_refs(struct ref_store *ref_store, const char *msg,1204 struct string_list *refnames, unsigned int flags)1205{1206 struct files_ref_store *refs =1207 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");1208 struct strbuf err = STRBUF_INIT;1209 int i, result = 0;12101211 if (!refnames->nr)1212 return 0;12131214 if (packed_refs_lock(refs->packed_ref_store, 0, &err))1215 goto error;12161217 if (refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {1218 packed_refs_unlock(refs->packed_ref_store);1219 goto error;1220 }12211222 packed_refs_unlock(refs->packed_ref_store);12231224 for (i = 0; i < refnames->nr; i++) {1225 const char *refname = refnames->items[i].string;12261227 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))1228 result |= error(_("could not remove reference %s"), refname);1229 }12301231 strbuf_release(&err);1232 return result;12331234error:1235 /*1236 * If we failed to rewrite the packed-refs file, then it is1237 * unsafe to try to remove loose refs, because doing so might1238 * expose an obsolete packed value for a reference that might1239 * even point at an object that has been garbage collected.1240 */1241 if (refnames->nr == 1)1242 error(_("could not delete reference %s: %s"),1243 refnames->items[0].string, err.buf);1244 else1245 error(_("could not delete references: %s"), err.buf);12461247 strbuf_release(&err);1248 return -1;1249}12501251/*1252 * People using contrib's git-new-workdir have .git/logs/refs ->1253 * /some/other/path/.git/logs/refs, and that may live on another device.1254 *1255 * IOW, to avoid cross device rename errors, the temporary renamed log must1256 * live into logs/refs.1257 */1258#define TMP_RENAMED_LOG "refs/.tmp-renamed-log"12591260struct rename_cb {1261 const char *tmp_renamed_log;1262 int true_errno;1263};12641265static int rename_tmp_log_callback(const char *path, void *cb_data)1266{1267 struct rename_cb *cb = cb_data;12681269 if (rename(cb->tmp_renamed_log, path)) {1270 /*1271 * rename(a, b) when b is an existing directory ought1272 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1273 * Sheesh. Record the true errno for error reporting,1274 * but report EISDIR to raceproof_create_file() so1275 * that it knows to retry.1276 */1277 cb->true_errno = errno;1278 if (errno == ENOTDIR)1279 errno = EISDIR;1280 return -1;1281 } else {1282 return 0;1283 }1284}12851286static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)1287{1288 struct strbuf path = STRBUF_INIT;1289 struct strbuf tmp = STRBUF_INIT;1290 struct rename_cb cb;1291 int ret;12921293 files_reflog_path(refs, &path, newrefname);1294 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1295 cb.tmp_renamed_log = tmp.buf;1296 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1297 if (ret) {1298 if (errno == EISDIR)1299 error("directory not empty: %s", path.buf);1300 else1301 error("unable to move logfile %s to %s: %s",1302 tmp.buf, path.buf,1303 strerror(cb.true_errno));1304 }13051306 strbuf_release(&path);1307 strbuf_release(&tmp);1308 return ret;1309}13101311static int write_ref_to_lockfile(struct ref_lock *lock,1312 const struct object_id *oid, struct strbuf *err);1313static int commit_ref_update(struct files_ref_store *refs,1314 struct ref_lock *lock,1315 const struct object_id *oid, const char *logmsg,1316 struct strbuf *err);13171318static int files_copy_or_rename_ref(struct ref_store *ref_store,1319 const char *oldrefname, const char *newrefname,1320 const char *logmsg, int copy)1321{1322 struct files_ref_store *refs =1323 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");1324 struct object_id oid, orig_oid;1325 int flag = 0, logmoved = 0;1326 struct ref_lock *lock;1327 struct stat loginfo;1328 struct strbuf sb_oldref = STRBUF_INIT;1329 struct strbuf sb_newref = STRBUF_INIT;1330 struct strbuf tmp_renamed_log = STRBUF_INIT;1331 int log, ret;1332 struct strbuf err = STRBUF_INIT;13331334 files_reflog_path(refs, &sb_oldref, oldrefname);1335 files_reflog_path(refs, &sb_newref, newrefname);1336 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);13371338 log = !lstat(sb_oldref.buf, &loginfo);1339 if (log && S_ISLNK(loginfo.st_mode)) {1340 ret = error("reflog for %s is a symlink", oldrefname);1341 goto out;1342 }13431344 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,1345 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1346 &orig_oid, &flag)) {1347 ret = error("refname %s not found", oldrefname);1348 goto out;1349 }13501351 if (flag & REF_ISSYMREF) {1352 if (copy)1353 ret = error("refname %s is a symbolic ref, copying it is not supported",1354 oldrefname);1355 else1356 ret = error("refname %s is a symbolic ref, renaming it is not supported",1357 oldrefname);1358 goto out;1359 }1360 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1361 ret = 1;1362 goto out;1363 }13641365 if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {1366 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",1367 oldrefname, strerror(errno));1368 goto out;1369 }13701371 if (copy && log && copy_file(tmp_renamed_log.buf, sb_oldref.buf, 0644)) {1372 ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",1373 oldrefname, strerror(errno));1374 goto out;1375 }13761377 if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,1378 &orig_oid, REF_NO_DEREF)) {1379 error("unable to delete old %s", oldrefname);1380 goto rollback;1381 }13821383 /*1384 * Since we are doing a shallow lookup, oid is not the1385 * correct value to pass to delete_ref as old_oid. But that1386 * doesn't matter, because an old_oid check wouldn't add to1387 * the safety anyway; we want to delete the reference whatever1388 * its current value.1389 */1390 if (!copy && !refs_read_ref_full(&refs->base, newrefname,1391 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1392 &oid, NULL) &&1393 refs_delete_ref(&refs->base, NULL, newrefname,1394 NULL, REF_NO_DEREF)) {1395 if (errno == EISDIR) {1396 struct strbuf path = STRBUF_INIT;1397 int result;13981399 files_ref_path(refs, &path, newrefname);1400 result = remove_empty_directories(&path);1401 strbuf_release(&path);14021403 if (result) {1404 error("Directory not empty: %s", newrefname);1405 goto rollback;1406 }1407 } else {1408 error("unable to delete existing %s", newrefname);1409 goto rollback;1410 }1411 }14121413 if (log && rename_tmp_log(refs, newrefname))1414 goto rollback;14151416 logmoved = log;14171418 lock = lock_ref_oid_basic(refs, newrefname, NULL, NULL, NULL,1419 REF_NO_DEREF, NULL, &err);1420 if (!lock) {1421 if (copy)1422 error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);1423 else1424 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);1425 strbuf_release(&err);1426 goto rollback;1427 }1428 oidcpy(&lock->old_oid, &orig_oid);14291430 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||1431 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1432 error("unable to write current sha1 into %s: %s", newrefname, err.buf);1433 strbuf_release(&err);1434 goto rollback;1435 }14361437 ret = 0;1438 goto out;14391440 rollback:1441 lock = lock_ref_oid_basic(refs, oldrefname, NULL, NULL, NULL,1442 REF_NO_DEREF, NULL, &err);1443 if (!lock) {1444 error("unable to lock %s for rollback: %s", oldrefname, err.buf);1445 strbuf_release(&err);1446 goto rollbacklog;1447 }14481449 flag = log_all_ref_updates;1450 log_all_ref_updates = LOG_REFS_NONE;1451 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||1452 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1453 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);1454 strbuf_release(&err);1455 }1456 log_all_ref_updates = flag;14571458 rollbacklog:1459 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))1460 error("unable to restore logfile %s from %s: %s",1461 oldrefname, newrefname, strerror(errno));1462 if (!logmoved && log &&1463 rename(tmp_renamed_log.buf, sb_oldref.buf))1464 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",1465 oldrefname, strerror(errno));1466 ret = 1;1467 out:1468 strbuf_release(&sb_newref);1469 strbuf_release(&sb_oldref);1470 strbuf_release(&tmp_renamed_log);14711472 return ret;1473}14741475static int files_rename_ref(struct ref_store *ref_store,1476 const char *oldrefname, const char *newrefname,1477 const char *logmsg)1478{1479 return files_copy_or_rename_ref(ref_store, oldrefname,1480 newrefname, logmsg, 0);1481}14821483static int files_copy_ref(struct ref_store *ref_store,1484 const char *oldrefname, const char *newrefname,1485 const char *logmsg)1486{1487 return files_copy_or_rename_ref(ref_store, oldrefname,1488 newrefname, logmsg, 1);1489}14901491static int close_ref_gently(struct ref_lock *lock)1492{1493 if (close_lock_file_gently(&lock->lk))1494 return -1;1495 return 0;1496}14971498static int commit_ref(struct ref_lock *lock)1499{1500 char *path = get_locked_file_path(&lock->lk);1501 struct stat st;15021503 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {1504 /*1505 * There is a directory at the path we want to rename1506 * the lockfile to. Hopefully it is empty; try to1507 * delete it.1508 */1509 size_t len = strlen(path);1510 struct strbuf sb_path = STRBUF_INIT;15111512 strbuf_attach(&sb_path, path, len, len);15131514 /*1515 * If this fails, commit_lock_file() will also fail1516 * and will report the problem.1517 */1518 remove_empty_directories(&sb_path);1519 strbuf_release(&sb_path);1520 } else {1521 free(path);1522 }15231524 if (commit_lock_file(&lock->lk))1525 return -1;1526 return 0;1527}15281529static int open_or_create_logfile(const char *path, void *cb)1530{1531 int *fd = cb;15321533 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);1534 return (*fd < 0) ? -1 : 0;1535}15361537/*1538 * Create a reflog for a ref. If force_create = 0, only create the1539 * reflog for certain refs (those for which should_autocreate_reflog1540 * returns non-zero). Otherwise, create it regardless of the reference1541 * name. If the logfile already existed or was created, return 0 and1542 * set *logfd to the file descriptor opened for appending to the file.1543 * If no logfile exists and we decided not to create one, return 0 and1544 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1545 * return -1.1546 */1547static int log_ref_setup(struct files_ref_store *refs,1548 const char *refname, int force_create,1549 int *logfd, struct strbuf *err)1550{1551 struct strbuf logfile_sb = STRBUF_INIT;1552 char *logfile;15531554 files_reflog_path(refs, &logfile_sb, refname);1555 logfile = strbuf_detach(&logfile_sb, NULL);15561557 if (force_create || should_autocreate_reflog(refname)) {1558 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1559 if (errno == ENOENT)1560 strbuf_addf(err, "unable to create directory for '%s': "1561 "%s", logfile, strerror(errno));1562 else if (errno == EISDIR)1563 strbuf_addf(err, "there are still logs under '%s'",1564 logfile);1565 else1566 strbuf_addf(err, "unable to append to '%s': %s",1567 logfile, strerror(errno));15681569 goto error;1570 }1571 } else {1572 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);1573 if (*logfd < 0) {1574 if (errno == ENOENT || errno == EISDIR) {1575 /*1576 * The logfile doesn't already exist,1577 * but that is not an error; it only1578 * means that we won't write log1579 * entries to it.1580 */1581 ;1582 } else {1583 strbuf_addf(err, "unable to append to '%s': %s",1584 logfile, strerror(errno));1585 goto error;1586 }1587 }1588 }15891590 if (*logfd >= 0)1591 adjust_shared_perm(logfile);15921593 free(logfile);1594 return 0;15951596error:1597 free(logfile);1598 return -1;1599}16001601static int files_create_reflog(struct ref_store *ref_store,1602 const char *refname, int force_create,1603 struct strbuf *err)1604{1605 struct files_ref_store *refs =1606 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");1607 int fd;16081609 if (log_ref_setup(refs, refname, force_create, &fd, err))1610 return -1;16111612 if (fd >= 0)1613 close(fd);16141615 return 0;1616}16171618static int log_ref_write_fd(int fd, const struct object_id *old_oid,1619 const struct object_id *new_oid,1620 const char *committer, const char *msg)1621{1622 struct strbuf sb = STRBUF_INIT;1623 int ret = 0;16241625 strbuf_addf(&sb, "%s %s %s", oid_to_hex(old_oid), oid_to_hex(new_oid), committer);1626 if (msg && *msg)1627 copy_reflog_msg(&sb, msg);1628 strbuf_addch(&sb, '\n');1629 if (write_in_full(fd, sb.buf, sb.len) < 0)1630 ret = -1;1631 strbuf_release(&sb);1632 return ret;1633}16341635static int files_log_ref_write(struct files_ref_store *refs,1636 const char *refname, const struct object_id *old_oid,1637 const struct object_id *new_oid, const char *msg,1638 int flags, struct strbuf *err)1639{1640 int logfd, result;16411642 if (log_all_ref_updates == LOG_REFS_UNSET)1643 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;16441645 result = log_ref_setup(refs, refname,1646 flags & REF_FORCE_CREATE_REFLOG,1647 &logfd, err);16481649 if (result)1650 return result;16511652 if (logfd < 0)1653 return 0;1654 result = log_ref_write_fd(logfd, old_oid, new_oid,1655 git_committer_info(0), msg);1656 if (result) {1657 struct strbuf sb = STRBUF_INIT;1658 int save_errno = errno;16591660 files_reflog_path(refs, &sb, refname);1661 strbuf_addf(err, "unable to append to '%s': %s",1662 sb.buf, strerror(save_errno));1663 strbuf_release(&sb);1664 close(logfd);1665 return -1;1666 }1667 if (close(logfd)) {1668 struct strbuf sb = STRBUF_INIT;1669 int save_errno = errno;16701671 files_reflog_path(refs, &sb, refname);1672 strbuf_addf(err, "unable to append to '%s': %s",1673 sb.buf, strerror(save_errno));1674 strbuf_release(&sb);1675 return -1;1676 }1677 return 0;1678}16791680/*1681 * Write oid into the open lockfile, then close the lockfile. On1682 * errors, rollback the lockfile, fill in *err and return -1.1683 */1684static int write_ref_to_lockfile(struct ref_lock *lock,1685 const struct object_id *oid, struct strbuf *err)1686{1687 static char term = '\n';1688 struct object *o;1689 int fd;16901691 o = parse_object(the_repository, oid);1692 if (!o) {1693 strbuf_addf(err,1694 "trying to write ref '%s' with nonexistent object %s",1695 lock->ref_name, oid_to_hex(oid));1696 unlock_ref(lock);1697 return -1;1698 }1699 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {1700 strbuf_addf(err,1701 "trying to write non-commit object %s to branch '%s'",1702 oid_to_hex(oid), lock->ref_name);1703 unlock_ref(lock);1704 return -1;1705 }1706 fd = get_lock_file_fd(&lock->lk);1707 if (write_in_full(fd, oid_to_hex(oid), the_hash_algo->hexsz) < 0 ||1708 write_in_full(fd, &term, 1) < 0 ||1709 close_ref_gently(lock) < 0) {1710 strbuf_addf(err,1711 "couldn't write '%s'", get_lock_file_path(&lock->lk));1712 unlock_ref(lock);1713 return -1;1714 }1715 return 0;1716}17171718/*1719 * Commit a change to a loose reference that has already been written1720 * to the loose reference lockfile. Also update the reflogs if1721 * necessary, using the specified lockmsg (which can be NULL).1722 */1723static int commit_ref_update(struct files_ref_store *refs,1724 struct ref_lock *lock,1725 const struct object_id *oid, const char *logmsg,1726 struct strbuf *err)1727{1728 files_assert_main_repository(refs, "commit_ref_update");17291730 clear_loose_ref_cache(refs);1731 if (files_log_ref_write(refs, lock->ref_name,1732 &lock->old_oid, oid,1733 logmsg, 0, err)) {1734 char *old_msg = strbuf_detach(err, NULL);1735 strbuf_addf(err, "cannot update the ref '%s': %s",1736 lock->ref_name, old_msg);1737 free(old_msg);1738 unlock_ref(lock);1739 return -1;1740 }17411742 if (strcmp(lock->ref_name, "HEAD") != 0) {1743 /*1744 * Special hack: If a branch is updated directly and HEAD1745 * points to it (may happen on the remote side of a push1746 * for example) then logically the HEAD reflog should be1747 * updated too.1748 * A generic solution implies reverse symref information,1749 * but finding all symrefs pointing to the given branch1750 * would be rather costly for this rare event (the direct1751 * update of a branch) to be worth it. So let's cheat and1752 * check with HEAD only which should cover 99% of all usage1753 * scenarios (even 100% of the default ones).1754 */1755 int head_flag;1756 const char *head_ref;17571758 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",1759 RESOLVE_REF_READING,1760 NULL, &head_flag);1761 if (head_ref && (head_flag & REF_ISSYMREF) &&1762 !strcmp(head_ref, lock->ref_name)) {1763 struct strbuf log_err = STRBUF_INIT;1764 if (files_log_ref_write(refs, "HEAD",1765 &lock->old_oid, oid,1766 logmsg, 0, &log_err)) {1767 error("%s", log_err.buf);1768 strbuf_release(&log_err);1769 }1770 }1771 }17721773 if (commit_ref(lock)) {1774 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);1775 unlock_ref(lock);1776 return -1;1777 }17781779 unlock_ref(lock);1780 return 0;1781}17821783static int create_ref_symlink(struct ref_lock *lock, const char *target)1784{1785 int ret = -1;1786#ifndef NO_SYMLINK_HEAD1787 char *ref_path = get_locked_file_path(&lock->lk);1788 unlink(ref_path);1789 ret = symlink(target, ref_path);1790 free(ref_path);17911792 if (ret)1793 fprintf(stderr, "no symlink - falling back to symbolic ref\n");1794#endif1795 return ret;1796}17971798static void update_symref_reflog(struct files_ref_store *refs,1799 struct ref_lock *lock, const char *refname,1800 const char *target, const char *logmsg)1801{1802 struct strbuf err = STRBUF_INIT;1803 struct object_id new_oid;1804 if (logmsg &&1805 !refs_read_ref_full(&refs->base, target,1806 RESOLVE_REF_READING, &new_oid, NULL) &&1807 files_log_ref_write(refs, refname, &lock->old_oid,1808 &new_oid, logmsg, 0, &err)) {1809 error("%s", err.buf);1810 strbuf_release(&err);1811 }1812}18131814static int create_symref_locked(struct files_ref_store *refs,1815 struct ref_lock *lock, const char *refname,1816 const char *target, const char *logmsg)1817{1818 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {1819 update_symref_reflog(refs, lock, refname, target, logmsg);1820 return 0;1821 }18221823 if (!fdopen_lock_file(&lock->lk, "w"))1824 return error("unable to fdopen %s: %s",1825 lock->lk.tempfile->filename.buf, strerror(errno));18261827 update_symref_reflog(refs, lock, refname, target, logmsg);18281829 /* no error check; commit_ref will check ferror */1830 fprintf(lock->lk.tempfile->fp, "ref: %s\n", target);1831 if (commit_ref(lock) < 0)1832 return error("unable to write symref for %s: %s", refname,1833 strerror(errno));1834 return 0;1835}18361837static int files_create_symref(struct ref_store *ref_store,1838 const char *refname, const char *target,1839 const char *logmsg)1840{1841 struct files_ref_store *refs =1842 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");1843 struct strbuf err = STRBUF_INIT;1844 struct ref_lock *lock;1845 int ret;18461847 lock = lock_ref_oid_basic(refs, refname, NULL,1848 NULL, NULL, REF_NO_DEREF, NULL,1849 &err);1850 if (!lock) {1851 error("%s", err.buf);1852 strbuf_release(&err);1853 return -1;1854 }18551856 ret = create_symref_locked(refs, lock, refname, target, logmsg);1857 unlock_ref(lock);1858 return ret;1859}18601861static int files_reflog_exists(struct ref_store *ref_store,1862 const char *refname)1863{1864 struct files_ref_store *refs =1865 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");1866 struct strbuf sb = STRBUF_INIT;1867 struct stat st;1868 int ret;18691870 files_reflog_path(refs, &sb, refname);1871 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);1872 strbuf_release(&sb);1873 return ret;1874}18751876static int files_delete_reflog(struct ref_store *ref_store,1877 const char *refname)1878{1879 struct files_ref_store *refs =1880 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");1881 struct strbuf sb = STRBUF_INIT;1882 int ret;18831884 files_reflog_path(refs, &sb, refname);1885 ret = remove_path(sb.buf);1886 strbuf_release(&sb);1887 return ret;1888}18891890static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)1891{1892 struct object_id ooid, noid;1893 char *email_end, *message;1894 timestamp_t timestamp;1895 int tz;1896 const char *p = sb->buf;18971898 /* old SP new SP name <email> SP time TAB msg LF */1899 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||1900 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||1901 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||1902 !(email_end = strchr(p, '>')) ||1903 email_end[1] != ' ' ||1904 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||1905 !message || message[0] != ' ' ||1906 (message[1] != '+' && message[1] != '-') ||1907 !isdigit(message[2]) || !isdigit(message[3]) ||1908 !isdigit(message[4]) || !isdigit(message[5]))1909 return 0; /* corrupt? */1910 email_end[1] = '\0';1911 tz = strtol(message + 1, NULL, 10);1912 if (message[6] != '\t')1913 message += 6;1914 else1915 message += 7;1916 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);1917}19181919static char *find_beginning_of_line(char *bob, char *scan)1920{1921 while (bob < scan && *(--scan) != '\n')1922 ; /* keep scanning backwards */1923 /*1924 * Return either beginning of the buffer, or LF at the end of1925 * the previous line.1926 */1927 return scan;1928}19291930static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,1931 const char *refname,1932 each_reflog_ent_fn fn,1933 void *cb_data)1934{1935 struct files_ref_store *refs =1936 files_downcast(ref_store, REF_STORE_READ,1937 "for_each_reflog_ent_reverse");1938 struct strbuf sb = STRBUF_INIT;1939 FILE *logfp;1940 long pos;1941 int ret = 0, at_tail = 1;19421943 files_reflog_path(refs, &sb, refname);1944 logfp = fopen(sb.buf, "r");1945 strbuf_release(&sb);1946 if (!logfp)1947 return -1;19481949 /* Jump to the end */1950 if (fseek(logfp, 0, SEEK_END) < 0)1951 ret = error("cannot seek back reflog for %s: %s",1952 refname, strerror(errno));1953 pos = ftell(logfp);1954 while (!ret && 0 < pos) {1955 int cnt;1956 size_t nread;1957 char buf[BUFSIZ];1958 char *endp, *scanp;19591960 /* Fill next block from the end */1961 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;1962 if (fseek(logfp, pos - cnt, SEEK_SET)) {1963 ret = error("cannot seek back reflog for %s: %s",1964 refname, strerror(errno));1965 break;1966 }1967 nread = fread(buf, cnt, 1, logfp);1968 if (nread != 1) {1969 ret = error("cannot read %d bytes from reflog for %s: %s",1970 cnt, refname, strerror(errno));1971 break;1972 }1973 pos -= cnt;19741975 scanp = endp = buf + cnt;1976 if (at_tail && scanp[-1] == '\n')1977 /* Looking at the final LF at the end of the file */1978 scanp--;1979 at_tail = 0;19801981 while (buf < scanp) {1982 /*1983 * terminating LF of the previous line, or the beginning1984 * of the buffer.1985 */1986 char *bp;19871988 bp = find_beginning_of_line(buf, scanp);19891990 if (*bp == '\n') {1991 /*1992 * The newline is the end of the previous line,1993 * so we know we have complete line starting1994 * at (bp + 1). Prefix it onto any prior data1995 * we collected for the line and process it.1996 */1997 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));1998 scanp = bp;1999 endp = bp + 1;2000 ret = show_one_reflog_ent(&sb, fn, cb_data);2001 strbuf_reset(&sb);2002 if (ret)2003 break;2004 } else if (!pos) {2005 /*2006 * We are at the start of the buffer, and the2007 * start of the file; there is no previous2008 * line, and we have everything for this one.2009 * Process it, and we can end the loop.2010 */2011 strbuf_splice(&sb, 0, 0, buf, endp - buf);2012 ret = show_one_reflog_ent(&sb, fn, cb_data);2013 strbuf_reset(&sb);2014 break;2015 }20162017 if (bp == buf) {2018 /*2019 * We are at the start of the buffer, and there2020 * is more file to read backwards. Which means2021 * we are in the middle of a line. Note that we2022 * may get here even if *bp was a newline; that2023 * just means we are at the exact end of the2024 * previous line, rather than some spot in the2025 * middle.2026 *2027 * Save away what we have to be combined with2028 * the data from the next read.2029 */2030 strbuf_splice(&sb, 0, 0, buf, endp - buf);2031 break;2032 }2033 }20342035 }2036 if (!ret && sb.len)2037 BUG("reverse reflog parser had leftover data");20382039 fclose(logfp);2040 strbuf_release(&sb);2041 return ret;2042}20432044static int files_for_each_reflog_ent(struct ref_store *ref_store,2045 const char *refname,2046 each_reflog_ent_fn fn, void *cb_data)2047{2048 struct files_ref_store *refs =2049 files_downcast(ref_store, REF_STORE_READ,2050 "for_each_reflog_ent");2051 FILE *logfp;2052 struct strbuf sb = STRBUF_INIT;2053 int ret = 0;20542055 files_reflog_path(refs, &sb, refname);2056 logfp = fopen(sb.buf, "r");2057 strbuf_release(&sb);2058 if (!logfp)2059 return -1;20602061 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))2062 ret = show_one_reflog_ent(&sb, fn, cb_data);2063 fclose(logfp);2064 strbuf_release(&sb);2065 return ret;2066}20672068struct files_reflog_iterator {2069 struct ref_iterator base;20702071 struct ref_store *ref_store;2072 struct dir_iterator *dir_iterator;2073 struct object_id oid;2074};20752076static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)2077{2078 struct files_reflog_iterator *iter =2079 (struct files_reflog_iterator *)ref_iterator;2080 struct dir_iterator *diter = iter->dir_iterator;2081 int ok;20822083 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {2084 int flags;20852086 if (!S_ISREG(diter->st.st_mode))2087 continue;2088 if (diter->basename[0] == '.')2089 continue;2090 if (ends_with(diter->basename, ".lock"))2091 continue;20922093 if (refs_read_ref_full(iter->ref_store,2094 diter->relative_path, 0,2095 &iter->oid, &flags)) {2096 error("bad ref for %s", diter->path.buf);2097 continue;2098 }20992100 iter->base.refname = diter->relative_path;2101 iter->base.oid = &iter->oid;2102 iter->base.flags = flags;2103 return ITER_OK;2104 }21052106 iter->dir_iterator = NULL;2107 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)2108 ok = ITER_ERROR;2109 return ok;2110}21112112static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,2113 struct object_id *peeled)2114{2115 BUG("ref_iterator_peel() called for reflog_iterator");2116}21172118static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)2119{2120 struct files_reflog_iterator *iter =2121 (struct files_reflog_iterator *)ref_iterator;2122 int ok = ITER_DONE;21232124 if (iter->dir_iterator)2125 ok = dir_iterator_abort(iter->dir_iterator);21262127 base_ref_iterator_free(ref_iterator);2128 return ok;2129}21302131static struct ref_iterator_vtable files_reflog_iterator_vtable = {2132 files_reflog_iterator_advance,2133 files_reflog_iterator_peel,2134 files_reflog_iterator_abort2135};21362137static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,2138 const char *gitdir)2139{2140 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));2141 struct ref_iterator *ref_iterator = &iter->base;2142 struct strbuf sb = STRBUF_INIT;21432144 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable, 0);2145 strbuf_addf(&sb, "%s/logs", gitdir);2146 iter->dir_iterator = dir_iterator_begin(sb.buf);2147 iter->ref_store = ref_store;2148 strbuf_release(&sb);21492150 return ref_iterator;2151}21522153static enum iterator_selection reflog_iterator_select(2154 struct ref_iterator *iter_worktree,2155 struct ref_iterator *iter_common,2156 void *cb_data)2157{2158 if (iter_worktree) {2159 /*2160 * We're a bit loose here. We probably should ignore2161 * common refs if they are accidentally added as2162 * per-worktree refs.2163 */2164 return ITER_SELECT_0;2165 } else if (iter_common) {2166 if (ref_type(iter_common->refname) == REF_TYPE_NORMAL)2167 return ITER_SELECT_1;21682169 /*2170 * The main ref store may contain main worktree's2171 * per-worktree refs, which should be ignored2172 */2173 return ITER_SKIP_1;2174 } else2175 return ITER_DONE;2176}21772178static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2179{2180 struct files_ref_store *refs =2181 files_downcast(ref_store, REF_STORE_READ,2182 "reflog_iterator_begin");21832184 if (!strcmp(refs->gitdir, refs->gitcommondir)) {2185 return reflog_iterator_begin(ref_store, refs->gitcommondir);2186 } else {2187 return merge_ref_iterator_begin(2188 0,2189 reflog_iterator_begin(ref_store, refs->gitdir),2190 reflog_iterator_begin(ref_store, refs->gitcommondir),2191 reflog_iterator_select, refs);2192 }2193}21942195/*2196 * If update is a direct update of head_ref (the reference pointed to2197 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2198 */2199static int split_head_update(struct ref_update *update,2200 struct ref_transaction *transaction,2201 const char *head_ref,2202 struct string_list *affected_refnames,2203 struct strbuf *err)2204{2205 struct string_list_item *item;2206 struct ref_update *new_update;22072208 if ((update->flags & REF_LOG_ONLY) ||2209 (update->flags & REF_IS_PRUNING) ||2210 (update->flags & REF_UPDATE_VIA_HEAD))2211 return 0;22122213 if (strcmp(update->refname, head_ref))2214 return 0;22152216 /*2217 * First make sure that HEAD is not already in the2218 * transaction. This check is O(lg N) in the transaction2219 * size, but it happens at most once per transaction.2220 */2221 if (string_list_has_string(affected_refnames, "HEAD")) {2222 /* An entry already existed */2223 strbuf_addf(err,2224 "multiple updates for 'HEAD' (including one "2225 "via its referent '%s') are not allowed",2226 update->refname);2227 return TRANSACTION_NAME_CONFLICT;2228 }22292230 new_update = ref_transaction_add_update(2231 transaction, "HEAD",2232 update->flags | REF_LOG_ONLY | REF_NO_DEREF,2233 &update->new_oid, &update->old_oid,2234 update->msg);22352236 /*2237 * Add "HEAD". This insertion is O(N) in the transaction2238 * size, but it happens at most once per transaction.2239 * Add new_update->refname instead of a literal "HEAD".2240 */2241 if (strcmp(new_update->refname, "HEAD"))2242 BUG("%s unexpectedly not 'HEAD'", new_update->refname);2243 item = string_list_insert(affected_refnames, new_update->refname);2244 item->util = new_update;22452246 return 0;2247}22482249/*2250 * update is for a symref that points at referent and doesn't have2251 * REF_NO_DEREF set. Split it into two updates:2252 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set2253 * - A new, separate update for the referent reference2254 * Note that the new update will itself be subject to splitting when2255 * the iteration gets to it.2256 */2257static int split_symref_update(struct files_ref_store *refs,2258 struct ref_update *update,2259 const char *referent,2260 struct ref_transaction *transaction,2261 struct string_list *affected_refnames,2262 struct strbuf *err)2263{2264 struct string_list_item *item;2265 struct ref_update *new_update;2266 unsigned int new_flags;22672268 /*2269 * First make sure that referent is not already in the2270 * transaction. This check is O(lg N) in the transaction2271 * size, but it happens at most once per symref in a2272 * transaction.2273 */2274 if (string_list_has_string(affected_refnames, referent)) {2275 /* An entry already exists */2276 strbuf_addf(err,2277 "multiple updates for '%s' (including one "2278 "via symref '%s') are not allowed",2279 referent, update->refname);2280 return TRANSACTION_NAME_CONFLICT;2281 }22822283 new_flags = update->flags;2284 if (!strcmp(update->refname, "HEAD")) {2285 /*2286 * Record that the new update came via HEAD, so that2287 * when we process it, split_head_update() doesn't try2288 * to add another reflog update for HEAD. Note that2289 * this bit will be propagated if the new_update2290 * itself needs to be split.2291 */2292 new_flags |= REF_UPDATE_VIA_HEAD;2293 }22942295 new_update = ref_transaction_add_update(2296 transaction, referent, new_flags,2297 &update->new_oid, &update->old_oid,2298 update->msg);22992300 new_update->parent_update = update;23012302 /*2303 * Change the symbolic ref update to log only. Also, it2304 * doesn't need to check its old OID value, as that will be2305 * done when new_update is processed.2306 */2307 update->flags |= REF_LOG_ONLY | REF_NO_DEREF;2308 update->flags &= ~REF_HAVE_OLD;23092310 /*2311 * Add the referent. This insertion is O(N) in the transaction2312 * size, but it happens at most once per symref in a2313 * transaction. Make sure to add new_update->refname, which will2314 * be valid as long as affected_refnames is in use, and NOT2315 * referent, which might soon be freed by our caller.2316 */2317 item = string_list_insert(affected_refnames, new_update->refname);2318 if (item->util)2319 BUG("%s unexpectedly found in affected_refnames",2320 new_update->refname);2321 item->util = new_update;23222323 return 0;2324}23252326/*2327 * Return the refname under which update was originally requested.2328 */2329static const char *original_update_refname(struct ref_update *update)2330{2331 while (update->parent_update)2332 update = update->parent_update;23332334 return update->refname;2335}23362337/*2338 * Check whether the REF_HAVE_OLD and old_oid values stored in update2339 * are consistent with oid, which is the reference's current value. If2340 * everything is OK, return 0; otherwise, write an error message to2341 * err and return -1.2342 */2343static int check_old_oid(struct ref_update *update, struct object_id *oid,2344 struct strbuf *err)2345{2346 if (!(update->flags & REF_HAVE_OLD) ||2347 oideq(oid, &update->old_oid))2348 return 0;23492350 if (is_null_oid(&update->old_oid))2351 strbuf_addf(err, "cannot lock ref '%s': "2352 "reference already exists",2353 original_update_refname(update));2354 else if (is_null_oid(oid))2355 strbuf_addf(err, "cannot lock ref '%s': "2356 "reference is missing but expected %s",2357 original_update_refname(update),2358 oid_to_hex(&update->old_oid));2359 else2360 strbuf_addf(err, "cannot lock ref '%s': "2361 "is at %s but expected %s",2362 original_update_refname(update),2363 oid_to_hex(oid),2364 oid_to_hex(&update->old_oid));23652366 return -1;2367}23682369/*2370 * Prepare for carrying out update:2371 * - Lock the reference referred to by update.2372 * - Read the reference under lock.2373 * - Check that its old OID value (if specified) is correct, and in2374 * any case record it in update->lock->old_oid for later use when2375 * writing the reflog.2376 * - If it is a symref update without REF_NO_DEREF, split it up into a2377 * REF_LOG_ONLY update of the symref and add a separate update for2378 * the referent to transaction.2379 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2380 * update of HEAD.2381 */2382static int lock_ref_for_update(struct files_ref_store *refs,2383 struct ref_update *update,2384 struct ref_transaction *transaction,2385 const char *head_ref,2386 struct string_list *affected_refnames,2387 struct strbuf *err)2388{2389 struct strbuf referent = STRBUF_INIT;2390 int mustexist = (update->flags & REF_HAVE_OLD) &&2391 !is_null_oid(&update->old_oid);2392 int ret = 0;2393 struct ref_lock *lock;23942395 files_assert_main_repository(refs, "lock_ref_for_update");23962397 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))2398 update->flags |= REF_DELETING;23992400 if (head_ref) {2401 ret = split_head_update(update, transaction, head_ref,2402 affected_refnames, err);2403 if (ret)2404 goto out;2405 }24062407 ret = lock_raw_ref(refs, update->refname, mustexist,2408 affected_refnames, NULL,2409 &lock, &referent,2410 &update->type, err);2411 if (ret) {2412 char *reason;24132414 reason = strbuf_detach(err, NULL);2415 strbuf_addf(err, "cannot lock ref '%s': %s",2416 original_update_refname(update), reason);2417 free(reason);2418 goto out;2419 }24202421 update->backend_data = lock;24222423 if (update->type & REF_ISSYMREF) {2424 if (update->flags & REF_NO_DEREF) {2425 /*2426 * We won't be reading the referent as part of2427 * the transaction, so we have to read it here2428 * to record and possibly check old_oid:2429 */2430 if (refs_read_ref_full(&refs->base,2431 referent.buf, 0,2432 &lock->old_oid, NULL)) {2433 if (update->flags & REF_HAVE_OLD) {2434 strbuf_addf(err, "cannot lock ref '%s': "2435 "error reading reference",2436 original_update_refname(update));2437 ret = TRANSACTION_GENERIC_ERROR;2438 goto out;2439 }2440 } else if (check_old_oid(update, &lock->old_oid, err)) {2441 ret = TRANSACTION_GENERIC_ERROR;2442 goto out;2443 }2444 } else {2445 /*2446 * Create a new update for the reference this2447 * symref is pointing at. Also, we will record2448 * and verify old_oid for this update as part2449 * of processing the split-off update, so we2450 * don't have to do it here.2451 */2452 ret = split_symref_update(refs, update,2453 referent.buf, transaction,2454 affected_refnames, err);2455 if (ret)2456 goto out;2457 }2458 } else {2459 struct ref_update *parent_update;24602461 if (check_old_oid(update, &lock->old_oid, err)) {2462 ret = TRANSACTION_GENERIC_ERROR;2463 goto out;2464 }24652466 /*2467 * If this update is happening indirectly because of a2468 * symref update, record the old OID in the parent2469 * update:2470 */2471 for (parent_update = update->parent_update;2472 parent_update;2473 parent_update = parent_update->parent_update) {2474 struct ref_lock *parent_lock = parent_update->backend_data;2475 oidcpy(&parent_lock->old_oid, &lock->old_oid);2476 }2477 }24782479 if ((update->flags & REF_HAVE_NEW) &&2480 !(update->flags & REF_DELETING) &&2481 !(update->flags & REF_LOG_ONLY)) {2482 if (!(update->type & REF_ISSYMREF) &&2483 oideq(&lock->old_oid, &update->new_oid)) {2484 /*2485 * The reference already has the desired2486 * value, so we don't need to write it.2487 */2488 } else if (write_ref_to_lockfile(lock, &update->new_oid,2489 err)) {2490 char *write_err = strbuf_detach(err, NULL);24912492 /*2493 * The lock was freed upon failure of2494 * write_ref_to_lockfile():2495 */2496 update->backend_data = NULL;2497 strbuf_addf(err,2498 "cannot update ref '%s': %s",2499 update->refname, write_err);2500 free(write_err);2501 ret = TRANSACTION_GENERIC_ERROR;2502 goto out;2503 } else {2504 update->flags |= REF_NEEDS_COMMIT;2505 }2506 }2507 if (!(update->flags & REF_NEEDS_COMMIT)) {2508 /*2509 * We didn't call write_ref_to_lockfile(), so2510 * the lockfile is still open. Close it to2511 * free up the file descriptor:2512 */2513 if (close_ref_gently(lock)) {2514 strbuf_addf(err, "couldn't close '%s.lock'",2515 update->refname);2516 ret = TRANSACTION_GENERIC_ERROR;2517 goto out;2518 }2519 }25202521out:2522 strbuf_release(&referent);2523 return ret;2524}25252526struct files_transaction_backend_data {2527 struct ref_transaction *packed_transaction;2528 int packed_refs_locked;2529};25302531/*2532 * Unlock any references in `transaction` that are still locked, and2533 * mark the transaction closed.2534 */2535static void files_transaction_cleanup(struct files_ref_store *refs,2536 struct ref_transaction *transaction)2537{2538 size_t i;2539 struct files_transaction_backend_data *backend_data =2540 transaction->backend_data;2541 struct strbuf err = STRBUF_INIT;25422543 for (i = 0; i < transaction->nr; i++) {2544 struct ref_update *update = transaction->updates[i];2545 struct ref_lock *lock = update->backend_data;25462547 if (lock) {2548 unlock_ref(lock);2549 update->backend_data = NULL;2550 }2551 }25522553 if (backend_data->packed_transaction &&2554 ref_transaction_abort(backend_data->packed_transaction, &err)) {2555 error("error aborting transaction: %s", err.buf);2556 strbuf_release(&err);2557 }25582559 if (backend_data->packed_refs_locked)2560 packed_refs_unlock(refs->packed_ref_store);25612562 free(backend_data);25632564 transaction->state = REF_TRANSACTION_CLOSED;2565}25662567static int files_transaction_prepare(struct ref_store *ref_store,2568 struct ref_transaction *transaction,2569 struct strbuf *err)2570{2571 struct files_ref_store *refs =2572 files_downcast(ref_store, REF_STORE_WRITE,2573 "ref_transaction_prepare");2574 size_t i;2575 int ret = 0;2576 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2577 char *head_ref = NULL;2578 int head_type;2579 struct files_transaction_backend_data *backend_data;2580 struct ref_transaction *packed_transaction = NULL;25812582 assert(err);25832584 if (!transaction->nr)2585 goto cleanup;25862587 backend_data = xcalloc(1, sizeof(*backend_data));2588 transaction->backend_data = backend_data;25892590 /*2591 * Fail if a refname appears more than once in the2592 * transaction. (If we end up splitting up any updates using2593 * split_symref_update() or split_head_update(), those2594 * functions will check that the new updates don't have the2595 * same refname as any existing ones.) Also fail if any of the2596 * updates use REF_IS_PRUNING without REF_NO_DEREF.2597 */2598 for (i = 0; i < transaction->nr; i++) {2599 struct ref_update *update = transaction->updates[i];2600 struct string_list_item *item =2601 string_list_append(&affected_refnames, update->refname);26022603 if ((update->flags & REF_IS_PRUNING) &&2604 !(update->flags & REF_NO_DEREF))2605 BUG("REF_IS_PRUNING set without REF_NO_DEREF");26062607 /*2608 * We store a pointer to update in item->util, but at2609 * the moment we never use the value of this field2610 * except to check whether it is non-NULL.2611 */2612 item->util = update;2613 }2614 string_list_sort(&affected_refnames);2615 if (ref_update_reject_duplicates(&affected_refnames, err)) {2616 ret = TRANSACTION_GENERIC_ERROR;2617 goto cleanup;2618 }26192620 /*2621 * Special hack: If a branch is updated directly and HEAD2622 * points to it (may happen on the remote side of a push2623 * for example) then logically the HEAD reflog should be2624 * updated too.2625 *2626 * A generic solution would require reverse symref lookups,2627 * but finding all symrefs pointing to a given branch would be2628 * rather costly for this rare event (the direct update of a2629 * branch) to be worth it. So let's cheat and check with HEAD2630 * only, which should cover 99% of all usage scenarios (even2631 * 100% of the default ones).2632 *2633 * So if HEAD is a symbolic reference, then record the name of2634 * the reference that it points to. If we see an update of2635 * head_ref within the transaction, then split_head_update()2636 * arranges for the reflog of HEAD to be updated, too.2637 */2638 head_ref = refs_resolve_refdup(ref_store, "HEAD",2639 RESOLVE_REF_NO_RECURSE,2640 NULL, &head_type);26412642 if (head_ref && !(head_type & REF_ISSYMREF)) {2643 FREE_AND_NULL(head_ref);2644 }26452646 /*2647 * Acquire all locks, verify old values if provided, check2648 * that new values are valid, and write new values to the2649 * lockfiles, ready to be activated. Only keep one lockfile2650 * open at a time to avoid running out of file descriptors.2651 * Note that lock_ref_for_update() might append more updates2652 * to the transaction.2653 */2654 for (i = 0; i < transaction->nr; i++) {2655 struct ref_update *update = transaction->updates[i];26562657 ret = lock_ref_for_update(refs, update, transaction,2658 head_ref, &affected_refnames, err);2659 if (ret)2660 goto cleanup;26612662 if (update->flags & REF_DELETING &&2663 !(update->flags & REF_LOG_ONLY) &&2664 !(update->flags & REF_IS_PRUNING)) {2665 /*2666 * This reference has to be deleted from2667 * packed-refs if it exists there.2668 */2669 if (!packed_transaction) {2670 packed_transaction = ref_store_transaction_begin(2671 refs->packed_ref_store, err);2672 if (!packed_transaction) {2673 ret = TRANSACTION_GENERIC_ERROR;2674 goto cleanup;2675 }26762677 backend_data->packed_transaction =2678 packed_transaction;2679 }26802681 ref_transaction_add_update(2682 packed_transaction, update->refname,2683 REF_HAVE_NEW | REF_NO_DEREF,2684 &update->new_oid, NULL,2685 NULL);2686 }2687 }26882689 if (packed_transaction) {2690 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {2691 ret = TRANSACTION_GENERIC_ERROR;2692 goto cleanup;2693 }2694 backend_data->packed_refs_locked = 1;26952696 if (is_packed_transaction_needed(refs->packed_ref_store,2697 packed_transaction)) {2698 ret = ref_transaction_prepare(packed_transaction, err);2699 /*2700 * A failure during the prepare step will abort2701 * itself, but not free. Do that now, and disconnect2702 * from the files_transaction so it does not try to2703 * abort us when we hit the cleanup code below.2704 */2705 if (ret) {2706 ref_transaction_free(packed_transaction);2707 backend_data->packed_transaction = NULL;2708 }2709 } else {2710 /*2711 * We can skip rewriting the `packed-refs`2712 * file. But we do need to leave it locked, so2713 * that somebody else doesn't pack a reference2714 * that we are trying to delete.2715 */2716 if (ref_transaction_abort(packed_transaction, err)) {2717 ret = TRANSACTION_GENERIC_ERROR;2718 goto cleanup;2719 }2720 backend_data->packed_transaction = NULL;2721 }2722 }27232724cleanup:2725 free(head_ref);2726 string_list_clear(&affected_refnames, 0);27272728 if (ret)2729 files_transaction_cleanup(refs, transaction);2730 else2731 transaction->state = REF_TRANSACTION_PREPARED;27322733 return ret;2734}27352736static int files_transaction_finish(struct ref_store *ref_store,2737 struct ref_transaction *transaction,2738 struct strbuf *err)2739{2740 struct files_ref_store *refs =2741 files_downcast(ref_store, 0, "ref_transaction_finish");2742 size_t i;2743 int ret = 0;2744 struct strbuf sb = STRBUF_INIT;2745 struct files_transaction_backend_data *backend_data;2746 struct ref_transaction *packed_transaction;274727482749 assert(err);27502751 if (!transaction->nr) {2752 transaction->state = REF_TRANSACTION_CLOSED;2753 return 0;2754 }27552756 backend_data = transaction->backend_data;2757 packed_transaction = backend_data->packed_transaction;27582759 /* Perform updates first so live commits remain referenced */2760 for (i = 0; i < transaction->nr; i++) {2761 struct ref_update *update = transaction->updates[i];2762 struct ref_lock *lock = update->backend_data;27632764 if (update->flags & REF_NEEDS_COMMIT ||2765 update->flags & REF_LOG_ONLY) {2766 if (files_log_ref_write(refs,2767 lock->ref_name,2768 &lock->old_oid,2769 &update->new_oid,2770 update->msg, update->flags,2771 err)) {2772 char *old_msg = strbuf_detach(err, NULL);27732774 strbuf_addf(err, "cannot update the ref '%s': %s",2775 lock->ref_name, old_msg);2776 free(old_msg);2777 unlock_ref(lock);2778 update->backend_data = NULL;2779 ret = TRANSACTION_GENERIC_ERROR;2780 goto cleanup;2781 }2782 }2783 if (update->flags & REF_NEEDS_COMMIT) {2784 clear_loose_ref_cache(refs);2785 if (commit_ref(lock)) {2786 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);2787 unlock_ref(lock);2788 update->backend_data = NULL;2789 ret = TRANSACTION_GENERIC_ERROR;2790 goto cleanup;2791 }2792 }2793 }27942795 /*2796 * Now that updates are safely completed, we can perform2797 * deletes. First delete the reflogs of any references that2798 * will be deleted, since (in the unexpected event of an2799 * error) leaving a reference without a reflog is less bad2800 * than leaving a reflog without a reference (the latter is a2801 * mildly invalid repository state):2802 */2803 for (i = 0; i < transaction->nr; i++) {2804 struct ref_update *update = transaction->updates[i];2805 if (update->flags & REF_DELETING &&2806 !(update->flags & REF_LOG_ONLY) &&2807 !(update->flags & REF_IS_PRUNING)) {2808 strbuf_reset(&sb);2809 files_reflog_path(refs, &sb, update->refname);2810 if (!unlink_or_warn(sb.buf))2811 try_remove_empty_parents(refs, update->refname,2812 REMOVE_EMPTY_PARENTS_REFLOG);2813 }2814 }28152816 /*2817 * Perform deletes now that updates are safely completed.2818 *2819 * First delete any packed versions of the references, while2820 * retaining the packed-refs lock:2821 */2822 if (packed_transaction) {2823 ret = ref_transaction_commit(packed_transaction, err);2824 ref_transaction_free(packed_transaction);2825 packed_transaction = NULL;2826 backend_data->packed_transaction = NULL;2827 if (ret)2828 goto cleanup;2829 }28302831 /* Now delete the loose versions of the references: */2832 for (i = 0; i < transaction->nr; i++) {2833 struct ref_update *update = transaction->updates[i];2834 struct ref_lock *lock = update->backend_data;28352836 if (update->flags & REF_DELETING &&2837 !(update->flags & REF_LOG_ONLY)) {2838 if (!(update->type & REF_ISPACKED) ||2839 update->type & REF_ISSYMREF) {2840 /* It is a loose reference. */2841 strbuf_reset(&sb);2842 files_ref_path(refs, &sb, lock->ref_name);2843 if (unlink_or_msg(sb.buf, err)) {2844 ret = TRANSACTION_GENERIC_ERROR;2845 goto cleanup;2846 }2847 update->flags |= REF_DELETED_LOOSE;2848 }2849 }2850 }28512852 clear_loose_ref_cache(refs);28532854cleanup:2855 files_transaction_cleanup(refs, transaction);28562857 for (i = 0; i < transaction->nr; i++) {2858 struct ref_update *update = transaction->updates[i];28592860 if (update->flags & REF_DELETED_LOOSE) {2861 /*2862 * The loose reference was deleted. Delete any2863 * empty parent directories. (Note that this2864 * can only work because we have already2865 * removed the lockfile.)2866 */2867 try_remove_empty_parents(refs, update->refname,2868 REMOVE_EMPTY_PARENTS_REF);2869 }2870 }28712872 strbuf_release(&sb);2873 return ret;2874}28752876static int files_transaction_abort(struct ref_store *ref_store,2877 struct ref_transaction *transaction,2878 struct strbuf *err)2879{2880 struct files_ref_store *refs =2881 files_downcast(ref_store, 0, "ref_transaction_abort");28822883 files_transaction_cleanup(refs, transaction);2884 return 0;2885}28862887static int ref_present(const char *refname,2888 const struct object_id *oid, int flags, void *cb_data)2889{2890 struct string_list *affected_refnames = cb_data;28912892 return string_list_has_string(affected_refnames, refname);2893}28942895static int files_initial_transaction_commit(struct ref_store *ref_store,2896 struct ref_transaction *transaction,2897 struct strbuf *err)2898{2899 struct files_ref_store *refs =2900 files_downcast(ref_store, REF_STORE_WRITE,2901 "initial_ref_transaction_commit");2902 size_t i;2903 int ret = 0;2904 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2905 struct ref_transaction *packed_transaction = NULL;29062907 assert(err);29082909 if (transaction->state != REF_TRANSACTION_OPEN)2910 BUG("commit called for transaction that is not open");29112912 /* Fail if a refname appears more than once in the transaction: */2913 for (i = 0; i < transaction->nr; i++)2914 string_list_append(&affected_refnames,2915 transaction->updates[i]->refname);2916 string_list_sort(&affected_refnames);2917 if (ref_update_reject_duplicates(&affected_refnames, err)) {2918 ret = TRANSACTION_GENERIC_ERROR;2919 goto cleanup;2920 }29212922 /*2923 * It's really undefined to call this function in an active2924 * repository or when there are existing references: we are2925 * only locking and changing packed-refs, so (1) any2926 * simultaneous processes might try to change a reference at2927 * the same time we do, and (2) any existing loose versions of2928 * the references that we are setting would have precedence2929 * over our values. But some remote helpers create the remote2930 * "HEAD" and "master" branches before calling this function,2931 * so here we really only check that none of the references2932 * that we are creating already exists.2933 */2934 if (refs_for_each_rawref(&refs->base, ref_present,2935 &affected_refnames))2936 BUG("initial ref transaction called with existing refs");29372938 packed_transaction = ref_store_transaction_begin(refs->packed_ref_store, err);2939 if (!packed_transaction) {2940 ret = TRANSACTION_GENERIC_ERROR;2941 goto cleanup;2942 }29432944 for (i = 0; i < transaction->nr; i++) {2945 struct ref_update *update = transaction->updates[i];29462947 if ((update->flags & REF_HAVE_OLD) &&2948 !is_null_oid(&update->old_oid))2949 BUG("initial ref transaction with old_sha1 set");2950 if (refs_verify_refname_available(&refs->base, update->refname,2951 &affected_refnames, NULL,2952 err)) {2953 ret = TRANSACTION_NAME_CONFLICT;2954 goto cleanup;2955 }29562957 /*2958 * Add a reference creation for this reference to the2959 * packed-refs transaction:2960 */2961 ref_transaction_add_update(packed_transaction, update->refname,2962 update->flags & ~REF_HAVE_OLD,2963 &update->new_oid, &update->old_oid,2964 NULL);2965 }29662967 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {2968 ret = TRANSACTION_GENERIC_ERROR;2969 goto cleanup;2970 }29712972 if (initial_ref_transaction_commit(packed_transaction, err)) {2973 ret = TRANSACTION_GENERIC_ERROR;2974 }29752976 packed_refs_unlock(refs->packed_ref_store);2977cleanup:2978 if (packed_transaction)2979 ref_transaction_free(packed_transaction);2980 transaction->state = REF_TRANSACTION_CLOSED;2981 string_list_clear(&affected_refnames, 0);2982 return ret;2983}29842985struct expire_reflog_cb {2986 unsigned int flags;2987 reflog_expiry_should_prune_fn *should_prune_fn;2988 void *policy_cb;2989 FILE *newlog;2990 struct object_id last_kept_oid;2991};29922993static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,2994 const char *email, timestamp_t timestamp, int tz,2995 const char *message, void *cb_data)2996{2997 struct expire_reflog_cb *cb = cb_data;2998 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;29993000 if (cb->flags & EXPIRE_REFLOGS_REWRITE)3001 ooid = &cb->last_kept_oid;30023003 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3004 message, policy_cb)) {3005 if (!cb->newlog)3006 printf("would prune %s", message);3007 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)3008 printf("prune %s", message);3009 } else {3010 if (cb->newlog) {3011 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",3012 oid_to_hex(ooid), oid_to_hex(noid),3013 email, timestamp, tz, message);3014 oidcpy(&cb->last_kept_oid, noid);3015 }3016 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)3017 printf("keep %s", message);3018 }3019 return 0;3020}30213022static int files_reflog_expire(struct ref_store *ref_store,3023 const char *refname, const struct object_id *oid,3024 unsigned int flags,3025 reflog_expiry_prepare_fn prepare_fn,3026 reflog_expiry_should_prune_fn should_prune_fn,3027 reflog_expiry_cleanup_fn cleanup_fn,3028 void *policy_cb_data)3029{3030 struct files_ref_store *refs =3031 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");3032 struct lock_file reflog_lock = LOCK_INIT;3033 struct expire_reflog_cb cb;3034 struct ref_lock *lock;3035 struct strbuf log_file_sb = STRBUF_INIT;3036 char *log_file;3037 int status = 0;3038 int type;3039 struct strbuf err = STRBUF_INIT;30403041 memset(&cb, 0, sizeof(cb));3042 cb.flags = flags;3043 cb.policy_cb = policy_cb_data;3044 cb.should_prune_fn = should_prune_fn;30453046 /*3047 * The reflog file is locked by holding the lock on the3048 * reference itself, plus we might need to update the3049 * reference if --updateref was specified:3050 */3051 lock = lock_ref_oid_basic(refs, refname, oid,3052 NULL, NULL, REF_NO_DEREF,3053 &type, &err);3054 if (!lock) {3055 error("cannot lock ref '%s': %s", refname, err.buf);3056 strbuf_release(&err);3057 return -1;3058 }3059 if (!refs_reflog_exists(ref_store, refname)) {3060 unlock_ref(lock);3061 return 0;3062 }30633064 files_reflog_path(refs, &log_file_sb, refname);3065 log_file = strbuf_detach(&log_file_sb, NULL);3066 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3067 /*3068 * Even though holding $GIT_DIR/logs/$reflog.lock has3069 * no locking implications, we use the lock_file3070 * machinery here anyway because it does a lot of the3071 * work we need, including cleaning up if the program3072 * exits unexpectedly.3073 */3074 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {3075 struct strbuf err = STRBUF_INIT;3076 unable_to_lock_message(log_file, errno, &err);3077 error("%s", err.buf);3078 strbuf_release(&err);3079 goto failure;3080 }3081 cb.newlog = fdopen_lock_file(&reflog_lock, "w");3082 if (!cb.newlog) {3083 error("cannot fdopen %s (%s)",3084 get_lock_file_path(&reflog_lock), strerror(errno));3085 goto failure;3086 }3087 }30883089 (*prepare_fn)(refname, oid, cb.policy_cb);3090 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3091 (*cleanup_fn)(cb.policy_cb);30923093 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3094 /*3095 * It doesn't make sense to adjust a reference pointed3096 * to by a symbolic ref based on expiring entries in3097 * the symbolic reference's reflog. Nor can we update3098 * a reference if there are no remaining reflog3099 * entries.3100 */3101 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3102 !(type & REF_ISSYMREF) &&3103 !is_null_oid(&cb.last_kept_oid);31043105 if (close_lock_file_gently(&reflog_lock)) {3106 status |= error("couldn't write %s: %s", log_file,3107 strerror(errno));3108 rollback_lock_file(&reflog_lock);3109 } else if (update &&3110 (write_in_full(get_lock_file_fd(&lock->lk),3111 oid_to_hex(&cb.last_kept_oid), the_hash_algo->hexsz) < 0 ||3112 write_str_in_full(get_lock_file_fd(&lock->lk), "\n") < 0 ||3113 close_ref_gently(lock) < 0)) {3114 status |= error("couldn't write %s",3115 get_lock_file_path(&lock->lk));3116 rollback_lock_file(&reflog_lock);3117 } else if (commit_lock_file(&reflog_lock)) {3118 status |= error("unable to write reflog '%s' (%s)",3119 log_file, strerror(errno));3120 } else if (update && commit_ref(lock)) {3121 status |= error("couldn't set %s", lock->ref_name);3122 }3123 }3124 free(log_file);3125 unlock_ref(lock);3126 return status;31273128 failure:3129 rollback_lock_file(&reflog_lock);3130 free(log_file);3131 unlock_ref(lock);3132 return -1;3133}31343135static int files_init_db(struct ref_store *ref_store, struct strbuf *err)3136{3137 struct files_ref_store *refs =3138 files_downcast(ref_store, REF_STORE_WRITE, "init_db");3139 struct strbuf sb = STRBUF_INIT;31403141 /*3142 * Create .git/refs/{heads,tags}3143 */3144 files_ref_path(refs, &sb, "refs/heads");3145 safe_create_dir(sb.buf, 1);31463147 strbuf_reset(&sb);3148 files_ref_path(refs, &sb, "refs/tags");3149 safe_create_dir(sb.buf, 1);31503151 strbuf_release(&sb);3152 return 0;3153}31543155struct ref_storage_be refs_be_files = {3156 NULL,3157 "files",3158 files_ref_store_create,3159 files_init_db,3160 files_transaction_prepare,3161 files_transaction_finish,3162 files_transaction_abort,3163 files_initial_transaction_commit,31643165 files_pack_refs,3166 files_create_symref,3167 files_delete_refs,3168 files_rename_ref,3169 files_copy_ref,31703171 files_ref_iterator_begin,3172 files_read_raw_ref,31733174 files_reflog_iterator_begin,3175 files_for_each_reflog_ent,3176 files_for_each_reflog_ent_reverse,3177 files_reflog_exists,3178 files_create_reflog,3179 files_delete_reflog,3180 files_reflog_expire3181};