1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * A container for `packed-refs`-related data. It is not (yet) a 52 * `ref_store`. 53 */ 54struct packed_ref_store { 55unsigned int store_flags; 56 57/* The path of the "packed-refs" file: */ 58char*path; 59 60/* 61 * A cache of the values read from the `packed-refs` file, if 62 * it might still be current; otherwise, NULL. 63 */ 64struct packed_ref_cache *cache; 65 66/* 67 * Lock used for the "packed-refs" file. Note that this (and 68 * thus the enclosing `packed_ref_store`) must not be freed. 69 */ 70struct lock_file lock; 71}; 72 73static struct packed_ref_store *packed_ref_store_create( 74const char*path,unsigned int store_flags) 75{ 76struct packed_ref_store *refs =xcalloc(1,sizeof(*refs)); 77 78 refs->store_flags = store_flags; 79 refs->path =xstrdup(path); 80return refs; 81} 82 83/* 84 * Die if refs is not the main ref store. caller is used in any 85 * necessary error messages. 86 */ 87static voidpacked_assert_main_repository(struct packed_ref_store *refs, 88const char*caller) 89{ 90if(refs->store_flags & REF_STORE_MAIN) 91return; 92 93die("BUG: operation%sonly allowed for main ref store", caller); 94} 95 96/* 97 * Future: need to be in "struct repository" 98 * when doing a full libification. 99 */ 100struct files_ref_store { 101struct ref_store base; 102unsigned int store_flags; 103 104char*gitdir; 105char*gitcommondir; 106 107struct ref_cache *loose; 108 109struct packed_ref_store *packed_ref_store; 110}; 111 112/* 113 * Increment the reference count of *packed_refs. 114 */ 115static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 116{ 117 packed_refs->referrers++; 118} 119 120/* 121 * Decrease the reference count of *packed_refs. If it goes to zero, 122 * free *packed_refs and return true; otherwise return false. 123 */ 124static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 125{ 126if(!--packed_refs->referrers) { 127free_ref_cache(packed_refs->cache); 128stat_validity_clear(&packed_refs->validity); 129free(packed_refs); 130return1; 131}else{ 132return0; 133} 134} 135 136static voidclear_packed_ref_cache(struct packed_ref_store *refs) 137{ 138if(refs->cache) { 139struct packed_ref_cache *cache = refs->cache; 140 141if(is_lock_file_locked(&refs->lock)) 142die("BUG: packed-ref cache cleared while locked"); 143 refs->cache = NULL; 144release_packed_ref_cache(cache); 145} 146} 147 148static voidclear_loose_ref_cache(struct files_ref_store *refs) 149{ 150if(refs->loose) { 151free_ref_cache(refs->loose); 152 refs->loose = NULL; 153} 154} 155 156/* 157 * Create a new submodule ref cache and add it to the internal 158 * set of caches. 159 */ 160static struct ref_store *files_ref_store_create(const char*gitdir, 161unsigned int flags) 162{ 163struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 164struct ref_store *ref_store = (struct ref_store *)refs; 165struct strbuf sb = STRBUF_INIT; 166 167base_ref_store_init(ref_store, &refs_be_files); 168 refs->store_flags = flags; 169 170 refs->gitdir =xstrdup(gitdir); 171get_common_dir_noenv(&sb, gitdir); 172 refs->gitcommondir =strbuf_detach(&sb, NULL); 173strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 174 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 175strbuf_release(&sb); 176 177return ref_store; 178} 179 180/* 181 * Die if refs is not the main ref store. caller is used in any 182 * necessary error messages. 183 */ 184static voidfiles_assert_main_repository(struct files_ref_store *refs, 185const char*caller) 186{ 187if(refs->store_flags & REF_STORE_MAIN) 188return; 189 190die("BUG: operation%sonly allowed for main ref store", caller); 191} 192 193/* 194 * Downcast ref_store to files_ref_store. Die if ref_store is not a 195 * files_ref_store. required_flags is compared with ref_store's 196 * store_flags to ensure the ref_store has all required capabilities. 197 * "caller" is used in any necessary error messages. 198 */ 199static struct files_ref_store *files_downcast(struct ref_store *ref_store, 200unsigned int required_flags, 201const char*caller) 202{ 203struct files_ref_store *refs; 204 205if(ref_store->be != &refs_be_files) 206die("BUG: ref_store is type\"%s\"not\"files\"in%s", 207 ref_store->be->name, caller); 208 209 refs = (struct files_ref_store *)ref_store; 210 211if((refs->store_flags & required_flags) != required_flags) 212die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 213 caller, required_flags, refs->store_flags); 214 215return refs; 216} 217 218/* The length of a peeled reference line in packed-refs, including EOL: */ 219#define PEELED_LINE_LENGTH 42 220 221/* 222 * The packed-refs header line that we write out. Perhaps other 223 * traits will be added later. The trailing space is required. 224 */ 225static const char PACKED_REFS_HEADER[] = 226"# pack-refs with: peeled fully-peeled\n"; 227 228/* 229 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 230 * Return a pointer to the refname within the line (null-terminated), 231 * or NULL if there was a problem. 232 */ 233static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 234{ 235const char*ref; 236 237if(parse_oid_hex(line->buf, oid, &ref) <0) 238return NULL; 239if(!isspace(*ref++)) 240return NULL; 241 242if(isspace(*ref)) 243return NULL; 244 245if(line->buf[line->len -1] !='\n') 246return NULL; 247 line->buf[--line->len] =0; 248 249return ref; 250} 251 252/* 253 * Read from `packed_refs_file` into a newly-allocated 254 * `packed_ref_cache` and return it. The return value will already 255 * have its reference count incremented. 256 * 257 * A comment line of the form "# pack-refs with: " may contain zero or 258 * more traits. We interpret the traits as follows: 259 * 260 * No traits: 261 * 262 * Probably no references are peeled. But if the file contains a 263 * peeled value for a reference, we will use it. 264 * 265 * peeled: 266 * 267 * References under "refs/tags/", if they *can* be peeled, *are* 268 * peeled in this file. References outside of "refs/tags/" are 269 * probably not peeled even if they could have been, but if we find 270 * a peeled value for such a reference we will use it. 271 * 272 * fully-peeled: 273 * 274 * All references in the file that can be peeled are peeled. 275 * Inversely (and this is more important), any references in the 276 * file for which no peeled value is recorded is not peelable. This 277 * trait should typically be written alongside "peeled" for 278 * compatibility with older clients, but we do not require it 279 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 280 */ 281static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 282{ 283FILE*f; 284struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 285struct ref_entry *last = NULL; 286struct strbuf line = STRBUF_INIT; 287enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 288struct ref_dir *dir; 289 290acquire_packed_ref_cache(packed_refs); 291 packed_refs->cache =create_ref_cache(NULL, NULL); 292 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 293 294 f =fopen(packed_refs_file,"r"); 295if(!f) { 296if(errno == ENOENT) { 297/* 298 * This is OK; it just means that no 299 * "packed-refs" file has been written yet, 300 * which is equivalent to it being empty. 301 */ 302return packed_refs; 303}else{ 304die_errno("couldn't read%s", packed_refs_file); 305} 306} 307 308stat_validity_update(&packed_refs->validity,fileno(f)); 309 310 dir =get_ref_dir(packed_refs->cache->root); 311while(strbuf_getwholeline(&line, f,'\n') != EOF) { 312struct object_id oid; 313const char*refname; 314const char*traits; 315 316if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 317if(strstr(traits," fully-peeled ")) 318 peeled = PEELED_FULLY; 319else if(strstr(traits," peeled ")) 320 peeled = PEELED_TAGS; 321/* perhaps other traits later as well */ 322continue; 323} 324 325 refname =parse_ref_line(&line, &oid); 326if(refname) { 327int flag = REF_ISPACKED; 328 329if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 330if(!refname_is_safe(refname)) 331die("packed refname is dangerous:%s", refname); 332oidclr(&oid); 333 flag |= REF_BAD_NAME | REF_ISBROKEN; 334} 335 last =create_ref_entry(refname, &oid, flag); 336if(peeled == PEELED_FULLY || 337(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 338 last->flag |= REF_KNOWS_PEELED; 339add_ref_entry(dir, last); 340continue; 341} 342if(last && 343 line.buf[0] =='^'&& 344 line.len == PEELED_LINE_LENGTH && 345 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 346!get_oid_hex(line.buf +1, &oid)) { 347oidcpy(&last->u.value.peeled, &oid); 348/* 349 * Regardless of what the file header said, 350 * we definitely know the value of *this* 351 * reference: 352 */ 353 last->flag |= REF_KNOWS_PEELED; 354} 355} 356 357fclose(f); 358strbuf_release(&line); 359 360return packed_refs; 361} 362 363static voidfiles_reflog_path(struct files_ref_store *refs, 364struct strbuf *sb, 365const char*refname) 366{ 367if(!refname) { 368/* 369 * FIXME: of course this is wrong in multi worktree 370 * setting. To be fixed real soon. 371 */ 372strbuf_addf(sb,"%s/logs", refs->gitcommondir); 373return; 374} 375 376switch(ref_type(refname)) { 377case REF_TYPE_PER_WORKTREE: 378case REF_TYPE_PSEUDOREF: 379strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 380break; 381case REF_TYPE_NORMAL: 382strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 383break; 384default: 385die("BUG: unknown ref type%dof ref%s", 386ref_type(refname), refname); 387} 388} 389 390static voidfiles_ref_path(struct files_ref_store *refs, 391struct strbuf *sb, 392const char*refname) 393{ 394switch(ref_type(refname)) { 395case REF_TYPE_PER_WORKTREE: 396case REF_TYPE_PSEUDOREF: 397strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 398break; 399case REF_TYPE_NORMAL: 400strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 401break; 402default: 403die("BUG: unknown ref type%dof ref%s", 404ref_type(refname), refname); 405} 406} 407 408/* 409 * Check that the packed refs cache (if any) still reflects the 410 * contents of the file. If not, clear the cache. 411 */ 412static voidvalidate_packed_ref_cache(struct packed_ref_store *refs) 413{ 414if(refs->cache && 415!stat_validity_check(&refs->cache->validity, refs->path)) 416clear_packed_ref_cache(refs); 417} 418 419/* 420 * Get the packed_ref_cache for the specified packed_ref_store, 421 * creating and populating it if it hasn't been read before or if the 422 * file has been changed (according to its `validity` field) since it 423 * was last read. On the other hand, if we hold the lock, then assume 424 * that the file hasn't been changed out from under us, so skip the 425 * extra `stat()` call in `stat_validity_check()`. 426 */ 427static struct packed_ref_cache *get_packed_ref_cache(struct packed_ref_store *refs) 428{ 429if(!is_lock_file_locked(&refs->lock)) 430validate_packed_ref_cache(refs); 431 432if(!refs->cache) 433 refs->cache =read_packed_refs(refs->path); 434 435return refs->cache; 436} 437 438static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 439{ 440returnget_ref_dir(packed_ref_cache->cache->root); 441} 442 443static struct ref_dir *get_packed_refs(struct packed_ref_store *refs) 444{ 445returnget_packed_ref_dir(get_packed_ref_cache(refs)); 446} 447 448/* 449 * Add or overwrite a reference in the in-memory packed reference 450 * cache. This may only be called while the packed-refs file is locked 451 * (see lock_packed_refs()). To actually write the packed-refs file, 452 * call commit_packed_refs(). 453 */ 454static voidadd_packed_ref(struct packed_ref_store *refs, 455const char*refname,const struct object_id *oid) 456{ 457struct ref_dir *packed_refs; 458struct ref_entry *packed_entry; 459 460if(!is_lock_file_locked(&refs->lock)) 461die("BUG: packed refs not locked"); 462 463if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 464die("Reference has invalid format: '%s'", refname); 465 466 packed_refs =get_packed_refs(refs); 467 packed_entry =find_ref_entry(packed_refs, refname); 468if(packed_entry) { 469/* Overwrite the existing entry: */ 470oidcpy(&packed_entry->u.value.oid, oid); 471 packed_entry->flag = REF_ISPACKED; 472oidclr(&packed_entry->u.value.peeled); 473}else{ 474 packed_entry =create_ref_entry(refname, oid, REF_ISPACKED); 475add_ref_entry(packed_refs, packed_entry); 476} 477} 478 479/* 480 * Read the loose references from the namespace dirname into dir 481 * (without recursing). dirname must end with '/'. dir must be the 482 * directory entry corresponding to dirname. 483 */ 484static voidloose_fill_ref_dir(struct ref_store *ref_store, 485struct ref_dir *dir,const char*dirname) 486{ 487struct files_ref_store *refs = 488files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 489DIR*d; 490struct dirent *de; 491int dirnamelen =strlen(dirname); 492struct strbuf refname; 493struct strbuf path = STRBUF_INIT; 494size_t path_baselen; 495 496files_ref_path(refs, &path, dirname); 497 path_baselen = path.len; 498 499 d =opendir(path.buf); 500if(!d) { 501strbuf_release(&path); 502return; 503} 504 505strbuf_init(&refname, dirnamelen +257); 506strbuf_add(&refname, dirname, dirnamelen); 507 508while((de =readdir(d)) != NULL) { 509struct object_id oid; 510struct stat st; 511int flag; 512 513if(de->d_name[0] =='.') 514continue; 515if(ends_with(de->d_name,".lock")) 516continue; 517strbuf_addstr(&refname, de->d_name); 518strbuf_addstr(&path, de->d_name); 519if(stat(path.buf, &st) <0) { 520;/* silently ignore */ 521}else if(S_ISDIR(st.st_mode)) { 522strbuf_addch(&refname,'/'); 523add_entry_to_dir(dir, 524create_dir_entry(dir->cache, refname.buf, 525 refname.len,1)); 526}else{ 527if(!refs_resolve_ref_unsafe(&refs->base, 528 refname.buf, 529 RESOLVE_REF_READING, 530 oid.hash, &flag)) { 531oidclr(&oid); 532 flag |= REF_ISBROKEN; 533}else if(is_null_oid(&oid)) { 534/* 535 * It is so astronomically unlikely 536 * that NULL_SHA1 is the SHA-1 of an 537 * actual object that we consider its 538 * appearance in a loose reference 539 * file to be repo corruption 540 * (probably due to a software bug). 541 */ 542 flag |= REF_ISBROKEN; 543} 544 545if(check_refname_format(refname.buf, 546 REFNAME_ALLOW_ONELEVEL)) { 547if(!refname_is_safe(refname.buf)) 548die("loose refname is dangerous:%s", refname.buf); 549oidclr(&oid); 550 flag |= REF_BAD_NAME | REF_ISBROKEN; 551} 552add_entry_to_dir(dir, 553create_ref_entry(refname.buf, &oid, flag)); 554} 555strbuf_setlen(&refname, dirnamelen); 556strbuf_setlen(&path, path_baselen); 557} 558strbuf_release(&refname); 559strbuf_release(&path); 560closedir(d); 561 562/* 563 * Manually add refs/bisect, which, being per-worktree, might 564 * not appear in the directory listing for refs/ in the main 565 * repo. 566 */ 567if(!strcmp(dirname,"refs/")) { 568int pos =search_ref_dir(dir,"refs/bisect/",12); 569 570if(pos <0) { 571struct ref_entry *child_entry =create_dir_entry( 572 dir->cache,"refs/bisect/",12,1); 573add_entry_to_dir(dir, child_entry); 574} 575} 576} 577 578static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 579{ 580if(!refs->loose) { 581/* 582 * Mark the top-level directory complete because we 583 * are about to read the only subdirectory that can 584 * hold references: 585 */ 586 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 587 588/* We're going to fill the top level ourselves: */ 589 refs->loose->root->flag &= ~REF_INCOMPLETE; 590 591/* 592 * Add an incomplete entry for "refs/" (to be filled 593 * lazily): 594 */ 595add_entry_to_dir(get_ref_dir(refs->loose->root), 596create_dir_entry(refs->loose,"refs/",5,1)); 597} 598return refs->loose; 599} 600 601/* 602 * Return the ref_entry for the given refname from the packed 603 * references. If it does not exist, return NULL. 604 */ 605static struct ref_entry *get_packed_ref(struct packed_ref_store *refs, 606const char*refname) 607{ 608returnfind_ref_entry(get_packed_refs(refs), refname); 609} 610 611static intpacked_read_raw_ref(struct packed_ref_store *refs, 612const char*refname,unsigned char*sha1, 613struct strbuf *referent,unsigned int*type) 614{ 615struct ref_entry *entry; 616 617*type =0; 618 619 entry =get_packed_ref(refs, refname); 620if(!entry) { 621 errno = ENOENT; 622return-1; 623} 624 625hashcpy(sha1, entry->u.value.oid.hash); 626*type = REF_ISPACKED; 627return0; 628} 629 630static intfiles_read_raw_ref(struct ref_store *ref_store, 631const char*refname,unsigned char*sha1, 632struct strbuf *referent,unsigned int*type) 633{ 634struct files_ref_store *refs = 635files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 636struct strbuf sb_contents = STRBUF_INIT; 637struct strbuf sb_path = STRBUF_INIT; 638const char*path; 639const char*buf; 640struct stat st; 641int fd; 642int ret = -1; 643int save_errno; 644int remaining_retries =3; 645 646*type =0; 647strbuf_reset(&sb_path); 648 649files_ref_path(refs, &sb_path, refname); 650 651 path = sb_path.buf; 652 653stat_ref: 654/* 655 * We might have to loop back here to avoid a race 656 * condition: first we lstat() the file, then we try 657 * to read it as a link or as a file. But if somebody 658 * changes the type of the file (file <-> directory 659 * <-> symlink) between the lstat() and reading, then 660 * we don't want to report that as an error but rather 661 * try again starting with the lstat(). 662 * 663 * We'll keep a count of the retries, though, just to avoid 664 * any confusing situation sending us into an infinite loop. 665 */ 666 667if(remaining_retries-- <=0) 668goto out; 669 670if(lstat(path, &st) <0) { 671if(errno != ENOENT) 672goto out; 673if(packed_read_raw_ref(refs->packed_ref_store, refname, 674 sha1, referent, type)) { 675 errno = ENOENT; 676goto out; 677} 678 ret =0; 679goto out; 680} 681 682/* Follow "normalized" - ie "refs/.." symlinks by hand */ 683if(S_ISLNK(st.st_mode)) { 684strbuf_reset(&sb_contents); 685if(strbuf_readlink(&sb_contents, path,0) <0) { 686if(errno == ENOENT || errno == EINVAL) 687/* inconsistent with lstat; retry */ 688goto stat_ref; 689else 690goto out; 691} 692if(starts_with(sb_contents.buf,"refs/") && 693!check_refname_format(sb_contents.buf,0)) { 694strbuf_swap(&sb_contents, referent); 695*type |= REF_ISSYMREF; 696 ret =0; 697goto out; 698} 699/* 700 * It doesn't look like a refname; fall through to just 701 * treating it like a non-symlink, and reading whatever it 702 * points to. 703 */ 704} 705 706/* Is it a directory? */ 707if(S_ISDIR(st.st_mode)) { 708/* 709 * Even though there is a directory where the loose 710 * ref is supposed to be, there could still be a 711 * packed ref: 712 */ 713if(packed_read_raw_ref(refs->packed_ref_store, refname, 714 sha1, referent, type)) { 715 errno = EISDIR; 716goto out; 717} 718 ret =0; 719goto out; 720} 721 722/* 723 * Anything else, just open it and try to use it as 724 * a ref 725 */ 726 fd =open(path, O_RDONLY); 727if(fd <0) { 728if(errno == ENOENT && !S_ISLNK(st.st_mode)) 729/* inconsistent with lstat; retry */ 730goto stat_ref; 731else 732goto out; 733} 734strbuf_reset(&sb_contents); 735if(strbuf_read(&sb_contents, fd,256) <0) { 736int save_errno = errno; 737close(fd); 738 errno = save_errno; 739goto out; 740} 741close(fd); 742strbuf_rtrim(&sb_contents); 743 buf = sb_contents.buf; 744if(starts_with(buf,"ref:")) { 745 buf +=4; 746while(isspace(*buf)) 747 buf++; 748 749strbuf_reset(referent); 750strbuf_addstr(referent, buf); 751*type |= REF_ISSYMREF; 752 ret =0; 753goto out; 754} 755 756/* 757 * Please note that FETCH_HEAD has additional 758 * data after the sha. 759 */ 760if(get_sha1_hex(buf, sha1) || 761(buf[40] !='\0'&& !isspace(buf[40]))) { 762*type |= REF_ISBROKEN; 763 errno = EINVAL; 764goto out; 765} 766 767 ret =0; 768 769out: 770 save_errno = errno; 771strbuf_release(&sb_path); 772strbuf_release(&sb_contents); 773 errno = save_errno; 774return ret; 775} 776 777static voidunlock_ref(struct ref_lock *lock) 778{ 779/* Do not free lock->lk -- atexit() still looks at them */ 780if(lock->lk) 781rollback_lock_file(lock->lk); 782free(lock->ref_name); 783free(lock); 784} 785 786/* 787 * Lock refname, without following symrefs, and set *lock_p to point 788 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 789 * and type similarly to read_raw_ref(). 790 * 791 * The caller must verify that refname is a "safe" reference name (in 792 * the sense of refname_is_safe()) before calling this function. 793 * 794 * If the reference doesn't already exist, verify that refname doesn't 795 * have a D/F conflict with any existing references. extras and skip 796 * are passed to refs_verify_refname_available() for this check. 797 * 798 * If mustexist is not set and the reference is not found or is 799 * broken, lock the reference anyway but clear sha1. 800 * 801 * Return 0 on success. On failure, write an error message to err and 802 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 803 * 804 * Implementation note: This function is basically 805 * 806 * lock reference 807 * read_raw_ref() 808 * 809 * but it includes a lot more code to 810 * - Deal with possible races with other processes 811 * - Avoid calling refs_verify_refname_available() when it can be 812 * avoided, namely if we were successfully able to read the ref 813 * - Generate informative error messages in the case of failure 814 */ 815static intlock_raw_ref(struct files_ref_store *refs, 816const char*refname,int mustexist, 817const struct string_list *extras, 818const struct string_list *skip, 819struct ref_lock **lock_p, 820struct strbuf *referent, 821unsigned int*type, 822struct strbuf *err) 823{ 824struct ref_lock *lock; 825struct strbuf ref_file = STRBUF_INIT; 826int attempts_remaining =3; 827int ret = TRANSACTION_GENERIC_ERROR; 828 829assert(err); 830files_assert_main_repository(refs,"lock_raw_ref"); 831 832*type =0; 833 834/* First lock the file so it can't change out from under us. */ 835 836*lock_p = lock =xcalloc(1,sizeof(*lock)); 837 838 lock->ref_name =xstrdup(refname); 839files_ref_path(refs, &ref_file, refname); 840 841retry: 842switch(safe_create_leading_directories(ref_file.buf)) { 843case SCLD_OK: 844break;/* success */ 845case SCLD_EXISTS: 846/* 847 * Suppose refname is "refs/foo/bar". We just failed 848 * to create the containing directory, "refs/foo", 849 * because there was a non-directory in the way. This 850 * indicates a D/F conflict, probably because of 851 * another reference such as "refs/foo". There is no 852 * reason to expect this error to be transitory. 853 */ 854if(refs_verify_refname_available(&refs->base, refname, 855 extras, skip, err)) { 856if(mustexist) { 857/* 858 * To the user the relevant error is 859 * that the "mustexist" reference is 860 * missing: 861 */ 862strbuf_reset(err); 863strbuf_addf(err,"unable to resolve reference '%s'", 864 refname); 865}else{ 866/* 867 * The error message set by 868 * refs_verify_refname_available() is 869 * OK. 870 */ 871 ret = TRANSACTION_NAME_CONFLICT; 872} 873}else{ 874/* 875 * The file that is in the way isn't a loose 876 * reference. Report it as a low-level 877 * failure. 878 */ 879strbuf_addf(err,"unable to create lock file%s.lock; " 880"non-directory in the way", 881 ref_file.buf); 882} 883goto error_return; 884case SCLD_VANISHED: 885/* Maybe another process was tidying up. Try again. */ 886if(--attempts_remaining >0) 887goto retry; 888/* fall through */ 889default: 890strbuf_addf(err,"unable to create directory for%s", 891 ref_file.buf); 892goto error_return; 893} 894 895if(!lock->lk) 896 lock->lk =xcalloc(1,sizeof(struct lock_file)); 897 898if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 899if(errno == ENOENT && --attempts_remaining >0) { 900/* 901 * Maybe somebody just deleted one of the 902 * directories leading to ref_file. Try 903 * again: 904 */ 905goto retry; 906}else{ 907unable_to_lock_message(ref_file.buf, errno, err); 908goto error_return; 909} 910} 911 912/* 913 * Now we hold the lock and can read the reference without 914 * fear that its value will change. 915 */ 916 917if(files_read_raw_ref(&refs->base, refname, 918 lock->old_oid.hash, referent, type)) { 919if(errno == ENOENT) { 920if(mustexist) { 921/* Garden variety missing reference. */ 922strbuf_addf(err,"unable to resolve reference '%s'", 923 refname); 924goto error_return; 925}else{ 926/* 927 * Reference is missing, but that's OK. We 928 * know that there is not a conflict with 929 * another loose reference because 930 * (supposing that we are trying to lock 931 * reference "refs/foo/bar"): 932 * 933 * - We were successfully able to create 934 * the lockfile refs/foo/bar.lock, so we 935 * know there cannot be a loose reference 936 * named "refs/foo". 937 * 938 * - We got ENOENT and not EISDIR, so we 939 * know that there cannot be a loose 940 * reference named "refs/foo/bar/baz". 941 */ 942} 943}else if(errno == EISDIR) { 944/* 945 * There is a directory in the way. It might have 946 * contained references that have been deleted. If 947 * we don't require that the reference already 948 * exists, try to remove the directory so that it 949 * doesn't cause trouble when we want to rename the 950 * lockfile into place later. 951 */ 952if(mustexist) { 953/* Garden variety missing reference. */ 954strbuf_addf(err,"unable to resolve reference '%s'", 955 refname); 956goto error_return; 957}else if(remove_dir_recursively(&ref_file, 958 REMOVE_DIR_EMPTY_ONLY)) { 959if(refs_verify_refname_available( 960&refs->base, refname, 961 extras, skip, err)) { 962/* 963 * The error message set by 964 * verify_refname_available() is OK. 965 */ 966 ret = TRANSACTION_NAME_CONFLICT; 967goto error_return; 968}else{ 969/* 970 * We can't delete the directory, 971 * but we also don't know of any 972 * references that it should 973 * contain. 974 */ 975strbuf_addf(err,"there is a non-empty directory '%s' " 976"blocking reference '%s'", 977 ref_file.buf, refname); 978goto error_return; 979} 980} 981}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 982strbuf_addf(err,"unable to resolve reference '%s': " 983"reference broken", refname); 984goto error_return; 985}else{ 986strbuf_addf(err,"unable to resolve reference '%s':%s", 987 refname,strerror(errno)); 988goto error_return; 989} 990 991/* 992 * If the ref did not exist and we are creating it, 993 * make sure there is no existing ref that conflicts 994 * with refname: 995 */ 996if(refs_verify_refname_available( 997&refs->base, refname, 998 extras, skip, err)) 999goto error_return;1000}10011002 ret =0;1003goto out;10041005error_return:1006unlock_ref(lock);1007*lock_p = NULL;10081009out:1010strbuf_release(&ref_file);1011return ret;1012}10131014static intpacked_peel_ref(struct packed_ref_store *refs,1015const char*refname,unsigned char*sha1)1016{1017struct ref_entry *r =get_packed_ref(refs, refname);10181019if(!r ||peel_entry(r,0))1020return-1;10211022hashcpy(sha1, r->u.value.peeled.hash);1023return0;1024}10251026static intfiles_peel_ref(struct ref_store *ref_store,1027const char*refname,unsigned char*sha1)1028{1029struct files_ref_store *refs =1030files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,1031"peel_ref");1032int flag;1033unsigned char base[20];10341035if(current_ref_iter && current_ref_iter->refname == refname) {1036struct object_id peeled;10371038if(ref_iterator_peel(current_ref_iter, &peeled))1039return-1;1040hashcpy(sha1, peeled.hash);1041return0;1042}10431044if(refs_read_ref_full(ref_store, refname,1045 RESOLVE_REF_READING, base, &flag))1046return-1;10471048/*1049 * If the reference is packed, read its ref_entry from the1050 * cache in the hope that we already know its peeled value.1051 * We only try this optimization on packed references because1052 * (a) forcing the filling of the loose reference cache could1053 * be expensive and (b) loose references anyway usually do not1054 * have REF_KNOWS_PEELED.1055 */1056if(flag & REF_ISPACKED &&1057!packed_peel_ref(refs->packed_ref_store, refname, sha1))1058return0;10591060returnpeel_object(base, sha1);1061}10621063struct packed_ref_iterator {1064struct ref_iterator base;10651066struct packed_ref_cache *cache;1067struct ref_iterator *iter0;1068unsigned int flags;1069};10701071static intpacked_ref_iterator_advance(struct ref_iterator *ref_iterator)1072{1073struct packed_ref_iterator *iter =1074(struct packed_ref_iterator *)ref_iterator;1075int ok;10761077while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1078if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1079ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1080continue;10811082if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1083!ref_resolves_to_object(iter->iter0->refname,1084 iter->iter0->oid,1085 iter->iter0->flags))1086continue;10871088 iter->base.refname = iter->iter0->refname;1089 iter->base.oid = iter->iter0->oid;1090 iter->base.flags = iter->iter0->flags;1091return ITER_OK;1092}10931094 iter->iter0 = NULL;1095if(ref_iterator_abort(ref_iterator) != ITER_DONE)1096 ok = ITER_ERROR;10971098return ok;1099}11001101static intpacked_ref_iterator_peel(struct ref_iterator *ref_iterator,1102struct object_id *peeled)1103{1104struct packed_ref_iterator *iter =1105(struct packed_ref_iterator *)ref_iterator;11061107returnref_iterator_peel(iter->iter0, peeled);1108}11091110static intpacked_ref_iterator_abort(struct ref_iterator *ref_iterator)1111{1112struct packed_ref_iterator *iter =1113(struct packed_ref_iterator *)ref_iterator;1114int ok = ITER_DONE;11151116if(iter->iter0)1117 ok =ref_iterator_abort(iter->iter0);11181119release_packed_ref_cache(iter->cache);1120base_ref_iterator_free(ref_iterator);1121return ok;1122}11231124static struct ref_iterator_vtable packed_ref_iterator_vtable = {1125 packed_ref_iterator_advance,1126 packed_ref_iterator_peel,1127 packed_ref_iterator_abort1128};11291130static struct ref_iterator *packed_ref_iterator_begin(1131struct packed_ref_store *refs,1132const char*prefix,unsigned int flags)1133{1134struct packed_ref_iterator *iter;1135struct ref_iterator *ref_iterator;11361137 iter =xcalloc(1,sizeof(*iter));1138 ref_iterator = &iter->base;1139base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable);11401141/*1142 * Note that get_packed_ref_cache() internally checks whether1143 * the packed-ref cache is up to date with what is on disk,1144 * and re-reads it if not.1145 */11461147 iter->cache =get_packed_ref_cache(refs);1148acquire_packed_ref_cache(iter->cache);1149 iter->iter0 =cache_ref_iterator_begin(iter->cache->cache, prefix,0);11501151 iter->flags = flags;11521153return ref_iterator;1154}11551156struct files_ref_iterator {1157struct ref_iterator base;11581159struct ref_iterator *iter0;1160unsigned int flags;1161};11621163static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1164{1165struct files_ref_iterator *iter =1166(struct files_ref_iterator *)ref_iterator;1167int ok;11681169while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1170if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1171ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1172continue;11731174if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1175!ref_resolves_to_object(iter->iter0->refname,1176 iter->iter0->oid,1177 iter->iter0->flags))1178continue;11791180 iter->base.refname = iter->iter0->refname;1181 iter->base.oid = iter->iter0->oid;1182 iter->base.flags = iter->iter0->flags;1183return ITER_OK;1184}11851186 iter->iter0 = NULL;1187if(ref_iterator_abort(ref_iterator) != ITER_DONE)1188 ok = ITER_ERROR;11891190return ok;1191}11921193static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1194struct object_id *peeled)1195{1196struct files_ref_iterator *iter =1197(struct files_ref_iterator *)ref_iterator;11981199returnref_iterator_peel(iter->iter0, peeled);1200}12011202static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1203{1204struct files_ref_iterator *iter =1205(struct files_ref_iterator *)ref_iterator;1206int ok = ITER_DONE;12071208if(iter->iter0)1209 ok =ref_iterator_abort(iter->iter0);12101211base_ref_iterator_free(ref_iterator);1212return ok;1213}12141215static struct ref_iterator_vtable files_ref_iterator_vtable = {1216 files_ref_iterator_advance,1217 files_ref_iterator_peel,1218 files_ref_iterator_abort1219};12201221static struct ref_iterator *files_ref_iterator_begin(1222struct ref_store *ref_store,1223const char*prefix,unsigned int flags)1224{1225struct files_ref_store *refs;1226struct ref_iterator *loose_iter, *packed_iter;1227struct files_ref_iterator *iter;1228struct ref_iterator *ref_iterator;1229unsigned int required_flags = REF_STORE_READ;12301231if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1232 required_flags |= REF_STORE_ODB;12331234 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");12351236 iter =xcalloc(1,sizeof(*iter));1237 ref_iterator = &iter->base;1238base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);12391240/*1241 * We must make sure that all loose refs are read before1242 * accessing the packed-refs file; this avoids a race1243 * condition if loose refs are migrated to the packed-refs1244 * file by a simultaneous process, but our in-memory view is1245 * from before the migration. We ensure this as follows:1246 * First, we call start the loose refs iteration with its1247 * `prime_ref` argument set to true. This causes the loose1248 * references in the subtree to be pre-read into the cache.1249 * (If they've already been read, that's OK; we only need to1250 * guarantee that they're read before the packed refs, not1251 * *how much* before.) After that, we call1252 * packed_ref_iterator_begin(), which internally checks1253 * whether the packed-ref cache is up to date with what is on1254 * disk, and re-reads it if not.1255 */12561257 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1258 prefix,1);12591260/*1261 * The packed-refs file might contain broken references, for1262 * example an old version of a reference that points at an1263 * object that has since been garbage-collected. This is OK as1264 * long as there is a corresponding loose reference that1265 * overrides it, and we don't want to emit an error message in1266 * this case. So ask the packed_ref_store for all of its1267 * references, and (if needed) do our own check for broken1268 * ones in files_ref_iterator_advance(), after we have merged1269 * the packed and loose references.1270 */1271 packed_iter =packed_ref_iterator_begin(1272 refs->packed_ref_store, prefix,1273 DO_FOR_EACH_INCLUDE_BROKEN);12741275 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1276 iter->flags = flags;12771278return ref_iterator;1279}12801281/*1282 * Verify that the reference locked by lock has the value old_sha1.1283 * Fail if the reference doesn't exist and mustexist is set. Return 01284 * on success. On error, write an error message to err, set errno, and1285 * return a negative value.1286 */1287static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1288const unsigned char*old_sha1,int mustexist,1289struct strbuf *err)1290{1291assert(err);12921293if(refs_read_ref_full(ref_store, lock->ref_name,1294 mustexist ? RESOLVE_REF_READING :0,1295 lock->old_oid.hash, NULL)) {1296if(old_sha1) {1297int save_errno = errno;1298strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1299 errno = save_errno;1300return-1;1301}else{1302oidclr(&lock->old_oid);1303return0;1304}1305}1306if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1307strbuf_addf(err,"ref '%s' is at%sbut expected%s",1308 lock->ref_name,1309oid_to_hex(&lock->old_oid),1310sha1_to_hex(old_sha1));1311 errno = EBUSY;1312return-1;1313}1314return0;1315}13161317static intremove_empty_directories(struct strbuf *path)1318{1319/*1320 * we want to create a file but there is a directory there;1321 * if that is an empty directory (or a directory that contains1322 * only empty directories), remove them.1323 */1324returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1325}13261327static intcreate_reflock(const char*path,void*cb)1328{1329struct lock_file *lk = cb;13301331returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1332}13331334/*1335 * Locks a ref returning the lock on success and NULL on failure.1336 * On failure errno is set to something meaningful.1337 */1338static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1339const char*refname,1340const unsigned char*old_sha1,1341const struct string_list *extras,1342const struct string_list *skip,1343unsigned int flags,int*type,1344struct strbuf *err)1345{1346struct strbuf ref_file = STRBUF_INIT;1347struct ref_lock *lock;1348int last_errno =0;1349int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1350int resolve_flags = RESOLVE_REF_NO_RECURSE;1351int resolved;13521353files_assert_main_repository(refs,"lock_ref_sha1_basic");1354assert(err);13551356 lock =xcalloc(1,sizeof(struct ref_lock));13571358if(mustexist)1359 resolve_flags |= RESOLVE_REF_READING;1360if(flags & REF_DELETING)1361 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;13621363files_ref_path(refs, &ref_file, refname);1364 resolved = !!refs_resolve_ref_unsafe(&refs->base,1365 refname, resolve_flags,1366 lock->old_oid.hash, type);1367if(!resolved && errno == EISDIR) {1368/*1369 * we are trying to lock foo but we used to1370 * have foo/bar which now does not exist;1371 * it is normal for the empty directory 'foo'1372 * to remain.1373 */1374if(remove_empty_directories(&ref_file)) {1375 last_errno = errno;1376if(!refs_verify_refname_available(1377&refs->base,1378 refname, extras, skip, err))1379strbuf_addf(err,"there are still refs under '%s'",1380 refname);1381goto error_return;1382}1383 resolved = !!refs_resolve_ref_unsafe(&refs->base,1384 refname, resolve_flags,1385 lock->old_oid.hash, type);1386}1387if(!resolved) {1388 last_errno = errno;1389if(last_errno != ENOTDIR ||1390!refs_verify_refname_available(&refs->base, refname,1391 extras, skip, err))1392strbuf_addf(err,"unable to resolve reference '%s':%s",1393 refname,strerror(last_errno));13941395goto error_return;1396}13971398/*1399 * If the ref did not exist and we are creating it, make sure1400 * there is no existing packed ref whose name begins with our1401 * refname, nor a packed ref whose name is a proper prefix of1402 * our refname.1403 */1404if(is_null_oid(&lock->old_oid) &&1405refs_verify_refname_available(&refs->base, refname,1406 extras, skip, err)) {1407 last_errno = ENOTDIR;1408goto error_return;1409}14101411 lock->lk =xcalloc(1,sizeof(struct lock_file));14121413 lock->ref_name =xstrdup(refname);14141415if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1416 last_errno = errno;1417unable_to_lock_message(ref_file.buf, errno, err);1418goto error_return;1419}14201421if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1422 last_errno = errno;1423goto error_return;1424}1425goto out;14261427 error_return:1428unlock_ref(lock);1429 lock = NULL;14301431 out:1432strbuf_release(&ref_file);1433 errno = last_errno;1434return lock;1435}14361437/*1438 * Write an entry to the packed-refs file for the specified refname.1439 * If peeled is non-NULL, write it as the entry's peeled value.1440 */1441static voidwrite_packed_entry(FILE*fh,const char*refname,1442const unsigned char*sha1,1443const unsigned char*peeled)1444{1445fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1446if(peeled)1447fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1448}14491450/*1451 * Lock the packed-refs file for writing. Flags is passed to1452 * hold_lock_file_for_update(). Return 0 on success. On errors, set1453 * errno appropriately and return a nonzero value.1454 */1455static intlock_packed_refs(struct packed_ref_store *refs,int flags)1456{1457static int timeout_configured =0;1458static int timeout_value =1000;1459struct packed_ref_cache *packed_ref_cache;14601461packed_assert_main_repository(refs,"lock_packed_refs");14621463if(!timeout_configured) {1464git_config_get_int("core.packedrefstimeout", &timeout_value);1465 timeout_configured =1;1466}14671468if(hold_lock_file_for_update_timeout(1469&refs->lock,1470 refs->path,1471 flags, timeout_value) <0)1472return-1;14731474/*1475 * Now that we hold the `packed-refs` lock, make sure that our1476 * cache matches the current version of the file. Normally1477 * `get_packed_ref_cache()` does that for us, but that1478 * function assumes that when the file is locked, any existing1479 * cache is still valid. We've just locked the file, but it1480 * might have changed the moment *before* we locked it.1481 */1482validate_packed_ref_cache(refs);14831484 packed_ref_cache =get_packed_ref_cache(refs);1485/* Increment the reference count to prevent it from being freed: */1486acquire_packed_ref_cache(packed_ref_cache);1487return0;1488}14891490/*1491 * Write the current version of the packed refs cache from memory to1492 * disk. The packed-refs file must already be locked for writing (see1493 * lock_packed_refs()). Return zero on success. On errors, set errno1494 * and return a nonzero value1495 */1496static intcommit_packed_refs(struct packed_ref_store *refs)1497{1498struct packed_ref_cache *packed_ref_cache =1499get_packed_ref_cache(refs);1500int ok, error =0;1501int save_errno =0;1502FILE*out;1503struct ref_iterator *iter;15041505packed_assert_main_repository(refs,"commit_packed_refs");15061507if(!is_lock_file_locked(&refs->lock))1508die("BUG: packed-refs not locked");15091510 out =fdopen_lock_file(&refs->lock,"w");1511if(!out)1512die_errno("unable to fdopen packed-refs descriptor");15131514fprintf_or_die(out,"%s", PACKED_REFS_HEADER);15151516 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1517while((ok =ref_iterator_advance(iter)) == ITER_OK) {1518struct object_id peeled;1519int peel_error =ref_iterator_peel(iter, &peeled);15201521write_packed_entry(out, iter->refname, iter->oid->hash,1522 peel_error ? NULL : peeled.hash);1523}15241525if(ok != ITER_DONE)1526die("error while iterating over references");15271528if(commit_lock_file(&refs->lock)) {1529 save_errno = errno;1530 error = -1;1531}1532release_packed_ref_cache(packed_ref_cache);1533 errno = save_errno;1534return error;1535}15361537/*1538 * Rollback the lockfile for the packed-refs file, and discard the1539 * in-memory packed reference cache. (The packed-refs file will be1540 * read anew if it is needed again after this function is called.)1541 */1542static voidrollback_packed_refs(struct packed_ref_store *refs)1543{1544struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs);15451546packed_assert_main_repository(refs,"rollback_packed_refs");15471548if(!is_lock_file_locked(&refs->lock))1549die("BUG: packed-refs not locked");1550rollback_lock_file(&refs->lock);1551release_packed_ref_cache(packed_ref_cache);1552clear_packed_ref_cache(refs);1553}15541555struct ref_to_prune {1556struct ref_to_prune *next;1557unsigned char sha1[20];1558char name[FLEX_ARRAY];1559};15601561enum{1562 REMOVE_EMPTY_PARENTS_REF =0x01,1563 REMOVE_EMPTY_PARENTS_REFLOG =0x021564};15651566/*1567 * Remove empty parent directories associated with the specified1568 * reference and/or its reflog, but spare [logs/]refs/ and immediate1569 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1570 * REMOVE_EMPTY_PARENTS_REFLOG.1571 */1572static voidtry_remove_empty_parents(struct files_ref_store *refs,1573const char*refname,1574unsigned int flags)1575{1576struct strbuf buf = STRBUF_INIT;1577struct strbuf sb = STRBUF_INIT;1578char*p, *q;1579int i;15801581strbuf_addstr(&buf, refname);1582 p = buf.buf;1583for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1584while(*p && *p !='/')1585 p++;1586/* tolerate duplicate slashes; see check_refname_format() */1587while(*p =='/')1588 p++;1589}1590 q = buf.buf + buf.len;1591while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1592while(q > p && *q !='/')1593 q--;1594while(q > p && *(q-1) =='/')1595 q--;1596if(q == p)1597break;1598strbuf_setlen(&buf, q - buf.buf);15991600strbuf_reset(&sb);1601files_ref_path(refs, &sb, buf.buf);1602if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1603 flags &= ~REMOVE_EMPTY_PARENTS_REF;16041605strbuf_reset(&sb);1606files_reflog_path(refs, &sb, buf.buf);1607if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1608 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1609}1610strbuf_release(&buf);1611strbuf_release(&sb);1612}16131614/* make sure nobody touched the ref, and unlink */1615static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1616{1617struct ref_transaction *transaction;1618struct strbuf err = STRBUF_INIT;16191620if(check_refname_format(r->name,0))1621return;16221623 transaction =ref_store_transaction_begin(&refs->base, &err);1624if(!transaction ||1625ref_transaction_delete(transaction, r->name, r->sha1,1626 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1627ref_transaction_commit(transaction, &err)) {1628ref_transaction_free(transaction);1629error("%s", err.buf);1630strbuf_release(&err);1631return;1632}1633ref_transaction_free(transaction);1634strbuf_release(&err);1635}16361637static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1638{1639while(r) {1640prune_ref(refs, r);1641 r = r->next;1642}1643}16441645/*1646 * Return true if the specified reference should be packed.1647 */1648static intshould_pack_ref(const char*refname,1649const struct object_id *oid,unsigned int ref_flags,1650unsigned int pack_flags)1651{1652/* Do not pack per-worktree refs: */1653if(ref_type(refname) != REF_TYPE_NORMAL)1654return0;16551656/* Do not pack non-tags unless PACK_REFS_ALL is set: */1657if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1658return0;16591660/* Do not pack symbolic refs: */1661if(ref_flags & REF_ISSYMREF)1662return0;16631664/* Do not pack broken refs: */1665if(!ref_resolves_to_object(refname, oid, ref_flags))1666return0;16671668return1;1669}16701671static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1672{1673struct files_ref_store *refs =1674files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1675"pack_refs");1676struct ref_iterator *iter;1677int ok;1678struct ref_to_prune *refs_to_prune = NULL;16791680lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);16811682 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1683while((ok =ref_iterator_advance(iter)) == ITER_OK) {1684/*1685 * If the loose reference can be packed, add an entry1686 * in the packed ref cache. If the reference should be1687 * pruned, also add it to refs_to_prune.1688 */1689if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1690 flags))1691continue;16921693/*1694 * Create an entry in the packed-refs cache equivalent1695 * to the one from the loose ref cache, except that1696 * we don't copy the peeled status, because we want it1697 * to be re-peeled.1698 */1699add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);17001701/* Schedule the loose reference for pruning if requested. */1702if((flags & PACK_REFS_PRUNE)) {1703struct ref_to_prune *n;1704FLEX_ALLOC_STR(n, name, iter->refname);1705hashcpy(n->sha1, iter->oid->hash);1706 n->next = refs_to_prune;1707 refs_to_prune = n;1708}1709}1710if(ok != ITER_DONE)1711die("error while iterating over references");17121713if(commit_packed_refs(refs->packed_ref_store))1714die_errno("unable to overwrite old ref-pack file");17151716prune_refs(refs, refs_to_prune);1717return0;1718}17191720/*1721 * Rewrite the packed-refs file, omitting any refs listed in1722 * 'refnames'. On error, leave packed-refs unchanged, write an error1723 * message to 'err', and return a nonzero value.1724 *1725 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1726 */1727static intrepack_without_refs(struct packed_ref_store *refs,1728struct string_list *refnames,struct strbuf *err)1729{1730struct ref_dir *packed;1731struct string_list_item *refname;1732int ret, needs_repacking =0, removed =0;17331734packed_assert_main_repository(refs,"repack_without_refs");1735assert(err);17361737/* Look for a packed ref */1738for_each_string_list_item(refname, refnames) {1739if(get_packed_ref(refs, refname->string)) {1740 needs_repacking =1;1741break;1742}1743}17441745/* Avoid locking if we have nothing to do */1746if(!needs_repacking)1747return0;/* no refname exists in packed refs */17481749if(lock_packed_refs(refs,0)) {1750unable_to_lock_message(refs->path, errno, err);1751return-1;1752}1753 packed =get_packed_refs(refs);17541755/* Remove refnames from the cache */1756for_each_string_list_item(refname, refnames)1757if(remove_entry_from_dir(packed, refname->string) != -1)1758 removed =1;1759if(!removed) {1760/*1761 * All packed entries disappeared while we were1762 * acquiring the lock.1763 */1764rollback_packed_refs(refs);1765return0;1766}17671768/* Write what remains */1769 ret =commit_packed_refs(refs);1770if(ret)1771strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1772strerror(errno));1773return ret;1774}17751776static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1777struct string_list *refnames,unsigned int flags)1778{1779struct files_ref_store *refs =1780files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1781struct strbuf err = STRBUF_INIT;1782int i, result =0;17831784if(!refnames->nr)1785return0;17861787 result =repack_without_refs(refs->packed_ref_store, refnames, &err);1788if(result) {1789/*1790 * If we failed to rewrite the packed-refs file, then1791 * it is unsafe to try to remove loose refs, because1792 * doing so might expose an obsolete packed value for1793 * a reference that might even point at an object that1794 * has been garbage collected.1795 */1796if(refnames->nr ==1)1797error(_("could not delete reference%s:%s"),1798 refnames->items[0].string, err.buf);1799else1800error(_("could not delete references:%s"), err.buf);18011802goto out;1803}18041805for(i =0; i < refnames->nr; i++) {1806const char*refname = refnames->items[i].string;18071808if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1809 result |=error(_("could not remove reference%s"), refname);1810}18111812out:1813strbuf_release(&err);1814return result;1815}18161817/*1818 * People using contrib's git-new-workdir have .git/logs/refs ->1819 * /some/other/path/.git/logs/refs, and that may live on another device.1820 *1821 * IOW, to avoid cross device rename errors, the temporary renamed log must1822 * live into logs/refs.1823 */1824#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"18251826struct rename_cb {1827const char*tmp_renamed_log;1828int true_errno;1829};18301831static intrename_tmp_log_callback(const char*path,void*cb_data)1832{1833struct rename_cb *cb = cb_data;18341835if(rename(cb->tmp_renamed_log, path)) {1836/*1837 * rename(a, b) when b is an existing directory ought1838 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1839 * Sheesh. Record the true errno for error reporting,1840 * but report EISDIR to raceproof_create_file() so1841 * that it knows to retry.1842 */1843 cb->true_errno = errno;1844if(errno == ENOTDIR)1845 errno = EISDIR;1846return-1;1847}else{1848return0;1849}1850}18511852static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1853{1854struct strbuf path = STRBUF_INIT;1855struct strbuf tmp = STRBUF_INIT;1856struct rename_cb cb;1857int ret;18581859files_reflog_path(refs, &path, newrefname);1860files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1861 cb.tmp_renamed_log = tmp.buf;1862 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1863if(ret) {1864if(errno == EISDIR)1865error("directory not empty:%s", path.buf);1866else1867error("unable to move logfile%sto%s:%s",1868 tmp.buf, path.buf,1869strerror(cb.true_errno));1870}18711872strbuf_release(&path);1873strbuf_release(&tmp);1874return ret;1875}18761877static intwrite_ref_to_lockfile(struct ref_lock *lock,1878const struct object_id *oid,struct strbuf *err);1879static intcommit_ref_update(struct files_ref_store *refs,1880struct ref_lock *lock,1881const struct object_id *oid,const char*logmsg,1882struct strbuf *err);18831884static intfiles_rename_ref(struct ref_store *ref_store,1885const char*oldrefname,const char*newrefname,1886const char*logmsg)1887{1888struct files_ref_store *refs =1889files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1890struct object_id oid, orig_oid;1891int flag =0, logmoved =0;1892struct ref_lock *lock;1893struct stat loginfo;1894struct strbuf sb_oldref = STRBUF_INIT;1895struct strbuf sb_newref = STRBUF_INIT;1896struct strbuf tmp_renamed_log = STRBUF_INIT;1897int log, ret;1898struct strbuf err = STRBUF_INIT;18991900files_reflog_path(refs, &sb_oldref, oldrefname);1901files_reflog_path(refs, &sb_newref, newrefname);1902files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);19031904 log = !lstat(sb_oldref.buf, &loginfo);1905if(log &&S_ISLNK(loginfo.st_mode)) {1906 ret =error("reflog for%sis a symlink", oldrefname);1907goto out;1908}19091910if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1911 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1912 orig_oid.hash, &flag)) {1913 ret =error("refname%snot found", oldrefname);1914goto out;1915}19161917if(flag & REF_ISSYMREF) {1918 ret =error("refname%sis a symbolic ref, renaming it is not supported",1919 oldrefname);1920goto out;1921}1922if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1923 ret =1;1924goto out;1925}19261927if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1928 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1929 oldrefname,strerror(errno));1930goto out;1931}19321933if(refs_delete_ref(&refs->base, logmsg, oldrefname,1934 orig_oid.hash, REF_NODEREF)) {1935error("unable to delete old%s", oldrefname);1936goto rollback;1937}19381939/*1940 * Since we are doing a shallow lookup, oid is not the1941 * correct value to pass to delete_ref as old_oid. But that1942 * doesn't matter, because an old_oid check wouldn't add to1943 * the safety anyway; we want to delete the reference whatever1944 * its current value.1945 */1946if(!refs_read_ref_full(&refs->base, newrefname,1947 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1948 oid.hash, NULL) &&1949refs_delete_ref(&refs->base, NULL, newrefname,1950 NULL, REF_NODEREF)) {1951if(errno == EISDIR) {1952struct strbuf path = STRBUF_INIT;1953int result;19541955files_ref_path(refs, &path, newrefname);1956 result =remove_empty_directories(&path);1957strbuf_release(&path);19581959if(result) {1960error("Directory not empty:%s", newrefname);1961goto rollback;1962}1963}else{1964error("unable to delete existing%s", newrefname);1965goto rollback;1966}1967}19681969if(log &&rename_tmp_log(refs, newrefname))1970goto rollback;19711972 logmoved = log;19731974 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1975 REF_NODEREF, NULL, &err);1976if(!lock) {1977error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1978strbuf_release(&err);1979goto rollback;1980}1981oidcpy(&lock->old_oid, &orig_oid);19821983if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1984commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1985error("unable to write current sha1 into%s:%s", newrefname, err.buf);1986strbuf_release(&err);1987goto rollback;1988}19891990 ret =0;1991goto out;19921993 rollback:1994 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1995 REF_NODEREF, NULL, &err);1996if(!lock) {1997error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1998strbuf_release(&err);1999goto rollbacklog;2000}20012002 flag = log_all_ref_updates;2003 log_all_ref_updates = LOG_REFS_NONE;2004if(write_ref_to_lockfile(lock, &orig_oid, &err) ||2005commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {2006error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2007strbuf_release(&err);2008}2009 log_all_ref_updates = flag;20102011 rollbacklog:2012if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))2013error("unable to restore logfile%sfrom%s:%s",2014 oldrefname, newrefname,strerror(errno));2015if(!logmoved && log &&2016rename(tmp_renamed_log.buf, sb_oldref.buf))2017error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",2018 oldrefname,strerror(errno));2019 ret =1;2020 out:2021strbuf_release(&sb_newref);2022strbuf_release(&sb_oldref);2023strbuf_release(&tmp_renamed_log);20242025return ret;2026}20272028static intclose_ref(struct ref_lock *lock)2029{2030if(close_lock_file(lock->lk))2031return-1;2032return0;2033}20342035static intcommit_ref(struct ref_lock *lock)2036{2037char*path =get_locked_file_path(lock->lk);2038struct stat st;20392040if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2041/*2042 * There is a directory at the path we want to rename2043 * the lockfile to. Hopefully it is empty; try to2044 * delete it.2045 */2046size_t len =strlen(path);2047struct strbuf sb_path = STRBUF_INIT;20482049strbuf_attach(&sb_path, path, len, len);20502051/*2052 * If this fails, commit_lock_file() will also fail2053 * and will report the problem.2054 */2055remove_empty_directories(&sb_path);2056strbuf_release(&sb_path);2057}else{2058free(path);2059}20602061if(commit_lock_file(lock->lk))2062return-1;2063return0;2064}20652066static intopen_or_create_logfile(const char*path,void*cb)2067{2068int*fd = cb;20692070*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);2071return(*fd <0) ? -1:0;2072}20732074/*2075 * Create a reflog for a ref. If force_create = 0, only create the2076 * reflog for certain refs (those for which should_autocreate_reflog2077 * returns non-zero). Otherwise, create it regardless of the reference2078 * name. If the logfile already existed or was created, return 0 and2079 * set *logfd to the file descriptor opened for appending to the file.2080 * If no logfile exists and we decided not to create one, return 0 and2081 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and2082 * return -1.2083 */2084static intlog_ref_setup(struct files_ref_store *refs,2085const char*refname,int force_create,2086int*logfd,struct strbuf *err)2087{2088struct strbuf logfile_sb = STRBUF_INIT;2089char*logfile;20902091files_reflog_path(refs, &logfile_sb, refname);2092 logfile =strbuf_detach(&logfile_sb, NULL);20932094if(force_create ||should_autocreate_reflog(refname)) {2095if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {2096if(errno == ENOENT)2097strbuf_addf(err,"unable to create directory for '%s': "2098"%s", logfile,strerror(errno));2099else if(errno == EISDIR)2100strbuf_addf(err,"there are still logs under '%s'",2101 logfile);2102else2103strbuf_addf(err,"unable to append to '%s':%s",2104 logfile,strerror(errno));21052106goto error;2107}2108}else{2109*logfd =open(logfile, O_APPEND | O_WRONLY,0666);2110if(*logfd <0) {2111if(errno == ENOENT || errno == EISDIR) {2112/*2113 * The logfile doesn't already exist,2114 * but that is not an error; it only2115 * means that we won't write log2116 * entries to it.2117 */2118;2119}else{2120strbuf_addf(err,"unable to append to '%s':%s",2121 logfile,strerror(errno));2122goto error;2123}2124}2125}21262127if(*logfd >=0)2128adjust_shared_perm(logfile);21292130free(logfile);2131return0;21322133error:2134free(logfile);2135return-1;2136}21372138static intfiles_create_reflog(struct ref_store *ref_store,2139const char*refname,int force_create,2140struct strbuf *err)2141{2142struct files_ref_store *refs =2143files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2144int fd;21452146if(log_ref_setup(refs, refname, force_create, &fd, err))2147return-1;21482149if(fd >=0)2150close(fd);21512152return0;2153}21542155static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2156const struct object_id *new_oid,2157const char*committer,const char*msg)2158{2159int msglen, written;2160unsigned maxlen, len;2161char*logrec;21622163 msglen = msg ?strlen(msg) :0;2164 maxlen =strlen(committer) + msglen +100;2165 logrec =xmalloc(maxlen);2166 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2167oid_to_hex(old_oid),2168oid_to_hex(new_oid),2169 committer);2170if(msglen)2171 len +=copy_reflog_msg(logrec + len -1, msg) -1;21722173 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2174free(logrec);2175if(written != len)2176return-1;21772178return0;2179}21802181static intfiles_log_ref_write(struct files_ref_store *refs,2182const char*refname,const struct object_id *old_oid,2183const struct object_id *new_oid,const char*msg,2184int flags,struct strbuf *err)2185{2186int logfd, result;21872188if(log_all_ref_updates == LOG_REFS_UNSET)2189 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;21902191 result =log_ref_setup(refs, refname,2192 flags & REF_FORCE_CREATE_REFLOG,2193&logfd, err);21942195if(result)2196return result;21972198if(logfd <0)2199return0;2200 result =log_ref_write_fd(logfd, old_oid, new_oid,2201git_committer_info(0), msg);2202if(result) {2203struct strbuf sb = STRBUF_INIT;2204int save_errno = errno;22052206files_reflog_path(refs, &sb, refname);2207strbuf_addf(err,"unable to append to '%s':%s",2208 sb.buf,strerror(save_errno));2209strbuf_release(&sb);2210close(logfd);2211return-1;2212}2213if(close(logfd)) {2214struct strbuf sb = STRBUF_INIT;2215int save_errno = errno;22162217files_reflog_path(refs, &sb, refname);2218strbuf_addf(err,"unable to append to '%s':%s",2219 sb.buf,strerror(save_errno));2220strbuf_release(&sb);2221return-1;2222}2223return0;2224}22252226/*2227 * Write sha1 into the open lockfile, then close the lockfile. On2228 * errors, rollback the lockfile, fill in *err and2229 * return -1.2230 */2231static intwrite_ref_to_lockfile(struct ref_lock *lock,2232const struct object_id *oid,struct strbuf *err)2233{2234static char term ='\n';2235struct object *o;2236int fd;22372238 o =parse_object(oid);2239if(!o) {2240strbuf_addf(err,2241"trying to write ref '%s' with nonexistent object%s",2242 lock->ref_name,oid_to_hex(oid));2243unlock_ref(lock);2244return-1;2245}2246if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2247strbuf_addf(err,2248"trying to write non-commit object%sto branch '%s'",2249oid_to_hex(oid), lock->ref_name);2250unlock_ref(lock);2251return-1;2252}2253 fd =get_lock_file_fd(lock->lk);2254if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2255write_in_full(fd, &term,1) !=1||2256close_ref(lock) <0) {2257strbuf_addf(err,2258"couldn't write '%s'",get_lock_file_path(lock->lk));2259unlock_ref(lock);2260return-1;2261}2262return0;2263}22642265/*2266 * Commit a change to a loose reference that has already been written2267 * to the loose reference lockfile. Also update the reflogs if2268 * necessary, using the specified lockmsg (which can be NULL).2269 */2270static intcommit_ref_update(struct files_ref_store *refs,2271struct ref_lock *lock,2272const struct object_id *oid,const char*logmsg,2273struct strbuf *err)2274{2275files_assert_main_repository(refs,"commit_ref_update");22762277clear_loose_ref_cache(refs);2278if(files_log_ref_write(refs, lock->ref_name,2279&lock->old_oid, oid,2280 logmsg,0, err)) {2281char*old_msg =strbuf_detach(err, NULL);2282strbuf_addf(err,"cannot update the ref '%s':%s",2283 lock->ref_name, old_msg);2284free(old_msg);2285unlock_ref(lock);2286return-1;2287}22882289if(strcmp(lock->ref_name,"HEAD") !=0) {2290/*2291 * Special hack: If a branch is updated directly and HEAD2292 * points to it (may happen on the remote side of a push2293 * for example) then logically the HEAD reflog should be2294 * updated too.2295 * A generic solution implies reverse symref information,2296 * but finding all symrefs pointing to the given branch2297 * would be rather costly for this rare event (the direct2298 * update of a branch) to be worth it. So let's cheat and2299 * check with HEAD only which should cover 99% of all usage2300 * scenarios (even 100% of the default ones).2301 */2302struct object_id head_oid;2303int head_flag;2304const char*head_ref;23052306 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2307 RESOLVE_REF_READING,2308 head_oid.hash, &head_flag);2309if(head_ref && (head_flag & REF_ISSYMREF) &&2310!strcmp(head_ref, lock->ref_name)) {2311struct strbuf log_err = STRBUF_INIT;2312if(files_log_ref_write(refs,"HEAD",2313&lock->old_oid, oid,2314 logmsg,0, &log_err)) {2315error("%s", log_err.buf);2316strbuf_release(&log_err);2317}2318}2319}23202321if(commit_ref(lock)) {2322strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2323unlock_ref(lock);2324return-1;2325}23262327unlock_ref(lock);2328return0;2329}23302331static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2332{2333int ret = -1;2334#ifndef NO_SYMLINK_HEAD2335char*ref_path =get_locked_file_path(lock->lk);2336unlink(ref_path);2337 ret =symlink(target, ref_path);2338free(ref_path);23392340if(ret)2341fprintf(stderr,"no symlink - falling back to symbolic ref\n");2342#endif2343return ret;2344}23452346static voidupdate_symref_reflog(struct files_ref_store *refs,2347struct ref_lock *lock,const char*refname,2348const char*target,const char*logmsg)2349{2350struct strbuf err = STRBUF_INIT;2351struct object_id new_oid;2352if(logmsg &&2353!refs_read_ref_full(&refs->base, target,2354 RESOLVE_REF_READING, new_oid.hash, NULL) &&2355files_log_ref_write(refs, refname, &lock->old_oid,2356&new_oid, logmsg,0, &err)) {2357error("%s", err.buf);2358strbuf_release(&err);2359}2360}23612362static intcreate_symref_locked(struct files_ref_store *refs,2363struct ref_lock *lock,const char*refname,2364const char*target,const char*logmsg)2365{2366if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2367update_symref_reflog(refs, lock, refname, target, logmsg);2368return0;2369}23702371if(!fdopen_lock_file(lock->lk,"w"))2372returnerror("unable to fdopen%s:%s",2373 lock->lk->tempfile.filename.buf,strerror(errno));23742375update_symref_reflog(refs, lock, refname, target, logmsg);23762377/* no error check; commit_ref will check ferror */2378fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2379if(commit_ref(lock) <0)2380returnerror("unable to write symref for%s:%s", refname,2381strerror(errno));2382return0;2383}23842385static intfiles_create_symref(struct ref_store *ref_store,2386const char*refname,const char*target,2387const char*logmsg)2388{2389struct files_ref_store *refs =2390files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2391struct strbuf err = STRBUF_INIT;2392struct ref_lock *lock;2393int ret;23942395 lock =lock_ref_sha1_basic(refs, refname, NULL,2396 NULL, NULL, REF_NODEREF, NULL,2397&err);2398if(!lock) {2399error("%s", err.buf);2400strbuf_release(&err);2401return-1;2402}24032404 ret =create_symref_locked(refs, lock, refname, target, logmsg);2405unlock_ref(lock);2406return ret;2407}24082409static intfiles_reflog_exists(struct ref_store *ref_store,2410const char*refname)2411{2412struct files_ref_store *refs =2413files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2414struct strbuf sb = STRBUF_INIT;2415struct stat st;2416int ret;24172418files_reflog_path(refs, &sb, refname);2419 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2420strbuf_release(&sb);2421return ret;2422}24232424static intfiles_delete_reflog(struct ref_store *ref_store,2425const char*refname)2426{2427struct files_ref_store *refs =2428files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2429struct strbuf sb = STRBUF_INIT;2430int ret;24312432files_reflog_path(refs, &sb, refname);2433 ret =remove_path(sb.buf);2434strbuf_release(&sb);2435return ret;2436}24372438static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2439{2440struct object_id ooid, noid;2441char*email_end, *message;2442 timestamp_t timestamp;2443int tz;2444const char*p = sb->buf;24452446/* old SP new SP name <email> SP time TAB msg LF */2447if(!sb->len || sb->buf[sb->len -1] !='\n'||2448parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2449parse_oid_hex(p, &noid, &p) || *p++ !=' '||2450!(email_end =strchr(p,'>')) ||2451 email_end[1] !=' '||2452!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2453!message || message[0] !=' '||2454(message[1] !='+'&& message[1] !='-') ||2455!isdigit(message[2]) || !isdigit(message[3]) ||2456!isdigit(message[4]) || !isdigit(message[5]))2457return0;/* corrupt? */2458 email_end[1] ='\0';2459 tz =strtol(message +1, NULL,10);2460if(message[6] !='\t')2461 message +=6;2462else2463 message +=7;2464returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2465}24662467static char*find_beginning_of_line(char*bob,char*scan)2468{2469while(bob < scan && *(--scan) !='\n')2470;/* keep scanning backwards */2471/*2472 * Return either beginning of the buffer, or LF at the end of2473 * the previous line.2474 */2475return scan;2476}24772478static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2479const char*refname,2480 each_reflog_ent_fn fn,2481void*cb_data)2482{2483struct files_ref_store *refs =2484files_downcast(ref_store, REF_STORE_READ,2485"for_each_reflog_ent_reverse");2486struct strbuf sb = STRBUF_INIT;2487FILE*logfp;2488long pos;2489int ret =0, at_tail =1;24902491files_reflog_path(refs, &sb, refname);2492 logfp =fopen(sb.buf,"r");2493strbuf_release(&sb);2494if(!logfp)2495return-1;24962497/* Jump to the end */2498if(fseek(logfp,0, SEEK_END) <0)2499 ret =error("cannot seek back reflog for%s:%s",2500 refname,strerror(errno));2501 pos =ftell(logfp);2502while(!ret &&0< pos) {2503int cnt;2504size_t nread;2505char buf[BUFSIZ];2506char*endp, *scanp;25072508/* Fill next block from the end */2509 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2510if(fseek(logfp, pos - cnt, SEEK_SET)) {2511 ret =error("cannot seek back reflog for%s:%s",2512 refname,strerror(errno));2513break;2514}2515 nread =fread(buf, cnt,1, logfp);2516if(nread !=1) {2517 ret =error("cannot read%dbytes from reflog for%s:%s",2518 cnt, refname,strerror(errno));2519break;2520}2521 pos -= cnt;25222523 scanp = endp = buf + cnt;2524if(at_tail && scanp[-1] =='\n')2525/* Looking at the final LF at the end of the file */2526 scanp--;2527 at_tail =0;25282529while(buf < scanp) {2530/*2531 * terminating LF of the previous line, or the beginning2532 * of the buffer.2533 */2534char*bp;25352536 bp =find_beginning_of_line(buf, scanp);25372538if(*bp =='\n') {2539/*2540 * The newline is the end of the previous line,2541 * so we know we have complete line starting2542 * at (bp + 1). Prefix it onto any prior data2543 * we collected for the line and process it.2544 */2545strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2546 scanp = bp;2547 endp = bp +1;2548 ret =show_one_reflog_ent(&sb, fn, cb_data);2549strbuf_reset(&sb);2550if(ret)2551break;2552}else if(!pos) {2553/*2554 * We are at the start of the buffer, and the2555 * start of the file; there is no previous2556 * line, and we have everything for this one.2557 * Process it, and we can end the loop.2558 */2559strbuf_splice(&sb,0,0, buf, endp - buf);2560 ret =show_one_reflog_ent(&sb, fn, cb_data);2561strbuf_reset(&sb);2562break;2563}25642565if(bp == buf) {2566/*2567 * We are at the start of the buffer, and there2568 * is more file to read backwards. Which means2569 * we are in the middle of a line. Note that we2570 * may get here even if *bp was a newline; that2571 * just means we are at the exact end of the2572 * previous line, rather than some spot in the2573 * middle.2574 *2575 * Save away what we have to be combined with2576 * the data from the next read.2577 */2578strbuf_splice(&sb,0,0, buf, endp - buf);2579break;2580}2581}25822583}2584if(!ret && sb.len)2585die("BUG: reverse reflog parser had leftover data");25862587fclose(logfp);2588strbuf_release(&sb);2589return ret;2590}25912592static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2593const char*refname,2594 each_reflog_ent_fn fn,void*cb_data)2595{2596struct files_ref_store *refs =2597files_downcast(ref_store, REF_STORE_READ,2598"for_each_reflog_ent");2599FILE*logfp;2600struct strbuf sb = STRBUF_INIT;2601int ret =0;26022603files_reflog_path(refs, &sb, refname);2604 logfp =fopen(sb.buf,"r");2605strbuf_release(&sb);2606if(!logfp)2607return-1;26082609while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2610 ret =show_one_reflog_ent(&sb, fn, cb_data);2611fclose(logfp);2612strbuf_release(&sb);2613return ret;2614}26152616struct files_reflog_iterator {2617struct ref_iterator base;26182619struct ref_store *ref_store;2620struct dir_iterator *dir_iterator;2621struct object_id oid;2622};26232624static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2625{2626struct files_reflog_iterator *iter =2627(struct files_reflog_iterator *)ref_iterator;2628struct dir_iterator *diter = iter->dir_iterator;2629int ok;26302631while((ok =dir_iterator_advance(diter)) == ITER_OK) {2632int flags;26332634if(!S_ISREG(diter->st.st_mode))2635continue;2636if(diter->basename[0] =='.')2637continue;2638if(ends_with(diter->basename,".lock"))2639continue;26402641if(refs_read_ref_full(iter->ref_store,2642 diter->relative_path,0,2643 iter->oid.hash, &flags)) {2644error("bad ref for%s", diter->path.buf);2645continue;2646}26472648 iter->base.refname = diter->relative_path;2649 iter->base.oid = &iter->oid;2650 iter->base.flags = flags;2651return ITER_OK;2652}26532654 iter->dir_iterator = NULL;2655if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2656 ok = ITER_ERROR;2657return ok;2658}26592660static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2661struct object_id *peeled)2662{2663die("BUG: ref_iterator_peel() called for reflog_iterator");2664}26652666static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2667{2668struct files_reflog_iterator *iter =2669(struct files_reflog_iterator *)ref_iterator;2670int ok = ITER_DONE;26712672if(iter->dir_iterator)2673 ok =dir_iterator_abort(iter->dir_iterator);26742675base_ref_iterator_free(ref_iterator);2676return ok;2677}26782679static struct ref_iterator_vtable files_reflog_iterator_vtable = {2680 files_reflog_iterator_advance,2681 files_reflog_iterator_peel,2682 files_reflog_iterator_abort2683};26842685static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2686{2687struct files_ref_store *refs =2688files_downcast(ref_store, REF_STORE_READ,2689"reflog_iterator_begin");2690struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2691struct ref_iterator *ref_iterator = &iter->base;2692struct strbuf sb = STRBUF_INIT;26932694base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2695files_reflog_path(refs, &sb, NULL);2696 iter->dir_iterator =dir_iterator_begin(sb.buf);2697 iter->ref_store = ref_store;2698strbuf_release(&sb);2699return ref_iterator;2700}27012702/*2703 * If update is a direct update of head_ref (the reference pointed to2704 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2705 */2706static intsplit_head_update(struct ref_update *update,2707struct ref_transaction *transaction,2708const char*head_ref,2709struct string_list *affected_refnames,2710struct strbuf *err)2711{2712struct string_list_item *item;2713struct ref_update *new_update;27142715if((update->flags & REF_LOG_ONLY) ||2716(update->flags & REF_ISPRUNING) ||2717(update->flags & REF_UPDATE_VIA_HEAD))2718return0;27192720if(strcmp(update->refname, head_ref))2721return0;27222723/*2724 * First make sure that HEAD is not already in the2725 * transaction. This insertion is O(N) in the transaction2726 * size, but it happens at most once per transaction.2727 */2728 item =string_list_insert(affected_refnames,"HEAD");2729if(item->util) {2730/* An entry already existed */2731strbuf_addf(err,2732"multiple updates for 'HEAD' (including one "2733"via its referent '%s') are not allowed",2734 update->refname);2735return TRANSACTION_NAME_CONFLICT;2736}27372738 new_update =ref_transaction_add_update(2739 transaction,"HEAD",2740 update->flags | REF_LOG_ONLY | REF_NODEREF,2741 update->new_oid.hash, update->old_oid.hash,2742 update->msg);27432744 item->util = new_update;27452746return0;2747}27482749/*2750 * update is for a symref that points at referent and doesn't have2751 * REF_NODEREF set. Split it into two updates:2752 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2753 * - A new, separate update for the referent reference2754 * Note that the new update will itself be subject to splitting when2755 * the iteration gets to it.2756 */2757static intsplit_symref_update(struct files_ref_store *refs,2758struct ref_update *update,2759const char*referent,2760struct ref_transaction *transaction,2761struct string_list *affected_refnames,2762struct strbuf *err)2763{2764struct string_list_item *item;2765struct ref_update *new_update;2766unsigned int new_flags;27672768/*2769 * First make sure that referent is not already in the2770 * transaction. This insertion is O(N) in the transaction2771 * size, but it happens at most once per symref in a2772 * transaction.2773 */2774 item =string_list_insert(affected_refnames, referent);2775if(item->util) {2776/* An entry already existed */2777strbuf_addf(err,2778"multiple updates for '%s' (including one "2779"via symref '%s') are not allowed",2780 referent, update->refname);2781return TRANSACTION_NAME_CONFLICT;2782}27832784 new_flags = update->flags;2785if(!strcmp(update->refname,"HEAD")) {2786/*2787 * Record that the new update came via HEAD, so that2788 * when we process it, split_head_update() doesn't try2789 * to add another reflog update for HEAD. Note that2790 * this bit will be propagated if the new_update2791 * itself needs to be split.2792 */2793 new_flags |= REF_UPDATE_VIA_HEAD;2794}27952796 new_update =ref_transaction_add_update(2797 transaction, referent, new_flags,2798 update->new_oid.hash, update->old_oid.hash,2799 update->msg);28002801 new_update->parent_update = update;28022803/*2804 * Change the symbolic ref update to log only. Also, it2805 * doesn't need to check its old SHA-1 value, as that will be2806 * done when new_update is processed.2807 */2808 update->flags |= REF_LOG_ONLY | REF_NODEREF;2809 update->flags &= ~REF_HAVE_OLD;28102811 item->util = new_update;28122813return0;2814}28152816/*2817 * Return the refname under which update was originally requested.2818 */2819static const char*original_update_refname(struct ref_update *update)2820{2821while(update->parent_update)2822 update = update->parent_update;28232824return update->refname;2825}28262827/*2828 * Check whether the REF_HAVE_OLD and old_oid values stored in update2829 * are consistent with oid, which is the reference's current value. If2830 * everything is OK, return 0; otherwise, write an error message to2831 * err and return -1.2832 */2833static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2834struct strbuf *err)2835{2836if(!(update->flags & REF_HAVE_OLD) ||2837!oidcmp(oid, &update->old_oid))2838return0;28392840if(is_null_oid(&update->old_oid))2841strbuf_addf(err,"cannot lock ref '%s': "2842"reference already exists",2843original_update_refname(update));2844else if(is_null_oid(oid))2845strbuf_addf(err,"cannot lock ref '%s': "2846"reference is missing but expected%s",2847original_update_refname(update),2848oid_to_hex(&update->old_oid));2849else2850strbuf_addf(err,"cannot lock ref '%s': "2851"is at%sbut expected%s",2852original_update_refname(update),2853oid_to_hex(oid),2854oid_to_hex(&update->old_oid));28552856return-1;2857}28582859/*2860 * Prepare for carrying out update:2861 * - Lock the reference referred to by update.2862 * - Read the reference under lock.2863 * - Check that its old SHA-1 value (if specified) is correct, and in2864 * any case record it in update->lock->old_oid for later use when2865 * writing the reflog.2866 * - If it is a symref update without REF_NODEREF, split it up into a2867 * REF_LOG_ONLY update of the symref and add a separate update for2868 * the referent to transaction.2869 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2870 * update of HEAD.2871 */2872static intlock_ref_for_update(struct files_ref_store *refs,2873struct ref_update *update,2874struct ref_transaction *transaction,2875const char*head_ref,2876struct string_list *affected_refnames,2877struct strbuf *err)2878{2879struct strbuf referent = STRBUF_INIT;2880int mustexist = (update->flags & REF_HAVE_OLD) &&2881!is_null_oid(&update->old_oid);2882int ret;2883struct ref_lock *lock;28842885files_assert_main_repository(refs,"lock_ref_for_update");28862887if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2888 update->flags |= REF_DELETING;28892890if(head_ref) {2891 ret =split_head_update(update, transaction, head_ref,2892 affected_refnames, err);2893if(ret)2894return ret;2895}28962897 ret =lock_raw_ref(refs, update->refname, mustexist,2898 affected_refnames, NULL,2899&lock, &referent,2900&update->type, err);2901if(ret) {2902char*reason;29032904 reason =strbuf_detach(err, NULL);2905strbuf_addf(err,"cannot lock ref '%s':%s",2906original_update_refname(update), reason);2907free(reason);2908return ret;2909}29102911 update->backend_data = lock;29122913if(update->type & REF_ISSYMREF) {2914if(update->flags & REF_NODEREF) {2915/*2916 * We won't be reading the referent as part of2917 * the transaction, so we have to read it here2918 * to record and possibly check old_sha1:2919 */2920if(refs_read_ref_full(&refs->base,2921 referent.buf,0,2922 lock->old_oid.hash, NULL)) {2923if(update->flags & REF_HAVE_OLD) {2924strbuf_addf(err,"cannot lock ref '%s': "2925"error reading reference",2926original_update_refname(update));2927return-1;2928}2929}else if(check_old_oid(update, &lock->old_oid, err)) {2930return TRANSACTION_GENERIC_ERROR;2931}2932}else{2933/*2934 * Create a new update for the reference this2935 * symref is pointing at. Also, we will record2936 * and verify old_sha1 for this update as part2937 * of processing the split-off update, so we2938 * don't have to do it here.2939 */2940 ret =split_symref_update(refs, update,2941 referent.buf, transaction,2942 affected_refnames, err);2943if(ret)2944return ret;2945}2946}else{2947struct ref_update *parent_update;29482949if(check_old_oid(update, &lock->old_oid, err))2950return TRANSACTION_GENERIC_ERROR;29512952/*2953 * If this update is happening indirectly because of a2954 * symref update, record the old SHA-1 in the parent2955 * update:2956 */2957for(parent_update = update->parent_update;2958 parent_update;2959 parent_update = parent_update->parent_update) {2960struct ref_lock *parent_lock = parent_update->backend_data;2961oidcpy(&parent_lock->old_oid, &lock->old_oid);2962}2963}29642965if((update->flags & REF_HAVE_NEW) &&2966!(update->flags & REF_DELETING) &&2967!(update->flags & REF_LOG_ONLY)) {2968if(!(update->type & REF_ISSYMREF) &&2969!oidcmp(&lock->old_oid, &update->new_oid)) {2970/*2971 * The reference already has the desired2972 * value, so we don't need to write it.2973 */2974}else if(write_ref_to_lockfile(lock, &update->new_oid,2975 err)) {2976char*write_err =strbuf_detach(err, NULL);29772978/*2979 * The lock was freed upon failure of2980 * write_ref_to_lockfile():2981 */2982 update->backend_data = NULL;2983strbuf_addf(err,2984"cannot update ref '%s':%s",2985 update->refname, write_err);2986free(write_err);2987return TRANSACTION_GENERIC_ERROR;2988}else{2989 update->flags |= REF_NEEDS_COMMIT;2990}2991}2992if(!(update->flags & REF_NEEDS_COMMIT)) {2993/*2994 * We didn't call write_ref_to_lockfile(), so2995 * the lockfile is still open. Close it to2996 * free up the file descriptor:2997 */2998if(close_ref(lock)) {2999strbuf_addf(err,"couldn't close '%s.lock'",3000 update->refname);3001return TRANSACTION_GENERIC_ERROR;3002}3003}3004return0;3005}30063007/*3008 * Unlock any references in `transaction` that are still locked, and3009 * mark the transaction closed.3010 */3011static voidfiles_transaction_cleanup(struct ref_transaction *transaction)3012{3013size_t i;30143015for(i =0; i < transaction->nr; i++) {3016struct ref_update *update = transaction->updates[i];3017struct ref_lock *lock = update->backend_data;30183019if(lock) {3020unlock_ref(lock);3021 update->backend_data = NULL;3022}3023}30243025 transaction->state = REF_TRANSACTION_CLOSED;3026}30273028static intfiles_transaction_prepare(struct ref_store *ref_store,3029struct ref_transaction *transaction,3030struct strbuf *err)3031{3032struct files_ref_store *refs =3033files_downcast(ref_store, REF_STORE_WRITE,3034"ref_transaction_prepare");3035size_t i;3036int ret =0;3037struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3038char*head_ref = NULL;3039int head_type;3040struct object_id head_oid;30413042assert(err);30433044if(!transaction->nr)3045goto cleanup;30463047/*3048 * Fail if a refname appears more than once in the3049 * transaction. (If we end up splitting up any updates using3050 * split_symref_update() or split_head_update(), those3051 * functions will check that the new updates don't have the3052 * same refname as any existing ones.)3053 */3054for(i =0; i < transaction->nr; i++) {3055struct ref_update *update = transaction->updates[i];3056struct string_list_item *item =3057string_list_append(&affected_refnames, update->refname);30583059/*3060 * We store a pointer to update in item->util, but at3061 * the moment we never use the value of this field3062 * except to check whether it is non-NULL.3063 */3064 item->util = update;3065}3066string_list_sort(&affected_refnames);3067if(ref_update_reject_duplicates(&affected_refnames, err)) {3068 ret = TRANSACTION_GENERIC_ERROR;3069goto cleanup;3070}30713072/*3073 * Special hack: If a branch is updated directly and HEAD3074 * points to it (may happen on the remote side of a push3075 * for example) then logically the HEAD reflog should be3076 * updated too.3077 *3078 * A generic solution would require reverse symref lookups,3079 * but finding all symrefs pointing to a given branch would be3080 * rather costly for this rare event (the direct update of a3081 * branch) to be worth it. So let's cheat and check with HEAD3082 * only, which should cover 99% of all usage scenarios (even3083 * 100% of the default ones).3084 *3085 * So if HEAD is a symbolic reference, then record the name of3086 * the reference that it points to. If we see an update of3087 * head_ref within the transaction, then split_head_update()3088 * arranges for the reflog of HEAD to be updated, too.3089 */3090 head_ref =refs_resolve_refdup(ref_store,"HEAD",3091 RESOLVE_REF_NO_RECURSE,3092 head_oid.hash, &head_type);30933094if(head_ref && !(head_type & REF_ISSYMREF)) {3095free(head_ref);3096 head_ref = NULL;3097}30983099/*3100 * Acquire all locks, verify old values if provided, check3101 * that new values are valid, and write new values to the3102 * lockfiles, ready to be activated. Only keep one lockfile3103 * open at a time to avoid running out of file descriptors.3104 * Note that lock_ref_for_update() might append more updates3105 * to the transaction.3106 */3107for(i =0; i < transaction->nr; i++) {3108struct ref_update *update = transaction->updates[i];31093110 ret =lock_ref_for_update(refs, update, transaction,3111 head_ref, &affected_refnames, err);3112if(ret)3113break;3114}31153116cleanup:3117free(head_ref);3118string_list_clear(&affected_refnames,0);31193120if(ret)3121files_transaction_cleanup(transaction);3122else3123 transaction->state = REF_TRANSACTION_PREPARED;31243125return ret;3126}31273128static intfiles_transaction_finish(struct ref_store *ref_store,3129struct ref_transaction *transaction,3130struct strbuf *err)3131{3132struct files_ref_store *refs =3133files_downcast(ref_store,0,"ref_transaction_finish");3134size_t i;3135int ret =0;3136struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3137struct string_list_item *ref_to_delete;3138struct strbuf sb = STRBUF_INIT;31393140assert(err);31413142if(!transaction->nr) {3143 transaction->state = REF_TRANSACTION_CLOSED;3144return0;3145}31463147/* Perform updates first so live commits remain referenced */3148for(i =0; i < transaction->nr; i++) {3149struct ref_update *update = transaction->updates[i];3150struct ref_lock *lock = update->backend_data;31513152if(update->flags & REF_NEEDS_COMMIT ||3153 update->flags & REF_LOG_ONLY) {3154if(files_log_ref_write(refs,3155 lock->ref_name,3156&lock->old_oid,3157&update->new_oid,3158 update->msg, update->flags,3159 err)) {3160char*old_msg =strbuf_detach(err, NULL);31613162strbuf_addf(err,"cannot update the ref '%s':%s",3163 lock->ref_name, old_msg);3164free(old_msg);3165unlock_ref(lock);3166 update->backend_data = NULL;3167 ret = TRANSACTION_GENERIC_ERROR;3168goto cleanup;3169}3170}3171if(update->flags & REF_NEEDS_COMMIT) {3172clear_loose_ref_cache(refs);3173if(commit_ref(lock)) {3174strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3175unlock_ref(lock);3176 update->backend_data = NULL;3177 ret = TRANSACTION_GENERIC_ERROR;3178goto cleanup;3179}3180}3181}3182/* Perform deletes now that updates are safely completed */3183for(i =0; i < transaction->nr; i++) {3184struct ref_update *update = transaction->updates[i];3185struct ref_lock *lock = update->backend_data;31863187if(update->flags & REF_DELETING &&3188!(update->flags & REF_LOG_ONLY)) {3189if(!(update->type & REF_ISPACKED) ||3190 update->type & REF_ISSYMREF) {3191/* It is a loose reference. */3192strbuf_reset(&sb);3193files_ref_path(refs, &sb, lock->ref_name);3194if(unlink_or_msg(sb.buf, err)) {3195 ret = TRANSACTION_GENERIC_ERROR;3196goto cleanup;3197}3198 update->flags |= REF_DELETED_LOOSE;3199}32003201if(!(update->flags & REF_ISPRUNING))3202string_list_append(&refs_to_delete,3203 lock->ref_name);3204}3205}32063207if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {3208 ret = TRANSACTION_GENERIC_ERROR;3209goto cleanup;3210}32113212/* Delete the reflogs of any references that were deleted: */3213for_each_string_list_item(ref_to_delete, &refs_to_delete) {3214strbuf_reset(&sb);3215files_reflog_path(refs, &sb, ref_to_delete->string);3216if(!unlink_or_warn(sb.buf))3217try_remove_empty_parents(refs, ref_to_delete->string,3218 REMOVE_EMPTY_PARENTS_REFLOG);3219}32203221clear_loose_ref_cache(refs);32223223cleanup:3224files_transaction_cleanup(transaction);32253226for(i =0; i < transaction->nr; i++) {3227struct ref_update *update = transaction->updates[i];32283229if(update->flags & REF_DELETED_LOOSE) {3230/*3231 * The loose reference was deleted. Delete any3232 * empty parent directories. (Note that this3233 * can only work because we have already3234 * removed the lockfile.)3235 */3236try_remove_empty_parents(refs, update->refname,3237 REMOVE_EMPTY_PARENTS_REF);3238}3239}32403241strbuf_release(&sb);3242string_list_clear(&refs_to_delete,0);3243return ret;3244}32453246static intfiles_transaction_abort(struct ref_store *ref_store,3247struct ref_transaction *transaction,3248struct strbuf *err)3249{3250files_transaction_cleanup(transaction);3251return0;3252}32533254static intref_present(const char*refname,3255const struct object_id *oid,int flags,void*cb_data)3256{3257struct string_list *affected_refnames = cb_data;32583259returnstring_list_has_string(affected_refnames, refname);3260}32613262static intfiles_initial_transaction_commit(struct ref_store *ref_store,3263struct ref_transaction *transaction,3264struct strbuf *err)3265{3266struct files_ref_store *refs =3267files_downcast(ref_store, REF_STORE_WRITE,3268"initial_ref_transaction_commit");3269size_t i;3270int ret =0;3271struct string_list affected_refnames = STRING_LIST_INIT_NODUP;32723273assert(err);32743275if(transaction->state != REF_TRANSACTION_OPEN)3276die("BUG: commit called for transaction that is not open");32773278/* Fail if a refname appears more than once in the transaction: */3279for(i =0; i < transaction->nr; i++)3280string_list_append(&affected_refnames,3281 transaction->updates[i]->refname);3282string_list_sort(&affected_refnames);3283if(ref_update_reject_duplicates(&affected_refnames, err)) {3284 ret = TRANSACTION_GENERIC_ERROR;3285goto cleanup;3286}32873288/*3289 * It's really undefined to call this function in an active3290 * repository or when there are existing references: we are3291 * only locking and changing packed-refs, so (1) any3292 * simultaneous processes might try to change a reference at3293 * the same time we do, and (2) any existing loose versions of3294 * the references that we are setting would have precedence3295 * over our values. But some remote helpers create the remote3296 * "HEAD" and "master" branches before calling this function,3297 * so here we really only check that none of the references3298 * that we are creating already exists.3299 */3300if(refs_for_each_rawref(&refs->base, ref_present,3301&affected_refnames))3302die("BUG: initial ref transaction called with existing refs");33033304for(i =0; i < transaction->nr; i++) {3305struct ref_update *update = transaction->updates[i];33063307if((update->flags & REF_HAVE_OLD) &&3308!is_null_oid(&update->old_oid))3309die("BUG: initial ref transaction with old_sha1 set");3310if(refs_verify_refname_available(&refs->base, update->refname,3311&affected_refnames, NULL,3312 err)) {3313 ret = TRANSACTION_NAME_CONFLICT;3314goto cleanup;3315}3316}33173318if(lock_packed_refs(refs->packed_ref_store,0)) {3319strbuf_addf(err,"unable to lock packed-refs file:%s",3320strerror(errno));3321 ret = TRANSACTION_GENERIC_ERROR;3322goto cleanup;3323}33243325for(i =0; i < transaction->nr; i++) {3326struct ref_update *update = transaction->updates[i];33273328if((update->flags & REF_HAVE_NEW) &&3329!is_null_oid(&update->new_oid))3330add_packed_ref(refs->packed_ref_store, update->refname,3331&update->new_oid);3332}33333334if(commit_packed_refs(refs->packed_ref_store)) {3335strbuf_addf(err,"unable to commit packed-refs file:%s",3336strerror(errno));3337 ret = TRANSACTION_GENERIC_ERROR;3338goto cleanup;3339}33403341cleanup:3342 transaction->state = REF_TRANSACTION_CLOSED;3343string_list_clear(&affected_refnames,0);3344return ret;3345}33463347struct expire_reflog_cb {3348unsigned int flags;3349 reflog_expiry_should_prune_fn *should_prune_fn;3350void*policy_cb;3351FILE*newlog;3352struct object_id last_kept_oid;3353};33543355static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3356const char*email, timestamp_t timestamp,int tz,3357const char*message,void*cb_data)3358{3359struct expire_reflog_cb *cb = cb_data;3360struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33613362if(cb->flags & EXPIRE_REFLOGS_REWRITE)3363 ooid = &cb->last_kept_oid;33643365if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3366 message, policy_cb)) {3367if(!cb->newlog)3368printf("would prune%s", message);3369else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3370printf("prune%s", message);3371}else{3372if(cb->newlog) {3373fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3374oid_to_hex(ooid),oid_to_hex(noid),3375 email, timestamp, tz, message);3376oidcpy(&cb->last_kept_oid, noid);3377}3378if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3379printf("keep%s", message);3380}3381return0;3382}33833384static intfiles_reflog_expire(struct ref_store *ref_store,3385const char*refname,const unsigned char*sha1,3386unsigned int flags,3387 reflog_expiry_prepare_fn prepare_fn,3388 reflog_expiry_should_prune_fn should_prune_fn,3389 reflog_expiry_cleanup_fn cleanup_fn,3390void*policy_cb_data)3391{3392struct files_ref_store *refs =3393files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3394static struct lock_file reflog_lock;3395struct expire_reflog_cb cb;3396struct ref_lock *lock;3397struct strbuf log_file_sb = STRBUF_INIT;3398char*log_file;3399int status =0;3400int type;3401struct strbuf err = STRBUF_INIT;3402struct object_id oid;34033404memset(&cb,0,sizeof(cb));3405 cb.flags = flags;3406 cb.policy_cb = policy_cb_data;3407 cb.should_prune_fn = should_prune_fn;34083409/*3410 * The reflog file is locked by holding the lock on the3411 * reference itself, plus we might need to update the3412 * reference if --updateref was specified:3413 */3414 lock =lock_ref_sha1_basic(refs, refname, sha1,3415 NULL, NULL, REF_NODEREF,3416&type, &err);3417if(!lock) {3418error("cannot lock ref '%s':%s", refname, err.buf);3419strbuf_release(&err);3420return-1;3421}3422if(!refs_reflog_exists(ref_store, refname)) {3423unlock_ref(lock);3424return0;3425}34263427files_reflog_path(refs, &log_file_sb, refname);3428 log_file =strbuf_detach(&log_file_sb, NULL);3429if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3430/*3431 * Even though holding $GIT_DIR/logs/$reflog.lock has3432 * no locking implications, we use the lock_file3433 * machinery here anyway because it does a lot of the3434 * work we need, including cleaning up if the program3435 * exits unexpectedly.3436 */3437if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3438struct strbuf err = STRBUF_INIT;3439unable_to_lock_message(log_file, errno, &err);3440error("%s", err.buf);3441strbuf_release(&err);3442goto failure;3443}3444 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3445if(!cb.newlog) {3446error("cannot fdopen%s(%s)",3447get_lock_file_path(&reflog_lock),strerror(errno));3448goto failure;3449}3450}34513452hashcpy(oid.hash, sha1);34533454(*prepare_fn)(refname, &oid, cb.policy_cb);3455refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3456(*cleanup_fn)(cb.policy_cb);34573458if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3459/*3460 * It doesn't make sense to adjust a reference pointed3461 * to by a symbolic ref based on expiring entries in3462 * the symbolic reference's reflog. Nor can we update3463 * a reference if there are no remaining reflog3464 * entries.3465 */3466int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3467!(type & REF_ISSYMREF) &&3468!is_null_oid(&cb.last_kept_oid);34693470if(close_lock_file(&reflog_lock)) {3471 status |=error("couldn't write%s:%s", log_file,3472strerror(errno));3473}else if(update &&3474(write_in_full(get_lock_file_fd(lock->lk),3475oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3476write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3477close_ref(lock) <0)) {3478 status |=error("couldn't write%s",3479get_lock_file_path(lock->lk));3480rollback_lock_file(&reflog_lock);3481}else if(commit_lock_file(&reflog_lock)) {3482 status |=error("unable to write reflog '%s' (%s)",3483 log_file,strerror(errno));3484}else if(update &&commit_ref(lock)) {3485 status |=error("couldn't set%s", lock->ref_name);3486}3487}3488free(log_file);3489unlock_ref(lock);3490return status;34913492 failure:3493rollback_lock_file(&reflog_lock);3494free(log_file);3495unlock_ref(lock);3496return-1;3497}34983499static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3500{3501struct files_ref_store *refs =3502files_downcast(ref_store, REF_STORE_WRITE,"init_db");3503struct strbuf sb = STRBUF_INIT;35043505/*3506 * Create .git/refs/{heads,tags}3507 */3508files_ref_path(refs, &sb,"refs/heads");3509safe_create_dir(sb.buf,1);35103511strbuf_reset(&sb);3512files_ref_path(refs, &sb,"refs/tags");3513safe_create_dir(sb.buf,1);35143515strbuf_release(&sb);3516return0;3517}35183519struct ref_storage_be refs_be_files = {3520 NULL,3521"files",3522 files_ref_store_create,3523 files_init_db,3524 files_transaction_prepare,3525 files_transaction_finish,3526 files_transaction_abort,3527 files_initial_transaction_commit,35283529 files_pack_refs,3530 files_peel_ref,3531 files_create_symref,3532 files_delete_refs,3533 files_rename_ref,35343535 files_ref_iterator_begin,3536 files_read_raw_ref,35373538 files_reflog_iterator_begin,3539 files_for_each_reflog_ent,3540 files_for_each_reflog_ent_reverse,3541 files_reflog_exists,3542 files_create_reflog,3543 files_delete_reflog,3544 files_reflog_expire3545};