1#include"../cache.h" 2#include"../config.h" 3#include"../refs.h" 4#include"refs-internal.h" 5#include"ref-cache.h" 6#include"../iterator.h" 7#include"../dir-iterator.h" 8#include"../lockfile.h" 9#include"../object.h" 10#include"../dir.h" 11 12struct ref_lock { 13char*ref_name; 14struct lock_file *lk; 15struct object_id old_oid; 16}; 17 18/* 19 * Return true if refname, which has the specified oid and flags, can 20 * be resolved to an object in the database. If the referred-to object 21 * does not exist, emit a warning and return false. 22 */ 23static intref_resolves_to_object(const char*refname, 24const struct object_id *oid, 25unsigned int flags) 26{ 27if(flags & REF_ISBROKEN) 28return0; 29if(!has_sha1_file(oid->hash)) { 30error("%sdoes not point to a valid object!", refname); 31return0; 32} 33return1; 34} 35 36struct packed_ref_cache { 37struct ref_cache *cache; 38 39/* 40 * Count of references to the data structure in this instance, 41 * including the pointer from files_ref_store::packed if any. 42 * The data will not be freed as long as the reference count 43 * is nonzero. 44 */ 45unsigned int referrers; 46 47/* The metadata from when this packed-refs cache was read */ 48struct stat_validity validity; 49}; 50 51/* 52 * Future: need to be in "struct repository" 53 * when doing a full libification. 54 */ 55struct files_ref_store { 56struct ref_store base; 57unsigned int store_flags; 58 59char*gitdir; 60char*gitcommondir; 61char*packed_refs_path; 62 63struct ref_cache *loose; 64struct packed_ref_cache *packed; 65 66/* 67 * Lock used for the "packed-refs" file. Note that this (and 68 * thus the enclosing `files_ref_store`) must not be freed. 69 */ 70struct lock_file packed_refs_lock; 71}; 72 73/* 74 * Increment the reference count of *packed_refs. 75 */ 76static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 77{ 78 packed_refs->referrers++; 79} 80 81/* 82 * Decrease the reference count of *packed_refs. If it goes to zero, 83 * free *packed_refs and return true; otherwise return false. 84 */ 85static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 86{ 87if(!--packed_refs->referrers) { 88free_ref_cache(packed_refs->cache); 89stat_validity_clear(&packed_refs->validity); 90free(packed_refs); 91return1; 92}else{ 93return0; 94} 95} 96 97static voidclear_packed_ref_cache(struct files_ref_store *refs) 98{ 99if(refs->packed) { 100struct packed_ref_cache *packed_refs = refs->packed; 101 102if(is_lock_file_locked(&refs->packed_refs_lock)) 103die("BUG: packed-ref cache cleared while locked"); 104 refs->packed = NULL; 105release_packed_ref_cache(packed_refs); 106} 107} 108 109static voidclear_loose_ref_cache(struct files_ref_store *refs) 110{ 111if(refs->loose) { 112free_ref_cache(refs->loose); 113 refs->loose = NULL; 114} 115} 116 117/* 118 * Create a new submodule ref cache and add it to the internal 119 * set of caches. 120 */ 121static struct ref_store *files_ref_store_create(const char*gitdir, 122unsigned int flags) 123{ 124struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 125struct ref_store *ref_store = (struct ref_store *)refs; 126struct strbuf sb = STRBUF_INIT; 127 128base_ref_store_init(ref_store, &refs_be_files); 129 refs->store_flags = flags; 130 131 refs->gitdir =xstrdup(gitdir); 132get_common_dir_noenv(&sb, gitdir); 133 refs->gitcommondir =strbuf_detach(&sb, NULL); 134strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 135 refs->packed_refs_path =strbuf_detach(&sb, NULL); 136 137return ref_store; 138} 139 140/* 141 * Die if refs is not the main ref store. caller is used in any 142 * necessary error messages. 143 */ 144static voidfiles_assert_main_repository(struct files_ref_store *refs, 145const char*caller) 146{ 147if(refs->store_flags & REF_STORE_MAIN) 148return; 149 150die("BUG: operation%sonly allowed for main ref store", caller); 151} 152 153/* 154 * Downcast ref_store to files_ref_store. Die if ref_store is not a 155 * files_ref_store. required_flags is compared with ref_store's 156 * store_flags to ensure the ref_store has all required capabilities. 157 * "caller" is used in any necessary error messages. 158 */ 159static struct files_ref_store *files_downcast(struct ref_store *ref_store, 160unsigned int required_flags, 161const char*caller) 162{ 163struct files_ref_store *refs; 164 165if(ref_store->be != &refs_be_files) 166die("BUG: ref_store is type\"%s\"not\"files\"in%s", 167 ref_store->be->name, caller); 168 169 refs = (struct files_ref_store *)ref_store; 170 171if((refs->store_flags & required_flags) != required_flags) 172die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 173 caller, required_flags, refs->store_flags); 174 175return refs; 176} 177 178/* The length of a peeled reference line in packed-refs, including EOL: */ 179#define PEELED_LINE_LENGTH 42 180 181/* 182 * The packed-refs header line that we write out. Perhaps other 183 * traits will be added later. The trailing space is required. 184 */ 185static const char PACKED_REFS_HEADER[] = 186"# pack-refs with: peeled fully-peeled\n"; 187 188/* 189 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 190 * Return a pointer to the refname within the line (null-terminated), 191 * or NULL if there was a problem. 192 */ 193static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 194{ 195const char*ref; 196 197if(parse_oid_hex(line->buf, oid, &ref) <0) 198return NULL; 199if(!isspace(*ref++)) 200return NULL; 201 202if(isspace(*ref)) 203return NULL; 204 205if(line->buf[line->len -1] !='\n') 206return NULL; 207 line->buf[--line->len] =0; 208 209return ref; 210} 211 212/* 213 * Read from `packed_refs_file` into a newly-allocated 214 * `packed_ref_cache` and return it. The return value will already 215 * have its reference count incremented. 216 * 217 * A comment line of the form "# pack-refs with: " may contain zero or 218 * more traits. We interpret the traits as follows: 219 * 220 * No traits: 221 * 222 * Probably no references are peeled. But if the file contains a 223 * peeled value for a reference, we will use it. 224 * 225 * peeled: 226 * 227 * References under "refs/tags/", if they *can* be peeled, *are* 228 * peeled in this file. References outside of "refs/tags/" are 229 * probably not peeled even if they could have been, but if we find 230 * a peeled value for such a reference we will use it. 231 * 232 * fully-peeled: 233 * 234 * All references in the file that can be peeled are peeled. 235 * Inversely (and this is more important), any references in the 236 * file for which no peeled value is recorded is not peelable. This 237 * trait should typically be written alongside "peeled" for 238 * compatibility with older clients, but we do not require it 239 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 240 */ 241static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 242{ 243FILE*f; 244struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 245struct ref_entry *last = NULL; 246struct strbuf line = STRBUF_INIT; 247enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 248struct ref_dir *dir; 249 250acquire_packed_ref_cache(packed_refs); 251 packed_refs->cache =create_ref_cache(NULL, NULL); 252 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 253 254 f =fopen(packed_refs_file,"r"); 255if(!f) { 256if(errno == ENOENT) { 257/* 258 * This is OK; it just means that no 259 * "packed-refs" file has been written yet, 260 * which is equivalent to it being empty. 261 */ 262return packed_refs; 263}else{ 264die_errno("couldn't read%s", packed_refs_file); 265} 266} 267 268stat_validity_update(&packed_refs->validity,fileno(f)); 269 270 dir =get_ref_dir(packed_refs->cache->root); 271while(strbuf_getwholeline(&line, f,'\n') != EOF) { 272struct object_id oid; 273const char*refname; 274const char*traits; 275 276if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 277if(strstr(traits," fully-peeled ")) 278 peeled = PEELED_FULLY; 279else if(strstr(traits," peeled ")) 280 peeled = PEELED_TAGS; 281/* perhaps other traits later as well */ 282continue; 283} 284 285 refname =parse_ref_line(&line, &oid); 286if(refname) { 287int flag = REF_ISPACKED; 288 289if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 290if(!refname_is_safe(refname)) 291die("packed refname is dangerous:%s", refname); 292oidclr(&oid); 293 flag |= REF_BAD_NAME | REF_ISBROKEN; 294} 295 last =create_ref_entry(refname, &oid, flag); 296if(peeled == PEELED_FULLY || 297(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 298 last->flag |= REF_KNOWS_PEELED; 299add_ref_entry(dir, last); 300continue; 301} 302if(last && 303 line.buf[0] =='^'&& 304 line.len == PEELED_LINE_LENGTH && 305 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 306!get_oid_hex(line.buf +1, &oid)) { 307oidcpy(&last->u.value.peeled, &oid); 308/* 309 * Regardless of what the file header said, 310 * we definitely know the value of *this* 311 * reference: 312 */ 313 last->flag |= REF_KNOWS_PEELED; 314} 315} 316 317fclose(f); 318strbuf_release(&line); 319 320return packed_refs; 321} 322 323static const char*files_packed_refs_path(struct files_ref_store *refs) 324{ 325return refs->packed_refs_path; 326} 327 328static voidfiles_reflog_path(struct files_ref_store *refs, 329struct strbuf *sb, 330const char*refname) 331{ 332if(!refname) { 333/* 334 * FIXME: of course this is wrong in multi worktree 335 * setting. To be fixed real soon. 336 */ 337strbuf_addf(sb,"%s/logs", refs->gitcommondir); 338return; 339} 340 341switch(ref_type(refname)) { 342case REF_TYPE_PER_WORKTREE: 343case REF_TYPE_PSEUDOREF: 344strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 345break; 346case REF_TYPE_NORMAL: 347strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 348break; 349default: 350die("BUG: unknown ref type%dof ref%s", 351ref_type(refname), refname); 352} 353} 354 355static voidfiles_ref_path(struct files_ref_store *refs, 356struct strbuf *sb, 357const char*refname) 358{ 359switch(ref_type(refname)) { 360case REF_TYPE_PER_WORKTREE: 361case REF_TYPE_PSEUDOREF: 362strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 363break; 364case REF_TYPE_NORMAL: 365strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 366break; 367default: 368die("BUG: unknown ref type%dof ref%s", 369ref_type(refname), refname); 370} 371} 372 373/* 374 * Check that the packed refs cache (if any) still reflects the 375 * contents of the file. If not, clear the cache. 376 */ 377static voidvalidate_packed_ref_cache(struct files_ref_store *refs) 378{ 379if(refs->packed && 380!stat_validity_check(&refs->packed->validity, 381files_packed_refs_path(refs))) 382clear_packed_ref_cache(refs); 383} 384 385/* 386 * Get the packed_ref_cache for the specified files_ref_store, 387 * creating and populating it if it hasn't been read before or if the 388 * file has been changed (according to its `validity` field) since it 389 * was last read. On the other hand, if we hold the lock, then assume 390 * that the file hasn't been changed out from under us, so skip the 391 * extra `stat()` call in `stat_validity_check()`. 392 */ 393static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 394{ 395const char*packed_refs_file =files_packed_refs_path(refs); 396 397if(!is_lock_file_locked(&refs->packed_refs_lock)) 398validate_packed_ref_cache(refs); 399 400if(!refs->packed) 401 refs->packed =read_packed_refs(packed_refs_file); 402 403return refs->packed; 404} 405 406static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 407{ 408returnget_ref_dir(packed_ref_cache->cache->root); 409} 410 411static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 412{ 413returnget_packed_ref_dir(get_packed_ref_cache(refs)); 414} 415 416/* 417 * Add a reference to the in-memory packed reference cache. This may 418 * only be called while the packed-refs file is locked (see 419 * lock_packed_refs()). To actually write the packed-refs file, call 420 * commit_packed_refs(). 421 */ 422static voidadd_packed_ref(struct files_ref_store *refs, 423const char*refname,const struct object_id *oid) 424{ 425struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 426 427if(!is_lock_file_locked(&refs->packed_refs_lock)) 428die("BUG: packed refs not locked"); 429 430if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 431die("Reference has invalid format: '%s'", refname); 432 433add_ref_entry(get_packed_ref_dir(packed_ref_cache), 434create_ref_entry(refname, oid, REF_ISPACKED)); 435} 436 437/* 438 * Read the loose references from the namespace dirname into dir 439 * (without recursing). dirname must end with '/'. dir must be the 440 * directory entry corresponding to dirname. 441 */ 442static voidloose_fill_ref_dir(struct ref_store *ref_store, 443struct ref_dir *dir,const char*dirname) 444{ 445struct files_ref_store *refs = 446files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 447DIR*d; 448struct dirent *de; 449int dirnamelen =strlen(dirname); 450struct strbuf refname; 451struct strbuf path = STRBUF_INIT; 452size_t path_baselen; 453 454files_ref_path(refs, &path, dirname); 455 path_baselen = path.len; 456 457 d =opendir(path.buf); 458if(!d) { 459strbuf_release(&path); 460return; 461} 462 463strbuf_init(&refname, dirnamelen +257); 464strbuf_add(&refname, dirname, dirnamelen); 465 466while((de =readdir(d)) != NULL) { 467struct object_id oid; 468struct stat st; 469int flag; 470 471if(de->d_name[0] =='.') 472continue; 473if(ends_with(de->d_name,".lock")) 474continue; 475strbuf_addstr(&refname, de->d_name); 476strbuf_addstr(&path, de->d_name); 477if(stat(path.buf, &st) <0) { 478;/* silently ignore */ 479}else if(S_ISDIR(st.st_mode)) { 480strbuf_addch(&refname,'/'); 481add_entry_to_dir(dir, 482create_dir_entry(dir->cache, refname.buf, 483 refname.len,1)); 484}else{ 485if(!refs_resolve_ref_unsafe(&refs->base, 486 refname.buf, 487 RESOLVE_REF_READING, 488 oid.hash, &flag)) { 489oidclr(&oid); 490 flag |= REF_ISBROKEN; 491}else if(is_null_oid(&oid)) { 492/* 493 * It is so astronomically unlikely 494 * that NULL_SHA1 is the SHA-1 of an 495 * actual object that we consider its 496 * appearance in a loose reference 497 * file to be repo corruption 498 * (probably due to a software bug). 499 */ 500 flag |= REF_ISBROKEN; 501} 502 503if(check_refname_format(refname.buf, 504 REFNAME_ALLOW_ONELEVEL)) { 505if(!refname_is_safe(refname.buf)) 506die("loose refname is dangerous:%s", refname.buf); 507oidclr(&oid); 508 flag |= REF_BAD_NAME | REF_ISBROKEN; 509} 510add_entry_to_dir(dir, 511create_ref_entry(refname.buf, &oid, flag)); 512} 513strbuf_setlen(&refname, dirnamelen); 514strbuf_setlen(&path, path_baselen); 515} 516strbuf_release(&refname); 517strbuf_release(&path); 518closedir(d); 519 520/* 521 * Manually add refs/bisect, which, being per-worktree, might 522 * not appear in the directory listing for refs/ in the main 523 * repo. 524 */ 525if(!strcmp(dirname,"refs/")) { 526int pos =search_ref_dir(dir,"refs/bisect/",12); 527 528if(pos <0) { 529struct ref_entry *child_entry =create_dir_entry( 530 dir->cache,"refs/bisect/",12,1); 531add_entry_to_dir(dir, child_entry); 532} 533} 534} 535 536static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 537{ 538if(!refs->loose) { 539/* 540 * Mark the top-level directory complete because we 541 * are about to read the only subdirectory that can 542 * hold references: 543 */ 544 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 545 546/* We're going to fill the top level ourselves: */ 547 refs->loose->root->flag &= ~REF_INCOMPLETE; 548 549/* 550 * Add an incomplete entry for "refs/" (to be filled 551 * lazily): 552 */ 553add_entry_to_dir(get_ref_dir(refs->loose->root), 554create_dir_entry(refs->loose,"refs/",5,1)); 555} 556return refs->loose; 557} 558 559/* 560 * Return the ref_entry for the given refname from the packed 561 * references. If it does not exist, return NULL. 562 */ 563static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 564const char*refname) 565{ 566returnfind_ref_entry(get_packed_refs(refs), refname); 567} 568 569/* 570 * A loose ref file doesn't exist; check for a packed ref. 571 */ 572static intresolve_packed_ref(struct files_ref_store *refs, 573const char*refname, 574unsigned char*sha1,unsigned int*flags) 575{ 576struct ref_entry *entry; 577 578/* 579 * The loose reference file does not exist; check for a packed 580 * reference. 581 */ 582 entry =get_packed_ref(refs, refname); 583if(entry) { 584hashcpy(sha1, entry->u.value.oid.hash); 585*flags |= REF_ISPACKED; 586return0; 587} 588/* refname is not a packed reference. */ 589return-1; 590} 591 592static intfiles_read_raw_ref(struct ref_store *ref_store, 593const char*refname,unsigned char*sha1, 594struct strbuf *referent,unsigned int*type) 595{ 596struct files_ref_store *refs = 597files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 598struct strbuf sb_contents = STRBUF_INIT; 599struct strbuf sb_path = STRBUF_INIT; 600const char*path; 601const char*buf; 602struct stat st; 603int fd; 604int ret = -1; 605int save_errno; 606int remaining_retries =3; 607 608*type =0; 609strbuf_reset(&sb_path); 610 611files_ref_path(refs, &sb_path, refname); 612 613 path = sb_path.buf; 614 615stat_ref: 616/* 617 * We might have to loop back here to avoid a race 618 * condition: first we lstat() the file, then we try 619 * to read it as a link or as a file. But if somebody 620 * changes the type of the file (file <-> directory 621 * <-> symlink) between the lstat() and reading, then 622 * we don't want to report that as an error but rather 623 * try again starting with the lstat(). 624 * 625 * We'll keep a count of the retries, though, just to avoid 626 * any confusing situation sending us into an infinite loop. 627 */ 628 629if(remaining_retries-- <=0) 630goto out; 631 632if(lstat(path, &st) <0) { 633if(errno != ENOENT) 634goto out; 635if(resolve_packed_ref(refs, refname, sha1, type)) { 636 errno = ENOENT; 637goto out; 638} 639 ret =0; 640goto out; 641} 642 643/* Follow "normalized" - ie "refs/.." symlinks by hand */ 644if(S_ISLNK(st.st_mode)) { 645strbuf_reset(&sb_contents); 646if(strbuf_readlink(&sb_contents, path,0) <0) { 647if(errno == ENOENT || errno == EINVAL) 648/* inconsistent with lstat; retry */ 649goto stat_ref; 650else 651goto out; 652} 653if(starts_with(sb_contents.buf,"refs/") && 654!check_refname_format(sb_contents.buf,0)) { 655strbuf_swap(&sb_contents, referent); 656*type |= REF_ISSYMREF; 657 ret =0; 658goto out; 659} 660/* 661 * It doesn't look like a refname; fall through to just 662 * treating it like a non-symlink, and reading whatever it 663 * points to. 664 */ 665} 666 667/* Is it a directory? */ 668if(S_ISDIR(st.st_mode)) { 669/* 670 * Even though there is a directory where the loose 671 * ref is supposed to be, there could still be a 672 * packed ref: 673 */ 674if(resolve_packed_ref(refs, refname, sha1, type)) { 675 errno = EISDIR; 676goto out; 677} 678 ret =0; 679goto out; 680} 681 682/* 683 * Anything else, just open it and try to use it as 684 * a ref 685 */ 686 fd =open(path, O_RDONLY); 687if(fd <0) { 688if(errno == ENOENT && !S_ISLNK(st.st_mode)) 689/* inconsistent with lstat; retry */ 690goto stat_ref; 691else 692goto out; 693} 694strbuf_reset(&sb_contents); 695if(strbuf_read(&sb_contents, fd,256) <0) { 696int save_errno = errno; 697close(fd); 698 errno = save_errno; 699goto out; 700} 701close(fd); 702strbuf_rtrim(&sb_contents); 703 buf = sb_contents.buf; 704if(starts_with(buf,"ref:")) { 705 buf +=4; 706while(isspace(*buf)) 707 buf++; 708 709strbuf_reset(referent); 710strbuf_addstr(referent, buf); 711*type |= REF_ISSYMREF; 712 ret =0; 713goto out; 714} 715 716/* 717 * Please note that FETCH_HEAD has additional 718 * data after the sha. 719 */ 720if(get_sha1_hex(buf, sha1) || 721(buf[40] !='\0'&& !isspace(buf[40]))) { 722*type |= REF_ISBROKEN; 723 errno = EINVAL; 724goto out; 725} 726 727 ret =0; 728 729out: 730 save_errno = errno; 731strbuf_release(&sb_path); 732strbuf_release(&sb_contents); 733 errno = save_errno; 734return ret; 735} 736 737static voidunlock_ref(struct ref_lock *lock) 738{ 739/* Do not free lock->lk -- atexit() still looks at them */ 740if(lock->lk) 741rollback_lock_file(lock->lk); 742free(lock->ref_name); 743free(lock); 744} 745 746/* 747 * Lock refname, without following symrefs, and set *lock_p to point 748 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 749 * and type similarly to read_raw_ref(). 750 * 751 * The caller must verify that refname is a "safe" reference name (in 752 * the sense of refname_is_safe()) before calling this function. 753 * 754 * If the reference doesn't already exist, verify that refname doesn't 755 * have a D/F conflict with any existing references. extras and skip 756 * are passed to refs_verify_refname_available() for this check. 757 * 758 * If mustexist is not set and the reference is not found or is 759 * broken, lock the reference anyway but clear sha1. 760 * 761 * Return 0 on success. On failure, write an error message to err and 762 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 763 * 764 * Implementation note: This function is basically 765 * 766 * lock reference 767 * read_raw_ref() 768 * 769 * but it includes a lot more code to 770 * - Deal with possible races with other processes 771 * - Avoid calling refs_verify_refname_available() when it can be 772 * avoided, namely if we were successfully able to read the ref 773 * - Generate informative error messages in the case of failure 774 */ 775static intlock_raw_ref(struct files_ref_store *refs, 776const char*refname,int mustexist, 777const struct string_list *extras, 778const struct string_list *skip, 779struct ref_lock **lock_p, 780struct strbuf *referent, 781unsigned int*type, 782struct strbuf *err) 783{ 784struct ref_lock *lock; 785struct strbuf ref_file = STRBUF_INIT; 786int attempts_remaining =3; 787int ret = TRANSACTION_GENERIC_ERROR; 788 789assert(err); 790files_assert_main_repository(refs,"lock_raw_ref"); 791 792*type =0; 793 794/* First lock the file so it can't change out from under us. */ 795 796*lock_p = lock =xcalloc(1,sizeof(*lock)); 797 798 lock->ref_name =xstrdup(refname); 799files_ref_path(refs, &ref_file, refname); 800 801retry: 802switch(safe_create_leading_directories(ref_file.buf)) { 803case SCLD_OK: 804break;/* success */ 805case SCLD_EXISTS: 806/* 807 * Suppose refname is "refs/foo/bar". We just failed 808 * to create the containing directory, "refs/foo", 809 * because there was a non-directory in the way. This 810 * indicates a D/F conflict, probably because of 811 * another reference such as "refs/foo". There is no 812 * reason to expect this error to be transitory. 813 */ 814if(refs_verify_refname_available(&refs->base, refname, 815 extras, skip, err)) { 816if(mustexist) { 817/* 818 * To the user the relevant error is 819 * that the "mustexist" reference is 820 * missing: 821 */ 822strbuf_reset(err); 823strbuf_addf(err,"unable to resolve reference '%s'", 824 refname); 825}else{ 826/* 827 * The error message set by 828 * refs_verify_refname_available() is 829 * OK. 830 */ 831 ret = TRANSACTION_NAME_CONFLICT; 832} 833}else{ 834/* 835 * The file that is in the way isn't a loose 836 * reference. Report it as a low-level 837 * failure. 838 */ 839strbuf_addf(err,"unable to create lock file%s.lock; " 840"non-directory in the way", 841 ref_file.buf); 842} 843goto error_return; 844case SCLD_VANISHED: 845/* Maybe another process was tidying up. Try again. */ 846if(--attempts_remaining >0) 847goto retry; 848/* fall through */ 849default: 850strbuf_addf(err,"unable to create directory for%s", 851 ref_file.buf); 852goto error_return; 853} 854 855if(!lock->lk) 856 lock->lk =xcalloc(1,sizeof(struct lock_file)); 857 858if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 859if(errno == ENOENT && --attempts_remaining >0) { 860/* 861 * Maybe somebody just deleted one of the 862 * directories leading to ref_file. Try 863 * again: 864 */ 865goto retry; 866}else{ 867unable_to_lock_message(ref_file.buf, errno, err); 868goto error_return; 869} 870} 871 872/* 873 * Now we hold the lock and can read the reference without 874 * fear that its value will change. 875 */ 876 877if(files_read_raw_ref(&refs->base, refname, 878 lock->old_oid.hash, referent, type)) { 879if(errno == ENOENT) { 880if(mustexist) { 881/* Garden variety missing reference. */ 882strbuf_addf(err,"unable to resolve reference '%s'", 883 refname); 884goto error_return; 885}else{ 886/* 887 * Reference is missing, but that's OK. We 888 * know that there is not a conflict with 889 * another loose reference because 890 * (supposing that we are trying to lock 891 * reference "refs/foo/bar"): 892 * 893 * - We were successfully able to create 894 * the lockfile refs/foo/bar.lock, so we 895 * know there cannot be a loose reference 896 * named "refs/foo". 897 * 898 * - We got ENOENT and not EISDIR, so we 899 * know that there cannot be a loose 900 * reference named "refs/foo/bar/baz". 901 */ 902} 903}else if(errno == EISDIR) { 904/* 905 * There is a directory in the way. It might have 906 * contained references that have been deleted. If 907 * we don't require that the reference already 908 * exists, try to remove the directory so that it 909 * doesn't cause trouble when we want to rename the 910 * lockfile into place later. 911 */ 912if(mustexist) { 913/* Garden variety missing reference. */ 914strbuf_addf(err,"unable to resolve reference '%s'", 915 refname); 916goto error_return; 917}else if(remove_dir_recursively(&ref_file, 918 REMOVE_DIR_EMPTY_ONLY)) { 919if(refs_verify_refname_available( 920&refs->base, refname, 921 extras, skip, err)) { 922/* 923 * The error message set by 924 * verify_refname_available() is OK. 925 */ 926 ret = TRANSACTION_NAME_CONFLICT; 927goto error_return; 928}else{ 929/* 930 * We can't delete the directory, 931 * but we also don't know of any 932 * references that it should 933 * contain. 934 */ 935strbuf_addf(err,"there is a non-empty directory '%s' " 936"blocking reference '%s'", 937 ref_file.buf, refname); 938goto error_return; 939} 940} 941}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 942strbuf_addf(err,"unable to resolve reference '%s': " 943"reference broken", refname); 944goto error_return; 945}else{ 946strbuf_addf(err,"unable to resolve reference '%s':%s", 947 refname,strerror(errno)); 948goto error_return; 949} 950 951/* 952 * If the ref did not exist and we are creating it, 953 * make sure there is no existing ref that conflicts 954 * with refname: 955 */ 956if(refs_verify_refname_available( 957&refs->base, refname, 958 extras, skip, err)) 959goto error_return; 960} 961 962 ret =0; 963goto out; 964 965error_return: 966unlock_ref(lock); 967*lock_p = NULL; 968 969out: 970strbuf_release(&ref_file); 971return ret; 972} 973 974static intfiles_peel_ref(struct ref_store *ref_store, 975const char*refname,unsigned char*sha1) 976{ 977struct files_ref_store *refs = 978files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 979"peel_ref"); 980int flag; 981unsigned char base[20]; 982 983if(current_ref_iter && current_ref_iter->refname == refname) { 984struct object_id peeled; 985 986if(ref_iterator_peel(current_ref_iter, &peeled)) 987return-1; 988hashcpy(sha1, peeled.hash); 989return0; 990} 991 992if(refs_read_ref_full(ref_store, refname, 993 RESOLVE_REF_READING, base, &flag)) 994return-1; 995 996/* 997 * If the reference is packed, read its ref_entry from the 998 * cache in the hope that we already know its peeled value. 999 * We only try this optimization on packed references because1000 * (a) forcing the filling of the loose reference cache could1001 * be expensive and (b) loose references anyway usually do not1002 * have REF_KNOWS_PEELED.1003 */1004if(flag & REF_ISPACKED) {1005struct ref_entry *r =get_packed_ref(refs, refname);1006if(r) {1007if(peel_entry(r,0))1008return-1;1009hashcpy(sha1, r->u.value.peeled.hash);1010return0;1011}1012}10131014returnpeel_object(base, sha1);1015}10161017struct files_ref_iterator {1018struct ref_iterator base;10191020struct packed_ref_cache *packed_ref_cache;1021struct ref_iterator *iter0;1022unsigned int flags;1023};10241025static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1026{1027struct files_ref_iterator *iter =1028(struct files_ref_iterator *)ref_iterator;1029int ok;10301031while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1032if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1033ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1034continue;10351036if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1037!ref_resolves_to_object(iter->iter0->refname,1038 iter->iter0->oid,1039 iter->iter0->flags))1040continue;10411042 iter->base.refname = iter->iter0->refname;1043 iter->base.oid = iter->iter0->oid;1044 iter->base.flags = iter->iter0->flags;1045return ITER_OK;1046}10471048 iter->iter0 = NULL;1049if(ref_iterator_abort(ref_iterator) != ITER_DONE)1050 ok = ITER_ERROR;10511052return ok;1053}10541055static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1056struct object_id *peeled)1057{1058struct files_ref_iterator *iter =1059(struct files_ref_iterator *)ref_iterator;10601061returnref_iterator_peel(iter->iter0, peeled);1062}10631064static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1065{1066struct files_ref_iterator *iter =1067(struct files_ref_iterator *)ref_iterator;1068int ok = ITER_DONE;10691070if(iter->iter0)1071 ok =ref_iterator_abort(iter->iter0);10721073release_packed_ref_cache(iter->packed_ref_cache);1074base_ref_iterator_free(ref_iterator);1075return ok;1076}10771078static struct ref_iterator_vtable files_ref_iterator_vtable = {1079 files_ref_iterator_advance,1080 files_ref_iterator_peel,1081 files_ref_iterator_abort1082};10831084static struct ref_iterator *files_ref_iterator_begin(1085struct ref_store *ref_store,1086const char*prefix,unsigned int flags)1087{1088struct files_ref_store *refs;1089struct ref_iterator *loose_iter, *packed_iter;1090struct files_ref_iterator *iter;1091struct ref_iterator *ref_iterator;1092unsigned int required_flags = REF_STORE_READ;10931094if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1095 required_flags |= REF_STORE_ODB;10961097 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");10981099 iter =xcalloc(1,sizeof(*iter));1100 ref_iterator = &iter->base;1101base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11021103/*1104 * We must make sure that all loose refs are read before1105 * accessing the packed-refs file; this avoids a race1106 * condition if loose refs are migrated to the packed-refs1107 * file by a simultaneous process, but our in-memory view is1108 * from before the migration. We ensure this as follows:1109 * First, we call start the loose refs iteration with its1110 * `prime_ref` argument set to true. This causes the loose1111 * references in the subtree to be pre-read into the cache.1112 * (If they've already been read, that's OK; we only need to1113 * guarantee that they're read before the packed refs, not1114 * *how much* before.) After that, we call1115 * get_packed_ref_cache(), which internally checks whether the1116 * packed-ref cache is up to date with what is on disk, and1117 * re-reads it if not.1118 */11191120 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1121 prefix,1);11221123 iter->packed_ref_cache =get_packed_ref_cache(refs);1124acquire_packed_ref_cache(iter->packed_ref_cache);1125 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1126 prefix,0);11271128 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1129 iter->flags = flags;11301131return ref_iterator;1132}11331134/*1135 * Verify that the reference locked by lock has the value old_sha1.1136 * Fail if the reference doesn't exist and mustexist is set. Return 01137 * on success. On error, write an error message to err, set errno, and1138 * return a negative value.1139 */1140static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1141const unsigned char*old_sha1,int mustexist,1142struct strbuf *err)1143{1144assert(err);11451146if(refs_read_ref_full(ref_store, lock->ref_name,1147 mustexist ? RESOLVE_REF_READING :0,1148 lock->old_oid.hash, NULL)) {1149if(old_sha1) {1150int save_errno = errno;1151strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1152 errno = save_errno;1153return-1;1154}else{1155oidclr(&lock->old_oid);1156return0;1157}1158}1159if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1160strbuf_addf(err,"ref '%s' is at%sbut expected%s",1161 lock->ref_name,1162oid_to_hex(&lock->old_oid),1163sha1_to_hex(old_sha1));1164 errno = EBUSY;1165return-1;1166}1167return0;1168}11691170static intremove_empty_directories(struct strbuf *path)1171{1172/*1173 * we want to create a file but there is a directory there;1174 * if that is an empty directory (or a directory that contains1175 * only empty directories), remove them.1176 */1177returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1178}11791180static intcreate_reflock(const char*path,void*cb)1181{1182struct lock_file *lk = cb;11831184returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1185}11861187/*1188 * Locks a ref returning the lock on success and NULL on failure.1189 * On failure errno is set to something meaningful.1190 */1191static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1192const char*refname,1193const unsigned char*old_sha1,1194const struct string_list *extras,1195const struct string_list *skip,1196unsigned int flags,int*type,1197struct strbuf *err)1198{1199struct strbuf ref_file = STRBUF_INIT;1200struct ref_lock *lock;1201int last_errno =0;1202int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1203int resolve_flags = RESOLVE_REF_NO_RECURSE;1204int resolved;12051206files_assert_main_repository(refs,"lock_ref_sha1_basic");1207assert(err);12081209 lock =xcalloc(1,sizeof(struct ref_lock));12101211if(mustexist)1212 resolve_flags |= RESOLVE_REF_READING;1213if(flags & REF_DELETING)1214 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12151216files_ref_path(refs, &ref_file, refname);1217 resolved = !!refs_resolve_ref_unsafe(&refs->base,1218 refname, resolve_flags,1219 lock->old_oid.hash, type);1220if(!resolved && errno == EISDIR) {1221/*1222 * we are trying to lock foo but we used to1223 * have foo/bar which now does not exist;1224 * it is normal for the empty directory 'foo'1225 * to remain.1226 */1227if(remove_empty_directories(&ref_file)) {1228 last_errno = errno;1229if(!refs_verify_refname_available(1230&refs->base,1231 refname, extras, skip, err))1232strbuf_addf(err,"there are still refs under '%s'",1233 refname);1234goto error_return;1235}1236 resolved = !!refs_resolve_ref_unsafe(&refs->base,1237 refname, resolve_flags,1238 lock->old_oid.hash, type);1239}1240if(!resolved) {1241 last_errno = errno;1242if(last_errno != ENOTDIR ||1243!refs_verify_refname_available(&refs->base, refname,1244 extras, skip, err))1245strbuf_addf(err,"unable to resolve reference '%s':%s",1246 refname,strerror(last_errno));12471248goto error_return;1249}12501251/*1252 * If the ref did not exist and we are creating it, make sure1253 * there is no existing packed ref whose name begins with our1254 * refname, nor a packed ref whose name is a proper prefix of1255 * our refname.1256 */1257if(is_null_oid(&lock->old_oid) &&1258refs_verify_refname_available(&refs->base, refname,1259 extras, skip, err)) {1260 last_errno = ENOTDIR;1261goto error_return;1262}12631264 lock->lk =xcalloc(1,sizeof(struct lock_file));12651266 lock->ref_name =xstrdup(refname);12671268if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1269 last_errno = errno;1270unable_to_lock_message(ref_file.buf, errno, err);1271goto error_return;1272}12731274if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1275 last_errno = errno;1276goto error_return;1277}1278goto out;12791280 error_return:1281unlock_ref(lock);1282 lock = NULL;12831284 out:1285strbuf_release(&ref_file);1286 errno = last_errno;1287return lock;1288}12891290/*1291 * Write an entry to the packed-refs file for the specified refname.1292 * If peeled is non-NULL, write it as the entry's peeled value.1293 */1294static voidwrite_packed_entry(FILE*fh,const char*refname,1295const unsigned char*sha1,1296const unsigned char*peeled)1297{1298fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1299if(peeled)1300fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1301}13021303/*1304 * Lock the packed-refs file for writing. Flags is passed to1305 * hold_lock_file_for_update(). Return 0 on success. On errors, set1306 * errno appropriately and return a nonzero value.1307 */1308static intlock_packed_refs(struct files_ref_store *refs,int flags)1309{1310static int timeout_configured =0;1311static int timeout_value =1000;1312struct packed_ref_cache *packed_ref_cache;13131314files_assert_main_repository(refs,"lock_packed_refs");13151316if(!timeout_configured) {1317git_config_get_int("core.packedrefstimeout", &timeout_value);1318 timeout_configured =1;1319}13201321if(hold_lock_file_for_update_timeout(1322&refs->packed_refs_lock,files_packed_refs_path(refs),1323 flags, timeout_value) <0)1324return-1;13251326/*1327 * Now that we hold the `packed-refs` lock, make sure that our1328 * cache matches the current version of the file. Normally1329 * `get_packed_ref_cache()` does that for us, but that1330 * function assumes that when the file is locked, any existing1331 * cache is still valid. We've just locked the file, but it1332 * might have changed the moment *before* we locked it.1333 */1334validate_packed_ref_cache(refs);13351336 packed_ref_cache =get_packed_ref_cache(refs);1337/* Increment the reference count to prevent it from being freed: */1338acquire_packed_ref_cache(packed_ref_cache);1339return0;1340}13411342/*1343 * Write the current version of the packed refs cache from memory to1344 * disk. The packed-refs file must already be locked for writing (see1345 * lock_packed_refs()). Return zero on success. On errors, set errno1346 * and return a nonzero value1347 */1348static intcommit_packed_refs(struct files_ref_store *refs)1349{1350struct packed_ref_cache *packed_ref_cache =1351get_packed_ref_cache(refs);1352int ok, error =0;1353int save_errno =0;1354FILE*out;1355struct ref_iterator *iter;13561357files_assert_main_repository(refs,"commit_packed_refs");13581359if(!is_lock_file_locked(&refs->packed_refs_lock))1360die("BUG: packed-refs not locked");13611362 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1363if(!out)1364die_errno("unable to fdopen packed-refs descriptor");13651366fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13671368 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1369while((ok =ref_iterator_advance(iter)) == ITER_OK) {1370struct object_id peeled;1371int peel_error =ref_iterator_peel(iter, &peeled);13721373write_packed_entry(out, iter->refname, iter->oid->hash,1374 peel_error ? NULL : peeled.hash);1375}13761377if(ok != ITER_DONE)1378die("error while iterating over references");13791380if(commit_lock_file(&refs->packed_refs_lock)) {1381 save_errno = errno;1382 error = -1;1383}1384release_packed_ref_cache(packed_ref_cache);1385 errno = save_errno;1386return error;1387}13881389/*1390 * Rollback the lockfile for the packed-refs file, and discard the1391 * in-memory packed reference cache. (The packed-refs file will be1392 * read anew if it is needed again after this function is called.)1393 */1394static voidrollback_packed_refs(struct files_ref_store *refs)1395{1396struct packed_ref_cache *packed_ref_cache =1397get_packed_ref_cache(refs);13981399files_assert_main_repository(refs,"rollback_packed_refs");14001401if(!is_lock_file_locked(&refs->packed_refs_lock))1402die("BUG: packed-refs not locked");1403rollback_lock_file(&refs->packed_refs_lock);1404release_packed_ref_cache(packed_ref_cache);1405clear_packed_ref_cache(refs);1406}14071408struct ref_to_prune {1409struct ref_to_prune *next;1410unsigned char sha1[20];1411char name[FLEX_ARRAY];1412};14131414enum{1415 REMOVE_EMPTY_PARENTS_REF =0x01,1416 REMOVE_EMPTY_PARENTS_REFLOG =0x021417};14181419/*1420 * Remove empty parent directories associated with the specified1421 * reference and/or its reflog, but spare [logs/]refs/ and immediate1422 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1423 * REMOVE_EMPTY_PARENTS_REFLOG.1424 */1425static voidtry_remove_empty_parents(struct files_ref_store *refs,1426const char*refname,1427unsigned int flags)1428{1429struct strbuf buf = STRBUF_INIT;1430struct strbuf sb = STRBUF_INIT;1431char*p, *q;1432int i;14331434strbuf_addstr(&buf, refname);1435 p = buf.buf;1436for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1437while(*p && *p !='/')1438 p++;1439/* tolerate duplicate slashes; see check_refname_format() */1440while(*p =='/')1441 p++;1442}1443 q = buf.buf + buf.len;1444while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1445while(q > p && *q !='/')1446 q--;1447while(q > p && *(q-1) =='/')1448 q--;1449if(q == p)1450break;1451strbuf_setlen(&buf, q - buf.buf);14521453strbuf_reset(&sb);1454files_ref_path(refs, &sb, buf.buf);1455if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1456 flags &= ~REMOVE_EMPTY_PARENTS_REF;14571458strbuf_reset(&sb);1459files_reflog_path(refs, &sb, buf.buf);1460if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1461 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1462}1463strbuf_release(&buf);1464strbuf_release(&sb);1465}14661467/* make sure nobody touched the ref, and unlink */1468static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1469{1470struct ref_transaction *transaction;1471struct strbuf err = STRBUF_INIT;14721473if(check_refname_format(r->name,0))1474return;14751476 transaction =ref_store_transaction_begin(&refs->base, &err);1477if(!transaction ||1478ref_transaction_delete(transaction, r->name, r->sha1,1479 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1480ref_transaction_commit(transaction, &err)) {1481ref_transaction_free(transaction);1482error("%s", err.buf);1483strbuf_release(&err);1484return;1485}1486ref_transaction_free(transaction);1487strbuf_release(&err);1488}14891490static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1491{1492while(r) {1493prune_ref(refs, r);1494 r = r->next;1495}1496}14971498/*1499 * Return true if the specified reference should be packed.1500 */1501static intshould_pack_ref(const char*refname,1502const struct object_id *oid,unsigned int ref_flags,1503unsigned int pack_flags)1504{1505/* Do not pack per-worktree refs: */1506if(ref_type(refname) != REF_TYPE_NORMAL)1507return0;15081509/* Do not pack non-tags unless PACK_REFS_ALL is set: */1510if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1511return0;15121513/* Do not pack symbolic refs: */1514if(ref_flags & REF_ISSYMREF)1515return0;15161517/* Do not pack broken refs: */1518if(!ref_resolves_to_object(refname, oid, ref_flags))1519return0;15201521return1;1522}15231524static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1525{1526struct files_ref_store *refs =1527files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1528"pack_refs");1529struct ref_iterator *iter;1530struct ref_dir *packed_refs;1531int ok;1532struct ref_to_prune *refs_to_prune = NULL;15331534lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1535 packed_refs =get_packed_refs(refs);15361537 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1538while((ok =ref_iterator_advance(iter)) == ITER_OK) {1539/*1540 * If the loose reference can be packed, add an entry1541 * in the packed ref cache. If the reference should be1542 * pruned, also add it to refs_to_prune.1543 */1544struct ref_entry *packed_entry;15451546if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1547 flags))1548continue;15491550/*1551 * Create an entry in the packed-refs cache equivalent1552 * to the one from the loose ref cache, except that1553 * we don't copy the peeled status, because we want it1554 * to be re-peeled.1555 */1556 packed_entry =find_ref_entry(packed_refs, iter->refname);1557if(packed_entry) {1558/* Overwrite existing packed entry with info from loose entry */1559 packed_entry->flag = REF_ISPACKED;1560oidcpy(&packed_entry->u.value.oid, iter->oid);1561}else{1562 packed_entry =create_ref_entry(iter->refname, iter->oid,1563 REF_ISPACKED);1564add_ref_entry(packed_refs, packed_entry);1565}1566oidclr(&packed_entry->u.value.peeled);15671568/* Schedule the loose reference for pruning if requested. */1569if((flags & PACK_REFS_PRUNE)) {1570struct ref_to_prune *n;1571FLEX_ALLOC_STR(n, name, iter->refname);1572hashcpy(n->sha1, iter->oid->hash);1573 n->next = refs_to_prune;1574 refs_to_prune = n;1575}1576}1577if(ok != ITER_DONE)1578die("error while iterating over references");15791580if(commit_packed_refs(refs))1581die_errno("unable to overwrite old ref-pack file");15821583prune_refs(refs, refs_to_prune);1584return0;1585}15861587/*1588 * Rewrite the packed-refs file, omitting any refs listed in1589 * 'refnames'. On error, leave packed-refs unchanged, write an error1590 * message to 'err', and return a nonzero value.1591 *1592 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1593 */1594static intrepack_without_refs(struct files_ref_store *refs,1595struct string_list *refnames,struct strbuf *err)1596{1597struct ref_dir *packed;1598struct string_list_item *refname;1599int ret, needs_repacking =0, removed =0;16001601files_assert_main_repository(refs,"repack_without_refs");1602assert(err);16031604/* Look for a packed ref */1605for_each_string_list_item(refname, refnames) {1606if(get_packed_ref(refs, refname->string)) {1607 needs_repacking =1;1608break;1609}1610}16111612/* Avoid locking if we have nothing to do */1613if(!needs_repacking)1614return0;/* no refname exists in packed refs */16151616if(lock_packed_refs(refs,0)) {1617unable_to_lock_message(files_packed_refs_path(refs), errno, err);1618return-1;1619}1620 packed =get_packed_refs(refs);16211622/* Remove refnames from the cache */1623for_each_string_list_item(refname, refnames)1624if(remove_entry_from_dir(packed, refname->string) != -1)1625 removed =1;1626if(!removed) {1627/*1628 * All packed entries disappeared while we were1629 * acquiring the lock.1630 */1631rollback_packed_refs(refs);1632return0;1633}16341635/* Write what remains */1636 ret =commit_packed_refs(refs);1637if(ret)1638strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1639strerror(errno));1640return ret;1641}16421643static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1644struct string_list *refnames,unsigned int flags)1645{1646struct files_ref_store *refs =1647files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1648struct strbuf err = STRBUF_INIT;1649int i, result =0;16501651if(!refnames->nr)1652return0;16531654 result =repack_without_refs(refs, refnames, &err);1655if(result) {1656/*1657 * If we failed to rewrite the packed-refs file, then1658 * it is unsafe to try to remove loose refs, because1659 * doing so might expose an obsolete packed value for1660 * a reference that might even point at an object that1661 * has been garbage collected.1662 */1663if(refnames->nr ==1)1664error(_("could not delete reference%s:%s"),1665 refnames->items[0].string, err.buf);1666else1667error(_("could not delete references:%s"), err.buf);16681669goto out;1670}16711672for(i =0; i < refnames->nr; i++) {1673const char*refname = refnames->items[i].string;16741675if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1676 result |=error(_("could not remove reference%s"), refname);1677}16781679out:1680strbuf_release(&err);1681return result;1682}16831684/*1685 * People using contrib's git-new-workdir have .git/logs/refs ->1686 * /some/other/path/.git/logs/refs, and that may live on another device.1687 *1688 * IOW, to avoid cross device rename errors, the temporary renamed log must1689 * live into logs/refs.1690 */1691#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16921693struct rename_cb {1694const char*tmp_renamed_log;1695int true_errno;1696};16971698static intrename_tmp_log_callback(const char*path,void*cb_data)1699{1700struct rename_cb *cb = cb_data;17011702if(rename(cb->tmp_renamed_log, path)) {1703/*1704 * rename(a, b) when b is an existing directory ought1705 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1706 * Sheesh. Record the true errno for error reporting,1707 * but report EISDIR to raceproof_create_file() so1708 * that it knows to retry.1709 */1710 cb->true_errno = errno;1711if(errno == ENOTDIR)1712 errno = EISDIR;1713return-1;1714}else{1715return0;1716}1717}17181719static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1720{1721struct strbuf path = STRBUF_INIT;1722struct strbuf tmp = STRBUF_INIT;1723struct rename_cb cb;1724int ret;17251726files_reflog_path(refs, &path, newrefname);1727files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1728 cb.tmp_renamed_log = tmp.buf;1729 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1730if(ret) {1731if(errno == EISDIR)1732error("directory not empty:%s", path.buf);1733else1734error("unable to move logfile%sto%s:%s",1735 tmp.buf, path.buf,1736strerror(cb.true_errno));1737}17381739strbuf_release(&path);1740strbuf_release(&tmp);1741return ret;1742}17431744static intwrite_ref_to_lockfile(struct ref_lock *lock,1745const struct object_id *oid,struct strbuf *err);1746static intcommit_ref_update(struct files_ref_store *refs,1747struct ref_lock *lock,1748const struct object_id *oid,const char*logmsg,1749struct strbuf *err);17501751static intfiles_rename_ref(struct ref_store *ref_store,1752const char*oldrefname,const char*newrefname,1753const char*logmsg)1754{1755struct files_ref_store *refs =1756files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1757struct object_id oid, orig_oid;1758int flag =0, logmoved =0;1759struct ref_lock *lock;1760struct stat loginfo;1761struct strbuf sb_oldref = STRBUF_INIT;1762struct strbuf sb_newref = STRBUF_INIT;1763struct strbuf tmp_renamed_log = STRBUF_INIT;1764int log, ret;1765struct strbuf err = STRBUF_INIT;17661767files_reflog_path(refs, &sb_oldref, oldrefname);1768files_reflog_path(refs, &sb_newref, newrefname);1769files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17701771 log = !lstat(sb_oldref.buf, &loginfo);1772if(log &&S_ISLNK(loginfo.st_mode)) {1773 ret =error("reflog for%sis a symlink", oldrefname);1774goto out;1775}17761777if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1778 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1779 orig_oid.hash, &flag)) {1780 ret =error("refname%snot found", oldrefname);1781goto out;1782}17831784if(flag & REF_ISSYMREF) {1785 ret =error("refname%sis a symbolic ref, renaming it is not supported",1786 oldrefname);1787goto out;1788}1789if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1790 ret =1;1791goto out;1792}17931794if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1795 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1796 oldrefname,strerror(errno));1797goto out;1798}17991800if(refs_delete_ref(&refs->base, logmsg, oldrefname,1801 orig_oid.hash, REF_NODEREF)) {1802error("unable to delete old%s", oldrefname);1803goto rollback;1804}18051806/*1807 * Since we are doing a shallow lookup, oid is not the1808 * correct value to pass to delete_ref as old_oid. But that1809 * doesn't matter, because an old_oid check wouldn't add to1810 * the safety anyway; we want to delete the reference whatever1811 * its current value.1812 */1813if(!refs_read_ref_full(&refs->base, newrefname,1814 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1815 oid.hash, NULL) &&1816refs_delete_ref(&refs->base, NULL, newrefname,1817 NULL, REF_NODEREF)) {1818if(errno == EISDIR) {1819struct strbuf path = STRBUF_INIT;1820int result;18211822files_ref_path(refs, &path, newrefname);1823 result =remove_empty_directories(&path);1824strbuf_release(&path);18251826if(result) {1827error("Directory not empty:%s", newrefname);1828goto rollback;1829}1830}else{1831error("unable to delete existing%s", newrefname);1832goto rollback;1833}1834}18351836if(log &&rename_tmp_log(refs, newrefname))1837goto rollback;18381839 logmoved = log;18401841 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1842 REF_NODEREF, NULL, &err);1843if(!lock) {1844error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1845strbuf_release(&err);1846goto rollback;1847}1848oidcpy(&lock->old_oid, &orig_oid);18491850if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1851commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1852error("unable to write current sha1 into%s:%s", newrefname, err.buf);1853strbuf_release(&err);1854goto rollback;1855}18561857 ret =0;1858goto out;18591860 rollback:1861 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1862 REF_NODEREF, NULL, &err);1863if(!lock) {1864error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1865strbuf_release(&err);1866goto rollbacklog;1867}18681869 flag = log_all_ref_updates;1870 log_all_ref_updates = LOG_REFS_NONE;1871if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1872commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1873error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1874strbuf_release(&err);1875}1876 log_all_ref_updates = flag;18771878 rollbacklog:1879if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1880error("unable to restore logfile%sfrom%s:%s",1881 oldrefname, newrefname,strerror(errno));1882if(!logmoved && log &&1883rename(tmp_renamed_log.buf, sb_oldref.buf))1884error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1885 oldrefname,strerror(errno));1886 ret =1;1887 out:1888strbuf_release(&sb_newref);1889strbuf_release(&sb_oldref);1890strbuf_release(&tmp_renamed_log);18911892return ret;1893}18941895static intclose_ref(struct ref_lock *lock)1896{1897if(close_lock_file(lock->lk))1898return-1;1899return0;1900}19011902static intcommit_ref(struct ref_lock *lock)1903{1904char*path =get_locked_file_path(lock->lk);1905struct stat st;19061907if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1908/*1909 * There is a directory at the path we want to rename1910 * the lockfile to. Hopefully it is empty; try to1911 * delete it.1912 */1913size_t len =strlen(path);1914struct strbuf sb_path = STRBUF_INIT;19151916strbuf_attach(&sb_path, path, len, len);19171918/*1919 * If this fails, commit_lock_file() will also fail1920 * and will report the problem.1921 */1922remove_empty_directories(&sb_path);1923strbuf_release(&sb_path);1924}else{1925free(path);1926}19271928if(commit_lock_file(lock->lk))1929return-1;1930return0;1931}19321933static intopen_or_create_logfile(const char*path,void*cb)1934{1935int*fd = cb;19361937*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1938return(*fd <0) ? -1:0;1939}19401941/*1942 * Create a reflog for a ref. If force_create = 0, only create the1943 * reflog for certain refs (those for which should_autocreate_reflog1944 * returns non-zero). Otherwise, create it regardless of the reference1945 * name. If the logfile already existed or was created, return 0 and1946 * set *logfd to the file descriptor opened for appending to the file.1947 * If no logfile exists and we decided not to create one, return 0 and1948 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1949 * return -1.1950 */1951static intlog_ref_setup(struct files_ref_store *refs,1952const char*refname,int force_create,1953int*logfd,struct strbuf *err)1954{1955struct strbuf logfile_sb = STRBUF_INIT;1956char*logfile;19571958files_reflog_path(refs, &logfile_sb, refname);1959 logfile =strbuf_detach(&logfile_sb, NULL);19601961if(force_create ||should_autocreate_reflog(refname)) {1962if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1963if(errno == ENOENT)1964strbuf_addf(err,"unable to create directory for '%s': "1965"%s", logfile,strerror(errno));1966else if(errno == EISDIR)1967strbuf_addf(err,"there are still logs under '%s'",1968 logfile);1969else1970strbuf_addf(err,"unable to append to '%s':%s",1971 logfile,strerror(errno));19721973goto error;1974}1975}else{1976*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1977if(*logfd <0) {1978if(errno == ENOENT || errno == EISDIR) {1979/*1980 * The logfile doesn't already exist,1981 * but that is not an error; it only1982 * means that we won't write log1983 * entries to it.1984 */1985;1986}else{1987strbuf_addf(err,"unable to append to '%s':%s",1988 logfile,strerror(errno));1989goto error;1990}1991}1992}19931994if(*logfd >=0)1995adjust_shared_perm(logfile);19961997free(logfile);1998return0;19992000error:2001free(logfile);2002return-1;2003}20042005static intfiles_create_reflog(struct ref_store *ref_store,2006const char*refname,int force_create,2007struct strbuf *err)2008{2009struct files_ref_store *refs =2010files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2011int fd;20122013if(log_ref_setup(refs, refname, force_create, &fd, err))2014return-1;20152016if(fd >=0)2017close(fd);20182019return0;2020}20212022static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2023const struct object_id *new_oid,2024const char*committer,const char*msg)2025{2026int msglen, written;2027unsigned maxlen, len;2028char*logrec;20292030 msglen = msg ?strlen(msg) :0;2031 maxlen =strlen(committer) + msglen +100;2032 logrec =xmalloc(maxlen);2033 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2034oid_to_hex(old_oid),2035oid_to_hex(new_oid),2036 committer);2037if(msglen)2038 len +=copy_reflog_msg(logrec + len -1, msg) -1;20392040 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2041free(logrec);2042if(written != len)2043return-1;20442045return0;2046}20472048static intfiles_log_ref_write(struct files_ref_store *refs,2049const char*refname,const struct object_id *old_oid,2050const struct object_id *new_oid,const char*msg,2051int flags,struct strbuf *err)2052{2053int logfd, result;20542055if(log_all_ref_updates == LOG_REFS_UNSET)2056 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20572058 result =log_ref_setup(refs, refname,2059 flags & REF_FORCE_CREATE_REFLOG,2060&logfd, err);20612062if(result)2063return result;20642065if(logfd <0)2066return0;2067 result =log_ref_write_fd(logfd, old_oid, new_oid,2068git_committer_info(0), msg);2069if(result) {2070struct strbuf sb = STRBUF_INIT;2071int save_errno = errno;20722073files_reflog_path(refs, &sb, refname);2074strbuf_addf(err,"unable to append to '%s':%s",2075 sb.buf,strerror(save_errno));2076strbuf_release(&sb);2077close(logfd);2078return-1;2079}2080if(close(logfd)) {2081struct strbuf sb = STRBUF_INIT;2082int save_errno = errno;20832084files_reflog_path(refs, &sb, refname);2085strbuf_addf(err,"unable to append to '%s':%s",2086 sb.buf,strerror(save_errno));2087strbuf_release(&sb);2088return-1;2089}2090return0;2091}20922093/*2094 * Write sha1 into the open lockfile, then close the lockfile. On2095 * errors, rollback the lockfile, fill in *err and2096 * return -1.2097 */2098static intwrite_ref_to_lockfile(struct ref_lock *lock,2099const struct object_id *oid,struct strbuf *err)2100{2101static char term ='\n';2102struct object *o;2103int fd;21042105 o =parse_object(oid);2106if(!o) {2107strbuf_addf(err,2108"trying to write ref '%s' with nonexistent object%s",2109 lock->ref_name,oid_to_hex(oid));2110unlock_ref(lock);2111return-1;2112}2113if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2114strbuf_addf(err,2115"trying to write non-commit object%sto branch '%s'",2116oid_to_hex(oid), lock->ref_name);2117unlock_ref(lock);2118return-1;2119}2120 fd =get_lock_file_fd(lock->lk);2121if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2122write_in_full(fd, &term,1) !=1||2123close_ref(lock) <0) {2124strbuf_addf(err,2125"couldn't write '%s'",get_lock_file_path(lock->lk));2126unlock_ref(lock);2127return-1;2128}2129return0;2130}21312132/*2133 * Commit a change to a loose reference that has already been written2134 * to the loose reference lockfile. Also update the reflogs if2135 * necessary, using the specified lockmsg (which can be NULL).2136 */2137static intcommit_ref_update(struct files_ref_store *refs,2138struct ref_lock *lock,2139const struct object_id *oid,const char*logmsg,2140struct strbuf *err)2141{2142files_assert_main_repository(refs,"commit_ref_update");21432144clear_loose_ref_cache(refs);2145if(files_log_ref_write(refs, lock->ref_name,2146&lock->old_oid, oid,2147 logmsg,0, err)) {2148char*old_msg =strbuf_detach(err, NULL);2149strbuf_addf(err,"cannot update the ref '%s':%s",2150 lock->ref_name, old_msg);2151free(old_msg);2152unlock_ref(lock);2153return-1;2154}21552156if(strcmp(lock->ref_name,"HEAD") !=0) {2157/*2158 * Special hack: If a branch is updated directly and HEAD2159 * points to it (may happen on the remote side of a push2160 * for example) then logically the HEAD reflog should be2161 * updated too.2162 * A generic solution implies reverse symref information,2163 * but finding all symrefs pointing to the given branch2164 * would be rather costly for this rare event (the direct2165 * update of a branch) to be worth it. So let's cheat and2166 * check with HEAD only which should cover 99% of all usage2167 * scenarios (even 100% of the default ones).2168 */2169struct object_id head_oid;2170int head_flag;2171const char*head_ref;21722173 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2174 RESOLVE_REF_READING,2175 head_oid.hash, &head_flag);2176if(head_ref && (head_flag & REF_ISSYMREF) &&2177!strcmp(head_ref, lock->ref_name)) {2178struct strbuf log_err = STRBUF_INIT;2179if(files_log_ref_write(refs,"HEAD",2180&lock->old_oid, oid,2181 logmsg,0, &log_err)) {2182error("%s", log_err.buf);2183strbuf_release(&log_err);2184}2185}2186}21872188if(commit_ref(lock)) {2189strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2190unlock_ref(lock);2191return-1;2192}21932194unlock_ref(lock);2195return0;2196}21972198static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2199{2200int ret = -1;2201#ifndef NO_SYMLINK_HEAD2202char*ref_path =get_locked_file_path(lock->lk);2203unlink(ref_path);2204 ret =symlink(target, ref_path);2205free(ref_path);22062207if(ret)2208fprintf(stderr,"no symlink - falling back to symbolic ref\n");2209#endif2210return ret;2211}22122213static voidupdate_symref_reflog(struct files_ref_store *refs,2214struct ref_lock *lock,const char*refname,2215const char*target,const char*logmsg)2216{2217struct strbuf err = STRBUF_INIT;2218struct object_id new_oid;2219if(logmsg &&2220!refs_read_ref_full(&refs->base, target,2221 RESOLVE_REF_READING, new_oid.hash, NULL) &&2222files_log_ref_write(refs, refname, &lock->old_oid,2223&new_oid, logmsg,0, &err)) {2224error("%s", err.buf);2225strbuf_release(&err);2226}2227}22282229static intcreate_symref_locked(struct files_ref_store *refs,2230struct ref_lock *lock,const char*refname,2231const char*target,const char*logmsg)2232{2233if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2234update_symref_reflog(refs, lock, refname, target, logmsg);2235return0;2236}22372238if(!fdopen_lock_file(lock->lk,"w"))2239returnerror("unable to fdopen%s:%s",2240 lock->lk->tempfile.filename.buf,strerror(errno));22412242update_symref_reflog(refs, lock, refname, target, logmsg);22432244/* no error check; commit_ref will check ferror */2245fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2246if(commit_ref(lock) <0)2247returnerror("unable to write symref for%s:%s", refname,2248strerror(errno));2249return0;2250}22512252static intfiles_create_symref(struct ref_store *ref_store,2253const char*refname,const char*target,2254const char*logmsg)2255{2256struct files_ref_store *refs =2257files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2258struct strbuf err = STRBUF_INIT;2259struct ref_lock *lock;2260int ret;22612262 lock =lock_ref_sha1_basic(refs, refname, NULL,2263 NULL, NULL, REF_NODEREF, NULL,2264&err);2265if(!lock) {2266error("%s", err.buf);2267strbuf_release(&err);2268return-1;2269}22702271 ret =create_symref_locked(refs, lock, refname, target, logmsg);2272unlock_ref(lock);2273return ret;2274}22752276static intfiles_reflog_exists(struct ref_store *ref_store,2277const char*refname)2278{2279struct files_ref_store *refs =2280files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2281struct strbuf sb = STRBUF_INIT;2282struct stat st;2283int ret;22842285files_reflog_path(refs, &sb, refname);2286 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2287strbuf_release(&sb);2288return ret;2289}22902291static intfiles_delete_reflog(struct ref_store *ref_store,2292const char*refname)2293{2294struct files_ref_store *refs =2295files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2296struct strbuf sb = STRBUF_INIT;2297int ret;22982299files_reflog_path(refs, &sb, refname);2300 ret =remove_path(sb.buf);2301strbuf_release(&sb);2302return ret;2303}23042305static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2306{2307struct object_id ooid, noid;2308char*email_end, *message;2309 timestamp_t timestamp;2310int tz;2311const char*p = sb->buf;23122313/* old SP new SP name <email> SP time TAB msg LF */2314if(!sb->len || sb->buf[sb->len -1] !='\n'||2315parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2316parse_oid_hex(p, &noid, &p) || *p++ !=' '||2317!(email_end =strchr(p,'>')) ||2318 email_end[1] !=' '||2319!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2320!message || message[0] !=' '||2321(message[1] !='+'&& message[1] !='-') ||2322!isdigit(message[2]) || !isdigit(message[3]) ||2323!isdigit(message[4]) || !isdigit(message[5]))2324return0;/* corrupt? */2325 email_end[1] ='\0';2326 tz =strtol(message +1, NULL,10);2327if(message[6] !='\t')2328 message +=6;2329else2330 message +=7;2331returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2332}23332334static char*find_beginning_of_line(char*bob,char*scan)2335{2336while(bob < scan && *(--scan) !='\n')2337;/* keep scanning backwards */2338/*2339 * Return either beginning of the buffer, or LF at the end of2340 * the previous line.2341 */2342return scan;2343}23442345static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2346const char*refname,2347 each_reflog_ent_fn fn,2348void*cb_data)2349{2350struct files_ref_store *refs =2351files_downcast(ref_store, REF_STORE_READ,2352"for_each_reflog_ent_reverse");2353struct strbuf sb = STRBUF_INIT;2354FILE*logfp;2355long pos;2356int ret =0, at_tail =1;23572358files_reflog_path(refs, &sb, refname);2359 logfp =fopen(sb.buf,"r");2360strbuf_release(&sb);2361if(!logfp)2362return-1;23632364/* Jump to the end */2365if(fseek(logfp,0, SEEK_END) <0)2366 ret =error("cannot seek back reflog for%s:%s",2367 refname,strerror(errno));2368 pos =ftell(logfp);2369while(!ret &&0< pos) {2370int cnt;2371size_t nread;2372char buf[BUFSIZ];2373char*endp, *scanp;23742375/* Fill next block from the end */2376 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2377if(fseek(logfp, pos - cnt, SEEK_SET)) {2378 ret =error("cannot seek back reflog for%s:%s",2379 refname,strerror(errno));2380break;2381}2382 nread =fread(buf, cnt,1, logfp);2383if(nread !=1) {2384 ret =error("cannot read%dbytes from reflog for%s:%s",2385 cnt, refname,strerror(errno));2386break;2387}2388 pos -= cnt;23892390 scanp = endp = buf + cnt;2391if(at_tail && scanp[-1] =='\n')2392/* Looking at the final LF at the end of the file */2393 scanp--;2394 at_tail =0;23952396while(buf < scanp) {2397/*2398 * terminating LF of the previous line, or the beginning2399 * of the buffer.2400 */2401char*bp;24022403 bp =find_beginning_of_line(buf, scanp);24042405if(*bp =='\n') {2406/*2407 * The newline is the end of the previous line,2408 * so we know we have complete line starting2409 * at (bp + 1). Prefix it onto any prior data2410 * we collected for the line and process it.2411 */2412strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2413 scanp = bp;2414 endp = bp +1;2415 ret =show_one_reflog_ent(&sb, fn, cb_data);2416strbuf_reset(&sb);2417if(ret)2418break;2419}else if(!pos) {2420/*2421 * We are at the start of the buffer, and the2422 * start of the file; there is no previous2423 * line, and we have everything for this one.2424 * Process it, and we can end the loop.2425 */2426strbuf_splice(&sb,0,0, buf, endp - buf);2427 ret =show_one_reflog_ent(&sb, fn, cb_data);2428strbuf_reset(&sb);2429break;2430}24312432if(bp == buf) {2433/*2434 * We are at the start of the buffer, and there2435 * is more file to read backwards. Which means2436 * we are in the middle of a line. Note that we2437 * may get here even if *bp was a newline; that2438 * just means we are at the exact end of the2439 * previous line, rather than some spot in the2440 * middle.2441 *2442 * Save away what we have to be combined with2443 * the data from the next read.2444 */2445strbuf_splice(&sb,0,0, buf, endp - buf);2446break;2447}2448}24492450}2451if(!ret && sb.len)2452die("BUG: reverse reflog parser had leftover data");24532454fclose(logfp);2455strbuf_release(&sb);2456return ret;2457}24582459static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2460const char*refname,2461 each_reflog_ent_fn fn,void*cb_data)2462{2463struct files_ref_store *refs =2464files_downcast(ref_store, REF_STORE_READ,2465"for_each_reflog_ent");2466FILE*logfp;2467struct strbuf sb = STRBUF_INIT;2468int ret =0;24692470files_reflog_path(refs, &sb, refname);2471 logfp =fopen(sb.buf,"r");2472strbuf_release(&sb);2473if(!logfp)2474return-1;24752476while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2477 ret =show_one_reflog_ent(&sb, fn, cb_data);2478fclose(logfp);2479strbuf_release(&sb);2480return ret;2481}24822483struct files_reflog_iterator {2484struct ref_iterator base;24852486struct ref_store *ref_store;2487struct dir_iterator *dir_iterator;2488struct object_id oid;2489};24902491static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2492{2493struct files_reflog_iterator *iter =2494(struct files_reflog_iterator *)ref_iterator;2495struct dir_iterator *diter = iter->dir_iterator;2496int ok;24972498while((ok =dir_iterator_advance(diter)) == ITER_OK) {2499int flags;25002501if(!S_ISREG(diter->st.st_mode))2502continue;2503if(diter->basename[0] =='.')2504continue;2505if(ends_with(diter->basename,".lock"))2506continue;25072508if(refs_read_ref_full(iter->ref_store,2509 diter->relative_path,0,2510 iter->oid.hash, &flags)) {2511error("bad ref for%s", diter->path.buf);2512continue;2513}25142515 iter->base.refname = diter->relative_path;2516 iter->base.oid = &iter->oid;2517 iter->base.flags = flags;2518return ITER_OK;2519}25202521 iter->dir_iterator = NULL;2522if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2523 ok = ITER_ERROR;2524return ok;2525}25262527static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2528struct object_id *peeled)2529{2530die("BUG: ref_iterator_peel() called for reflog_iterator");2531}25322533static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2534{2535struct files_reflog_iterator *iter =2536(struct files_reflog_iterator *)ref_iterator;2537int ok = ITER_DONE;25382539if(iter->dir_iterator)2540 ok =dir_iterator_abort(iter->dir_iterator);25412542base_ref_iterator_free(ref_iterator);2543return ok;2544}25452546static struct ref_iterator_vtable files_reflog_iterator_vtable = {2547 files_reflog_iterator_advance,2548 files_reflog_iterator_peel,2549 files_reflog_iterator_abort2550};25512552static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2553{2554struct files_ref_store *refs =2555files_downcast(ref_store, REF_STORE_READ,2556"reflog_iterator_begin");2557struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2558struct ref_iterator *ref_iterator = &iter->base;2559struct strbuf sb = STRBUF_INIT;25602561base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2562files_reflog_path(refs, &sb, NULL);2563 iter->dir_iterator =dir_iterator_begin(sb.buf);2564 iter->ref_store = ref_store;2565strbuf_release(&sb);2566return ref_iterator;2567}25682569/*2570 * If update is a direct update of head_ref (the reference pointed to2571 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2572 */2573static intsplit_head_update(struct ref_update *update,2574struct ref_transaction *transaction,2575const char*head_ref,2576struct string_list *affected_refnames,2577struct strbuf *err)2578{2579struct string_list_item *item;2580struct ref_update *new_update;25812582if((update->flags & REF_LOG_ONLY) ||2583(update->flags & REF_ISPRUNING) ||2584(update->flags & REF_UPDATE_VIA_HEAD))2585return0;25862587if(strcmp(update->refname, head_ref))2588return0;25892590/*2591 * First make sure that HEAD is not already in the2592 * transaction. This insertion is O(N) in the transaction2593 * size, but it happens at most once per transaction.2594 */2595 item =string_list_insert(affected_refnames,"HEAD");2596if(item->util) {2597/* An entry already existed */2598strbuf_addf(err,2599"multiple updates for 'HEAD' (including one "2600"via its referent '%s') are not allowed",2601 update->refname);2602return TRANSACTION_NAME_CONFLICT;2603}26042605 new_update =ref_transaction_add_update(2606 transaction,"HEAD",2607 update->flags | REF_LOG_ONLY | REF_NODEREF,2608 update->new_oid.hash, update->old_oid.hash,2609 update->msg);26102611 item->util = new_update;26122613return0;2614}26152616/*2617 * update is for a symref that points at referent and doesn't have2618 * REF_NODEREF set. Split it into two updates:2619 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2620 * - A new, separate update for the referent reference2621 * Note that the new update will itself be subject to splitting when2622 * the iteration gets to it.2623 */2624static intsplit_symref_update(struct files_ref_store *refs,2625struct ref_update *update,2626const char*referent,2627struct ref_transaction *transaction,2628struct string_list *affected_refnames,2629struct strbuf *err)2630{2631struct string_list_item *item;2632struct ref_update *new_update;2633unsigned int new_flags;26342635/*2636 * First make sure that referent is not already in the2637 * transaction. This insertion is O(N) in the transaction2638 * size, but it happens at most once per symref in a2639 * transaction.2640 */2641 item =string_list_insert(affected_refnames, referent);2642if(item->util) {2643/* An entry already existed */2644strbuf_addf(err,2645"multiple updates for '%s' (including one "2646"via symref '%s') are not allowed",2647 referent, update->refname);2648return TRANSACTION_NAME_CONFLICT;2649}26502651 new_flags = update->flags;2652if(!strcmp(update->refname,"HEAD")) {2653/*2654 * Record that the new update came via HEAD, so that2655 * when we process it, split_head_update() doesn't try2656 * to add another reflog update for HEAD. Note that2657 * this bit will be propagated if the new_update2658 * itself needs to be split.2659 */2660 new_flags |= REF_UPDATE_VIA_HEAD;2661}26622663 new_update =ref_transaction_add_update(2664 transaction, referent, new_flags,2665 update->new_oid.hash, update->old_oid.hash,2666 update->msg);26672668 new_update->parent_update = update;26692670/*2671 * Change the symbolic ref update to log only. Also, it2672 * doesn't need to check its old SHA-1 value, as that will be2673 * done when new_update is processed.2674 */2675 update->flags |= REF_LOG_ONLY | REF_NODEREF;2676 update->flags &= ~REF_HAVE_OLD;26772678 item->util = new_update;26792680return0;2681}26822683/*2684 * Return the refname under which update was originally requested.2685 */2686static const char*original_update_refname(struct ref_update *update)2687{2688while(update->parent_update)2689 update = update->parent_update;26902691return update->refname;2692}26932694/*2695 * Check whether the REF_HAVE_OLD and old_oid values stored in update2696 * are consistent with oid, which is the reference's current value. If2697 * everything is OK, return 0; otherwise, write an error message to2698 * err and return -1.2699 */2700static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2701struct strbuf *err)2702{2703if(!(update->flags & REF_HAVE_OLD) ||2704!oidcmp(oid, &update->old_oid))2705return0;27062707if(is_null_oid(&update->old_oid))2708strbuf_addf(err,"cannot lock ref '%s': "2709"reference already exists",2710original_update_refname(update));2711else if(is_null_oid(oid))2712strbuf_addf(err,"cannot lock ref '%s': "2713"reference is missing but expected%s",2714original_update_refname(update),2715oid_to_hex(&update->old_oid));2716else2717strbuf_addf(err,"cannot lock ref '%s': "2718"is at%sbut expected%s",2719original_update_refname(update),2720oid_to_hex(oid),2721oid_to_hex(&update->old_oid));27222723return-1;2724}27252726/*2727 * Prepare for carrying out update:2728 * - Lock the reference referred to by update.2729 * - Read the reference under lock.2730 * - Check that its old SHA-1 value (if specified) is correct, and in2731 * any case record it in update->lock->old_oid for later use when2732 * writing the reflog.2733 * - If it is a symref update without REF_NODEREF, split it up into a2734 * REF_LOG_ONLY update of the symref and add a separate update for2735 * the referent to transaction.2736 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2737 * update of HEAD.2738 */2739static intlock_ref_for_update(struct files_ref_store *refs,2740struct ref_update *update,2741struct ref_transaction *transaction,2742const char*head_ref,2743struct string_list *affected_refnames,2744struct strbuf *err)2745{2746struct strbuf referent = STRBUF_INIT;2747int mustexist = (update->flags & REF_HAVE_OLD) &&2748!is_null_oid(&update->old_oid);2749int ret;2750struct ref_lock *lock;27512752files_assert_main_repository(refs,"lock_ref_for_update");27532754if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2755 update->flags |= REF_DELETING;27562757if(head_ref) {2758 ret =split_head_update(update, transaction, head_ref,2759 affected_refnames, err);2760if(ret)2761return ret;2762}27632764 ret =lock_raw_ref(refs, update->refname, mustexist,2765 affected_refnames, NULL,2766&lock, &referent,2767&update->type, err);2768if(ret) {2769char*reason;27702771 reason =strbuf_detach(err, NULL);2772strbuf_addf(err,"cannot lock ref '%s':%s",2773original_update_refname(update), reason);2774free(reason);2775return ret;2776}27772778 update->backend_data = lock;27792780if(update->type & REF_ISSYMREF) {2781if(update->flags & REF_NODEREF) {2782/*2783 * We won't be reading the referent as part of2784 * the transaction, so we have to read it here2785 * to record and possibly check old_sha1:2786 */2787if(refs_read_ref_full(&refs->base,2788 referent.buf,0,2789 lock->old_oid.hash, NULL)) {2790if(update->flags & REF_HAVE_OLD) {2791strbuf_addf(err,"cannot lock ref '%s': "2792"error reading reference",2793original_update_refname(update));2794return-1;2795}2796}else if(check_old_oid(update, &lock->old_oid, err)) {2797return TRANSACTION_GENERIC_ERROR;2798}2799}else{2800/*2801 * Create a new update for the reference this2802 * symref is pointing at. Also, we will record2803 * and verify old_sha1 for this update as part2804 * of processing the split-off update, so we2805 * don't have to do it here.2806 */2807 ret =split_symref_update(refs, update,2808 referent.buf, transaction,2809 affected_refnames, err);2810if(ret)2811return ret;2812}2813}else{2814struct ref_update *parent_update;28152816if(check_old_oid(update, &lock->old_oid, err))2817return TRANSACTION_GENERIC_ERROR;28182819/*2820 * If this update is happening indirectly because of a2821 * symref update, record the old SHA-1 in the parent2822 * update:2823 */2824for(parent_update = update->parent_update;2825 parent_update;2826 parent_update = parent_update->parent_update) {2827struct ref_lock *parent_lock = parent_update->backend_data;2828oidcpy(&parent_lock->old_oid, &lock->old_oid);2829}2830}28312832if((update->flags & REF_HAVE_NEW) &&2833!(update->flags & REF_DELETING) &&2834!(update->flags & REF_LOG_ONLY)) {2835if(!(update->type & REF_ISSYMREF) &&2836!oidcmp(&lock->old_oid, &update->new_oid)) {2837/*2838 * The reference already has the desired2839 * value, so we don't need to write it.2840 */2841}else if(write_ref_to_lockfile(lock, &update->new_oid,2842 err)) {2843char*write_err =strbuf_detach(err, NULL);28442845/*2846 * The lock was freed upon failure of2847 * write_ref_to_lockfile():2848 */2849 update->backend_data = NULL;2850strbuf_addf(err,2851"cannot update ref '%s':%s",2852 update->refname, write_err);2853free(write_err);2854return TRANSACTION_GENERIC_ERROR;2855}else{2856 update->flags |= REF_NEEDS_COMMIT;2857}2858}2859if(!(update->flags & REF_NEEDS_COMMIT)) {2860/*2861 * We didn't call write_ref_to_lockfile(), so2862 * the lockfile is still open. Close it to2863 * free up the file descriptor:2864 */2865if(close_ref(lock)) {2866strbuf_addf(err,"couldn't close '%s.lock'",2867 update->refname);2868return TRANSACTION_GENERIC_ERROR;2869}2870}2871return0;2872}28732874/*2875 * Unlock any references in `transaction` that are still locked, and2876 * mark the transaction closed.2877 */2878static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2879{2880size_t i;28812882for(i =0; i < transaction->nr; i++) {2883struct ref_update *update = transaction->updates[i];2884struct ref_lock *lock = update->backend_data;28852886if(lock) {2887unlock_ref(lock);2888 update->backend_data = NULL;2889}2890}28912892 transaction->state = REF_TRANSACTION_CLOSED;2893}28942895static intfiles_transaction_prepare(struct ref_store *ref_store,2896struct ref_transaction *transaction,2897struct strbuf *err)2898{2899struct files_ref_store *refs =2900files_downcast(ref_store, REF_STORE_WRITE,2901"ref_transaction_prepare");2902size_t i;2903int ret =0;2904struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2905char*head_ref = NULL;2906int head_type;2907struct object_id head_oid;29082909assert(err);29102911if(!transaction->nr)2912goto cleanup;29132914/*2915 * Fail if a refname appears more than once in the2916 * transaction. (If we end up splitting up any updates using2917 * split_symref_update() or split_head_update(), those2918 * functions will check that the new updates don't have the2919 * same refname as any existing ones.)2920 */2921for(i =0; i < transaction->nr; i++) {2922struct ref_update *update = transaction->updates[i];2923struct string_list_item *item =2924string_list_append(&affected_refnames, update->refname);29252926/*2927 * We store a pointer to update in item->util, but at2928 * the moment we never use the value of this field2929 * except to check whether it is non-NULL.2930 */2931 item->util = update;2932}2933string_list_sort(&affected_refnames);2934if(ref_update_reject_duplicates(&affected_refnames, err)) {2935 ret = TRANSACTION_GENERIC_ERROR;2936goto cleanup;2937}29382939/*2940 * Special hack: If a branch is updated directly and HEAD2941 * points to it (may happen on the remote side of a push2942 * for example) then logically the HEAD reflog should be2943 * updated too.2944 *2945 * A generic solution would require reverse symref lookups,2946 * but finding all symrefs pointing to a given branch would be2947 * rather costly for this rare event (the direct update of a2948 * branch) to be worth it. So let's cheat and check with HEAD2949 * only, which should cover 99% of all usage scenarios (even2950 * 100% of the default ones).2951 *2952 * So if HEAD is a symbolic reference, then record the name of2953 * the reference that it points to. If we see an update of2954 * head_ref within the transaction, then split_head_update()2955 * arranges for the reflog of HEAD to be updated, too.2956 */2957 head_ref =refs_resolve_refdup(ref_store,"HEAD",2958 RESOLVE_REF_NO_RECURSE,2959 head_oid.hash, &head_type);29602961if(head_ref && !(head_type & REF_ISSYMREF)) {2962FREE_AND_NULL(head_ref);2963}29642965/*2966 * Acquire all locks, verify old values if provided, check2967 * that new values are valid, and write new values to the2968 * lockfiles, ready to be activated. Only keep one lockfile2969 * open at a time to avoid running out of file descriptors.2970 * Note that lock_ref_for_update() might append more updates2971 * to the transaction.2972 */2973for(i =0; i < transaction->nr; i++) {2974struct ref_update *update = transaction->updates[i];29752976 ret =lock_ref_for_update(refs, update, transaction,2977 head_ref, &affected_refnames, err);2978if(ret)2979break;2980}29812982cleanup:2983free(head_ref);2984string_list_clear(&affected_refnames,0);29852986if(ret)2987files_transaction_cleanup(transaction);2988else2989 transaction->state = REF_TRANSACTION_PREPARED;29902991return ret;2992}29932994static intfiles_transaction_finish(struct ref_store *ref_store,2995struct ref_transaction *transaction,2996struct strbuf *err)2997{2998struct files_ref_store *refs =2999files_downcast(ref_store,0,"ref_transaction_finish");3000size_t i;3001int ret =0;3002struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3003struct string_list_item *ref_to_delete;3004struct strbuf sb = STRBUF_INIT;30053006assert(err);30073008if(!transaction->nr) {3009 transaction->state = REF_TRANSACTION_CLOSED;3010return0;3011}30123013/* Perform updates first so live commits remain referenced */3014for(i =0; i < transaction->nr; i++) {3015struct ref_update *update = transaction->updates[i];3016struct ref_lock *lock = update->backend_data;30173018if(update->flags & REF_NEEDS_COMMIT ||3019 update->flags & REF_LOG_ONLY) {3020if(files_log_ref_write(refs,3021 lock->ref_name,3022&lock->old_oid,3023&update->new_oid,3024 update->msg, update->flags,3025 err)) {3026char*old_msg =strbuf_detach(err, NULL);30273028strbuf_addf(err,"cannot update the ref '%s':%s",3029 lock->ref_name, old_msg);3030free(old_msg);3031unlock_ref(lock);3032 update->backend_data = NULL;3033 ret = TRANSACTION_GENERIC_ERROR;3034goto cleanup;3035}3036}3037if(update->flags & REF_NEEDS_COMMIT) {3038clear_loose_ref_cache(refs);3039if(commit_ref(lock)) {3040strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3041unlock_ref(lock);3042 update->backend_data = NULL;3043 ret = TRANSACTION_GENERIC_ERROR;3044goto cleanup;3045}3046}3047}3048/* Perform deletes now that updates are safely completed */3049for(i =0; i < transaction->nr; i++) {3050struct ref_update *update = transaction->updates[i];3051struct ref_lock *lock = update->backend_data;30523053if(update->flags & REF_DELETING &&3054!(update->flags & REF_LOG_ONLY)) {3055if(!(update->type & REF_ISPACKED) ||3056 update->type & REF_ISSYMREF) {3057/* It is a loose reference. */3058strbuf_reset(&sb);3059files_ref_path(refs, &sb, lock->ref_name);3060if(unlink_or_msg(sb.buf, err)) {3061 ret = TRANSACTION_GENERIC_ERROR;3062goto cleanup;3063}3064 update->flags |= REF_DELETED_LOOSE;3065}30663067if(!(update->flags & REF_ISPRUNING))3068string_list_append(&refs_to_delete,3069 lock->ref_name);3070}3071}30723073if(repack_without_refs(refs, &refs_to_delete, err)) {3074 ret = TRANSACTION_GENERIC_ERROR;3075goto cleanup;3076}30773078/* Delete the reflogs of any references that were deleted: */3079for_each_string_list_item(ref_to_delete, &refs_to_delete) {3080strbuf_reset(&sb);3081files_reflog_path(refs, &sb, ref_to_delete->string);3082if(!unlink_or_warn(sb.buf))3083try_remove_empty_parents(refs, ref_to_delete->string,3084 REMOVE_EMPTY_PARENTS_REFLOG);3085}30863087clear_loose_ref_cache(refs);30883089cleanup:3090files_transaction_cleanup(transaction);30913092for(i =0; i < transaction->nr; i++) {3093struct ref_update *update = transaction->updates[i];30943095if(update->flags & REF_DELETED_LOOSE) {3096/*3097 * The loose reference was deleted. Delete any3098 * empty parent directories. (Note that this3099 * can only work because we have already3100 * removed the lockfile.)3101 */3102try_remove_empty_parents(refs, update->refname,3103 REMOVE_EMPTY_PARENTS_REF);3104}3105}31063107strbuf_release(&sb);3108string_list_clear(&refs_to_delete,0);3109return ret;3110}31113112static intfiles_transaction_abort(struct ref_store *ref_store,3113struct ref_transaction *transaction,3114struct strbuf *err)3115{3116files_transaction_cleanup(transaction);3117return0;3118}31193120static intref_present(const char*refname,3121const struct object_id *oid,int flags,void*cb_data)3122{3123struct string_list *affected_refnames = cb_data;31243125returnstring_list_has_string(affected_refnames, refname);3126}31273128static intfiles_initial_transaction_commit(struct ref_store *ref_store,3129struct ref_transaction *transaction,3130struct strbuf *err)3131{3132struct files_ref_store *refs =3133files_downcast(ref_store, REF_STORE_WRITE,3134"initial_ref_transaction_commit");3135size_t i;3136int ret =0;3137struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31383139assert(err);31403141if(transaction->state != REF_TRANSACTION_OPEN)3142die("BUG: commit called for transaction that is not open");31433144/* Fail if a refname appears more than once in the transaction: */3145for(i =0; i < transaction->nr; i++)3146string_list_append(&affected_refnames,3147 transaction->updates[i]->refname);3148string_list_sort(&affected_refnames);3149if(ref_update_reject_duplicates(&affected_refnames, err)) {3150 ret = TRANSACTION_GENERIC_ERROR;3151goto cleanup;3152}31533154/*3155 * It's really undefined to call this function in an active3156 * repository or when there are existing references: we are3157 * only locking and changing packed-refs, so (1) any3158 * simultaneous processes might try to change a reference at3159 * the same time we do, and (2) any existing loose versions of3160 * the references that we are setting would have precedence3161 * over our values. But some remote helpers create the remote3162 * "HEAD" and "master" branches before calling this function,3163 * so here we really only check that none of the references3164 * that we are creating already exists.3165 */3166if(refs_for_each_rawref(&refs->base, ref_present,3167&affected_refnames))3168die("BUG: initial ref transaction called with existing refs");31693170for(i =0; i < transaction->nr; i++) {3171struct ref_update *update = transaction->updates[i];31723173if((update->flags & REF_HAVE_OLD) &&3174!is_null_oid(&update->old_oid))3175die("BUG: initial ref transaction with old_sha1 set");3176if(refs_verify_refname_available(&refs->base, update->refname,3177&affected_refnames, NULL,3178 err)) {3179 ret = TRANSACTION_NAME_CONFLICT;3180goto cleanup;3181}3182}31833184if(lock_packed_refs(refs,0)) {3185strbuf_addf(err,"unable to lock packed-refs file:%s",3186strerror(errno));3187 ret = TRANSACTION_GENERIC_ERROR;3188goto cleanup;3189}31903191for(i =0; i < transaction->nr; i++) {3192struct ref_update *update = transaction->updates[i];31933194if((update->flags & REF_HAVE_NEW) &&3195!is_null_oid(&update->new_oid))3196add_packed_ref(refs, update->refname,3197&update->new_oid);3198}31993200if(commit_packed_refs(refs)) {3201strbuf_addf(err,"unable to commit packed-refs file:%s",3202strerror(errno));3203 ret = TRANSACTION_GENERIC_ERROR;3204goto cleanup;3205}32063207cleanup:3208 transaction->state = REF_TRANSACTION_CLOSED;3209string_list_clear(&affected_refnames,0);3210return ret;3211}32123213struct expire_reflog_cb {3214unsigned int flags;3215 reflog_expiry_should_prune_fn *should_prune_fn;3216void*policy_cb;3217FILE*newlog;3218struct object_id last_kept_oid;3219};32203221static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3222const char*email, timestamp_t timestamp,int tz,3223const char*message,void*cb_data)3224{3225struct expire_reflog_cb *cb = cb_data;3226struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32273228if(cb->flags & EXPIRE_REFLOGS_REWRITE)3229 ooid = &cb->last_kept_oid;32303231if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3232 message, policy_cb)) {3233if(!cb->newlog)3234printf("would prune%s", message);3235else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3236printf("prune%s", message);3237}else{3238if(cb->newlog) {3239fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3240oid_to_hex(ooid),oid_to_hex(noid),3241 email, timestamp, tz, message);3242oidcpy(&cb->last_kept_oid, noid);3243}3244if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3245printf("keep%s", message);3246}3247return0;3248}32493250static intfiles_reflog_expire(struct ref_store *ref_store,3251const char*refname,const unsigned char*sha1,3252unsigned int flags,3253 reflog_expiry_prepare_fn prepare_fn,3254 reflog_expiry_should_prune_fn should_prune_fn,3255 reflog_expiry_cleanup_fn cleanup_fn,3256void*policy_cb_data)3257{3258struct files_ref_store *refs =3259files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3260static struct lock_file reflog_lock;3261struct expire_reflog_cb cb;3262struct ref_lock *lock;3263struct strbuf log_file_sb = STRBUF_INIT;3264char*log_file;3265int status =0;3266int type;3267struct strbuf err = STRBUF_INIT;3268struct object_id oid;32693270memset(&cb,0,sizeof(cb));3271 cb.flags = flags;3272 cb.policy_cb = policy_cb_data;3273 cb.should_prune_fn = should_prune_fn;32743275/*3276 * The reflog file is locked by holding the lock on the3277 * reference itself, plus we might need to update the3278 * reference if --updateref was specified:3279 */3280 lock =lock_ref_sha1_basic(refs, refname, sha1,3281 NULL, NULL, REF_NODEREF,3282&type, &err);3283if(!lock) {3284error("cannot lock ref '%s':%s", refname, err.buf);3285strbuf_release(&err);3286return-1;3287}3288if(!refs_reflog_exists(ref_store, refname)) {3289unlock_ref(lock);3290return0;3291}32923293files_reflog_path(refs, &log_file_sb, refname);3294 log_file =strbuf_detach(&log_file_sb, NULL);3295if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3296/*3297 * Even though holding $GIT_DIR/logs/$reflog.lock has3298 * no locking implications, we use the lock_file3299 * machinery here anyway because it does a lot of the3300 * work we need, including cleaning up if the program3301 * exits unexpectedly.3302 */3303if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3304struct strbuf err = STRBUF_INIT;3305unable_to_lock_message(log_file, errno, &err);3306error("%s", err.buf);3307strbuf_release(&err);3308goto failure;3309}3310 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3311if(!cb.newlog) {3312error("cannot fdopen%s(%s)",3313get_lock_file_path(&reflog_lock),strerror(errno));3314goto failure;3315}3316}33173318hashcpy(oid.hash, sha1);33193320(*prepare_fn)(refname, &oid, cb.policy_cb);3321refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3322(*cleanup_fn)(cb.policy_cb);33233324if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3325/*3326 * It doesn't make sense to adjust a reference pointed3327 * to by a symbolic ref based on expiring entries in3328 * the symbolic reference's reflog. Nor can we update3329 * a reference if there are no remaining reflog3330 * entries.3331 */3332int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3333!(type & REF_ISSYMREF) &&3334!is_null_oid(&cb.last_kept_oid);33353336if(close_lock_file(&reflog_lock)) {3337 status |=error("couldn't write%s:%s", log_file,3338strerror(errno));3339}else if(update &&3340(write_in_full(get_lock_file_fd(lock->lk),3341oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3342write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3343close_ref(lock) <0)) {3344 status |=error("couldn't write%s",3345get_lock_file_path(lock->lk));3346rollback_lock_file(&reflog_lock);3347}else if(commit_lock_file(&reflog_lock)) {3348 status |=error("unable to write reflog '%s' (%s)",3349 log_file,strerror(errno));3350}else if(update &&commit_ref(lock)) {3351 status |=error("couldn't set%s", lock->ref_name);3352}3353}3354free(log_file);3355unlock_ref(lock);3356return status;33573358 failure:3359rollback_lock_file(&reflog_lock);3360free(log_file);3361unlock_ref(lock);3362return-1;3363}33643365static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3366{3367struct files_ref_store *refs =3368files_downcast(ref_store, REF_STORE_WRITE,"init_db");3369struct strbuf sb = STRBUF_INIT;33703371/*3372 * Create .git/refs/{heads,tags}3373 */3374files_ref_path(refs, &sb,"refs/heads");3375safe_create_dir(sb.buf,1);33763377strbuf_reset(&sb);3378files_ref_path(refs, &sb,"refs/tags");3379safe_create_dir(sb.buf,1);33803381strbuf_release(&sb);3382return0;3383}33843385struct ref_storage_be refs_be_files = {3386 NULL,3387"files",3388 files_ref_store_create,3389 files_init_db,3390 files_transaction_prepare,3391 files_transaction_finish,3392 files_transaction_abort,3393 files_initial_transaction_commit,33943395 files_pack_refs,3396 files_peel_ref,3397 files_create_symref,3398 files_delete_refs,3399 files_rename_ref,34003401 files_ref_iterator_begin,3402 files_read_raw_ref,34033404 files_reflog_iterator_begin,3405 files_for_each_reflog_ent,3406 files_for_each_reflog_ent_reverse,3407 files_reflog_exists,3408 files_create_reflog,3409 files_delete_reflog,3410 files_reflog_expire3411};