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_timeout( 859 lock->lk, ref_file.buf, LOCK_NO_DEREF, 860get_files_ref_lock_timeout_ms()) <0) { 861if(errno == ENOENT && --attempts_remaining >0) { 862/* 863 * Maybe somebody just deleted one of the 864 * directories leading to ref_file. Try 865 * again: 866 */ 867goto retry; 868}else{ 869unable_to_lock_message(ref_file.buf, errno, err); 870goto error_return; 871} 872} 873 874/* 875 * Now we hold the lock and can read the reference without 876 * fear that its value will change. 877 */ 878 879if(files_read_raw_ref(&refs->base, refname, 880 lock->old_oid.hash, referent, type)) { 881if(errno == ENOENT) { 882if(mustexist) { 883/* Garden variety missing reference. */ 884strbuf_addf(err,"unable to resolve reference '%s'", 885 refname); 886goto error_return; 887}else{ 888/* 889 * Reference is missing, but that's OK. We 890 * know that there is not a conflict with 891 * another loose reference because 892 * (supposing that we are trying to lock 893 * reference "refs/foo/bar"): 894 * 895 * - We were successfully able to create 896 * the lockfile refs/foo/bar.lock, so we 897 * know there cannot be a loose reference 898 * named "refs/foo". 899 * 900 * - We got ENOENT and not EISDIR, so we 901 * know that there cannot be a loose 902 * reference named "refs/foo/bar/baz". 903 */ 904} 905}else if(errno == EISDIR) { 906/* 907 * There is a directory in the way. It might have 908 * contained references that have been deleted. If 909 * we don't require that the reference already 910 * exists, try to remove the directory so that it 911 * doesn't cause trouble when we want to rename the 912 * lockfile into place later. 913 */ 914if(mustexist) { 915/* Garden variety missing reference. */ 916strbuf_addf(err,"unable to resolve reference '%s'", 917 refname); 918goto error_return; 919}else if(remove_dir_recursively(&ref_file, 920 REMOVE_DIR_EMPTY_ONLY)) { 921if(refs_verify_refname_available( 922&refs->base, refname, 923 extras, skip, err)) { 924/* 925 * The error message set by 926 * verify_refname_available() is OK. 927 */ 928 ret = TRANSACTION_NAME_CONFLICT; 929goto error_return; 930}else{ 931/* 932 * We can't delete the directory, 933 * but we also don't know of any 934 * references that it should 935 * contain. 936 */ 937strbuf_addf(err,"there is a non-empty directory '%s' " 938"blocking reference '%s'", 939 ref_file.buf, refname); 940goto error_return; 941} 942} 943}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 944strbuf_addf(err,"unable to resolve reference '%s': " 945"reference broken", refname); 946goto error_return; 947}else{ 948strbuf_addf(err,"unable to resolve reference '%s':%s", 949 refname,strerror(errno)); 950goto error_return; 951} 952 953/* 954 * If the ref did not exist and we are creating it, 955 * make sure there is no existing ref that conflicts 956 * with refname: 957 */ 958if(refs_verify_refname_available( 959&refs->base, refname, 960 extras, skip, err)) 961goto error_return; 962} 963 964 ret =0; 965goto out; 966 967error_return: 968unlock_ref(lock); 969*lock_p = NULL; 970 971out: 972strbuf_release(&ref_file); 973return ret; 974} 975 976static intfiles_peel_ref(struct ref_store *ref_store, 977const char*refname,unsigned char*sha1) 978{ 979struct files_ref_store *refs = 980files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 981"peel_ref"); 982int flag; 983unsigned char base[20]; 984 985if(current_ref_iter && current_ref_iter->refname == refname) { 986struct object_id peeled; 987 988if(ref_iterator_peel(current_ref_iter, &peeled)) 989return-1; 990hashcpy(sha1, peeled.hash); 991return0; 992} 993 994if(refs_read_ref_full(ref_store, refname, 995 RESOLVE_REF_READING, base, &flag)) 996return-1; 997 998/* 999 * If the reference is packed, read its ref_entry from the1000 * cache in the hope that we already know its peeled value.1001 * We only try this optimization on packed references because1002 * (a) forcing the filling of the loose reference cache could1003 * be expensive and (b) loose references anyway usually do not1004 * have REF_KNOWS_PEELED.1005 */1006if(flag & REF_ISPACKED) {1007struct ref_entry *r =get_packed_ref(refs, refname);1008if(r) {1009if(peel_entry(r,0))1010return-1;1011hashcpy(sha1, r->u.value.peeled.hash);1012return0;1013}1014}10151016returnpeel_object(base, sha1);1017}10181019struct files_ref_iterator {1020struct ref_iterator base;10211022struct packed_ref_cache *packed_ref_cache;1023struct ref_iterator *iter0;1024unsigned int flags;1025};10261027static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1028{1029struct files_ref_iterator *iter =1030(struct files_ref_iterator *)ref_iterator;1031int ok;10321033while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1034if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1035ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1036continue;10371038if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1039!ref_resolves_to_object(iter->iter0->refname,1040 iter->iter0->oid,1041 iter->iter0->flags))1042continue;10431044 iter->base.refname = iter->iter0->refname;1045 iter->base.oid = iter->iter0->oid;1046 iter->base.flags = iter->iter0->flags;1047return ITER_OK;1048}10491050 iter->iter0 = NULL;1051if(ref_iterator_abort(ref_iterator) != ITER_DONE)1052 ok = ITER_ERROR;10531054return ok;1055}10561057static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1058struct object_id *peeled)1059{1060struct files_ref_iterator *iter =1061(struct files_ref_iterator *)ref_iterator;10621063returnref_iterator_peel(iter->iter0, peeled);1064}10651066static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1067{1068struct files_ref_iterator *iter =1069(struct files_ref_iterator *)ref_iterator;1070int ok = ITER_DONE;10711072if(iter->iter0)1073 ok =ref_iterator_abort(iter->iter0);10741075release_packed_ref_cache(iter->packed_ref_cache);1076base_ref_iterator_free(ref_iterator);1077return ok;1078}10791080static struct ref_iterator_vtable files_ref_iterator_vtable = {1081 files_ref_iterator_advance,1082 files_ref_iterator_peel,1083 files_ref_iterator_abort1084};10851086static struct ref_iterator *files_ref_iterator_begin(1087struct ref_store *ref_store,1088const char*prefix,unsigned int flags)1089{1090struct files_ref_store *refs;1091struct ref_iterator *loose_iter, *packed_iter;1092struct files_ref_iterator *iter;1093struct ref_iterator *ref_iterator;1094unsigned int required_flags = REF_STORE_READ;10951096if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1097 required_flags |= REF_STORE_ODB;10981099 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11001101 iter =xcalloc(1,sizeof(*iter));1102 ref_iterator = &iter->base;1103base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11041105/*1106 * We must make sure that all loose refs are read before1107 * accessing the packed-refs file; this avoids a race1108 * condition if loose refs are migrated to the packed-refs1109 * file by a simultaneous process, but our in-memory view is1110 * from before the migration. We ensure this as follows:1111 * First, we call start the loose refs iteration with its1112 * `prime_ref` argument set to true. This causes the loose1113 * references in the subtree to be pre-read into the cache.1114 * (If they've already been read, that's OK; we only need to1115 * guarantee that they're read before the packed refs, not1116 * *how much* before.) After that, we call1117 * get_packed_ref_cache(), which internally checks whether the1118 * packed-ref cache is up to date with what is on disk, and1119 * re-reads it if not.1120 */11211122 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1123 prefix,1);11241125 iter->packed_ref_cache =get_packed_ref_cache(refs);1126acquire_packed_ref_cache(iter->packed_ref_cache);1127 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1128 prefix,0);11291130 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1131 iter->flags = flags;11321133return ref_iterator;1134}11351136/*1137 * Verify that the reference locked by lock has the value old_sha1.1138 * Fail if the reference doesn't exist and mustexist is set. Return 01139 * on success. On error, write an error message to err, set errno, and1140 * return a negative value.1141 */1142static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1143const unsigned char*old_sha1,int mustexist,1144struct strbuf *err)1145{1146assert(err);11471148if(refs_read_ref_full(ref_store, lock->ref_name,1149 mustexist ? RESOLVE_REF_READING :0,1150 lock->old_oid.hash, NULL)) {1151if(old_sha1) {1152int save_errno = errno;1153strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1154 errno = save_errno;1155return-1;1156}else{1157oidclr(&lock->old_oid);1158return0;1159}1160}1161if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1162strbuf_addf(err,"ref '%s' is at%sbut expected%s",1163 lock->ref_name,1164oid_to_hex(&lock->old_oid),1165sha1_to_hex(old_sha1));1166 errno = EBUSY;1167return-1;1168}1169return0;1170}11711172static intremove_empty_directories(struct strbuf *path)1173{1174/*1175 * we want to create a file but there is a directory there;1176 * if that is an empty directory (or a directory that contains1177 * only empty directories), remove them.1178 */1179returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1180}11811182static intcreate_reflock(const char*path,void*cb)1183{1184struct lock_file *lk = cb;11851186returnhold_lock_file_for_update_timeout(1187 lk, path, LOCK_NO_DEREF,1188get_files_ref_lock_timeout_ms()) <0? -1:0;1189}11901191/*1192 * Locks a ref returning the lock on success and NULL on failure.1193 * On failure errno is set to something meaningful.1194 */1195static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1196const char*refname,1197const unsigned char*old_sha1,1198const struct string_list *extras,1199const struct string_list *skip,1200unsigned int flags,int*type,1201struct strbuf *err)1202{1203struct strbuf ref_file = STRBUF_INIT;1204struct ref_lock *lock;1205int last_errno =0;1206int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1207int resolve_flags = RESOLVE_REF_NO_RECURSE;1208int resolved;12091210files_assert_main_repository(refs,"lock_ref_sha1_basic");1211assert(err);12121213 lock =xcalloc(1,sizeof(struct ref_lock));12141215if(mustexist)1216 resolve_flags |= RESOLVE_REF_READING;1217if(flags & REF_DELETING)1218 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12191220files_ref_path(refs, &ref_file, refname);1221 resolved = !!refs_resolve_ref_unsafe(&refs->base,1222 refname, resolve_flags,1223 lock->old_oid.hash, type);1224if(!resolved && errno == EISDIR) {1225/*1226 * we are trying to lock foo but we used to1227 * have foo/bar which now does not exist;1228 * it is normal for the empty directory 'foo'1229 * to remain.1230 */1231if(remove_empty_directories(&ref_file)) {1232 last_errno = errno;1233if(!refs_verify_refname_available(1234&refs->base,1235 refname, extras, skip, err))1236strbuf_addf(err,"there are still refs under '%s'",1237 refname);1238goto error_return;1239}1240 resolved = !!refs_resolve_ref_unsafe(&refs->base,1241 refname, resolve_flags,1242 lock->old_oid.hash, type);1243}1244if(!resolved) {1245 last_errno = errno;1246if(last_errno != ENOTDIR ||1247!refs_verify_refname_available(&refs->base, refname,1248 extras, skip, err))1249strbuf_addf(err,"unable to resolve reference '%s':%s",1250 refname,strerror(last_errno));12511252goto error_return;1253}12541255/*1256 * If the ref did not exist and we are creating it, make sure1257 * there is no existing packed ref whose name begins with our1258 * refname, nor a packed ref whose name is a proper prefix of1259 * our refname.1260 */1261if(is_null_oid(&lock->old_oid) &&1262refs_verify_refname_available(&refs->base, refname,1263 extras, skip, err)) {1264 last_errno = ENOTDIR;1265goto error_return;1266}12671268 lock->lk =xcalloc(1,sizeof(struct lock_file));12691270 lock->ref_name =xstrdup(refname);12711272if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1273 last_errno = errno;1274unable_to_lock_message(ref_file.buf, errno, err);1275goto error_return;1276}12771278if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1279 last_errno = errno;1280goto error_return;1281}1282goto out;12831284 error_return:1285unlock_ref(lock);1286 lock = NULL;12871288 out:1289strbuf_release(&ref_file);1290 errno = last_errno;1291return lock;1292}12931294/*1295 * Write an entry to the packed-refs file for the specified refname.1296 * If peeled is non-NULL, write it as the entry's peeled value.1297 */1298static voidwrite_packed_entry(FILE*fh,const char*refname,1299const unsigned char*sha1,1300const unsigned char*peeled)1301{1302fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1303if(peeled)1304fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1305}13061307/*1308 * Lock the packed-refs file for writing. Flags is passed to1309 * hold_lock_file_for_update(). Return 0 on success. On errors, set1310 * errno appropriately and return a nonzero value.1311 */1312static intlock_packed_refs(struct files_ref_store *refs,int flags)1313{1314static int timeout_configured =0;1315static int timeout_value =1000;1316struct packed_ref_cache *packed_ref_cache;13171318files_assert_main_repository(refs,"lock_packed_refs");13191320if(!timeout_configured) {1321git_config_get_int("core.packedrefstimeout", &timeout_value);1322 timeout_configured =1;1323}13241325if(hold_lock_file_for_update_timeout(1326&refs->packed_refs_lock,files_packed_refs_path(refs),1327 flags, timeout_value) <0)1328return-1;13291330/*1331 * Now that we hold the `packed-refs` lock, make sure that our1332 * cache matches the current version of the file. Normally1333 * `get_packed_ref_cache()` does that for us, but that1334 * function assumes that when the file is locked, any existing1335 * cache is still valid. We've just locked the file, but it1336 * might have changed the moment *before* we locked it.1337 */1338validate_packed_ref_cache(refs);13391340 packed_ref_cache =get_packed_ref_cache(refs);1341/* Increment the reference count to prevent it from being freed: */1342acquire_packed_ref_cache(packed_ref_cache);1343return0;1344}13451346/*1347 * Write the current version of the packed refs cache from memory to1348 * disk. The packed-refs file must already be locked for writing (see1349 * lock_packed_refs()). Return zero on success. On errors, set errno1350 * and return a nonzero value1351 */1352static intcommit_packed_refs(struct files_ref_store *refs)1353{1354struct packed_ref_cache *packed_ref_cache =1355get_packed_ref_cache(refs);1356int ok, error =0;1357int save_errno =0;1358FILE*out;1359struct ref_iterator *iter;13601361files_assert_main_repository(refs,"commit_packed_refs");13621363if(!is_lock_file_locked(&refs->packed_refs_lock))1364die("BUG: packed-refs not locked");13651366 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1367if(!out)1368die_errno("unable to fdopen packed-refs descriptor");13691370fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13711372 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1373while((ok =ref_iterator_advance(iter)) == ITER_OK) {1374struct object_id peeled;1375int peel_error =ref_iterator_peel(iter, &peeled);13761377write_packed_entry(out, iter->refname, iter->oid->hash,1378 peel_error ? NULL : peeled.hash);1379}13801381if(ok != ITER_DONE)1382die("error while iterating over references");13831384if(commit_lock_file(&refs->packed_refs_lock)) {1385 save_errno = errno;1386 error = -1;1387}1388release_packed_ref_cache(packed_ref_cache);1389 errno = save_errno;1390return error;1391}13921393/*1394 * Rollback the lockfile for the packed-refs file, and discard the1395 * in-memory packed reference cache. (The packed-refs file will be1396 * read anew if it is needed again after this function is called.)1397 */1398static voidrollback_packed_refs(struct files_ref_store *refs)1399{1400struct packed_ref_cache *packed_ref_cache =1401get_packed_ref_cache(refs);14021403files_assert_main_repository(refs,"rollback_packed_refs");14041405if(!is_lock_file_locked(&refs->packed_refs_lock))1406die("BUG: packed-refs not locked");1407rollback_lock_file(&refs->packed_refs_lock);1408release_packed_ref_cache(packed_ref_cache);1409clear_packed_ref_cache(refs);1410}14111412struct ref_to_prune {1413struct ref_to_prune *next;1414unsigned char sha1[20];1415char name[FLEX_ARRAY];1416};14171418enum{1419 REMOVE_EMPTY_PARENTS_REF =0x01,1420 REMOVE_EMPTY_PARENTS_REFLOG =0x021421};14221423/*1424 * Remove empty parent directories associated with the specified1425 * reference and/or its reflog, but spare [logs/]refs/ and immediate1426 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1427 * REMOVE_EMPTY_PARENTS_REFLOG.1428 */1429static voidtry_remove_empty_parents(struct files_ref_store *refs,1430const char*refname,1431unsigned int flags)1432{1433struct strbuf buf = STRBUF_INIT;1434struct strbuf sb = STRBUF_INIT;1435char*p, *q;1436int i;14371438strbuf_addstr(&buf, refname);1439 p = buf.buf;1440for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1441while(*p && *p !='/')1442 p++;1443/* tolerate duplicate slashes; see check_refname_format() */1444while(*p =='/')1445 p++;1446}1447 q = buf.buf + buf.len;1448while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1449while(q > p && *q !='/')1450 q--;1451while(q > p && *(q-1) =='/')1452 q--;1453if(q == p)1454break;1455strbuf_setlen(&buf, q - buf.buf);14561457strbuf_reset(&sb);1458files_ref_path(refs, &sb, buf.buf);1459if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1460 flags &= ~REMOVE_EMPTY_PARENTS_REF;14611462strbuf_reset(&sb);1463files_reflog_path(refs, &sb, buf.buf);1464if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1465 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1466}1467strbuf_release(&buf);1468strbuf_release(&sb);1469}14701471/* make sure nobody touched the ref, and unlink */1472static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1473{1474struct ref_transaction *transaction;1475struct strbuf err = STRBUF_INIT;14761477if(check_refname_format(r->name,0))1478return;14791480 transaction =ref_store_transaction_begin(&refs->base, &err);1481if(!transaction ||1482ref_transaction_delete(transaction, r->name, r->sha1,1483 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1484ref_transaction_commit(transaction, &err)) {1485ref_transaction_free(transaction);1486error("%s", err.buf);1487strbuf_release(&err);1488return;1489}1490ref_transaction_free(transaction);1491strbuf_release(&err);1492}14931494static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1495{1496while(r) {1497prune_ref(refs, r);1498 r = r->next;1499}1500}15011502/*1503 * Return true if the specified reference should be packed.1504 */1505static intshould_pack_ref(const char*refname,1506const struct object_id *oid,unsigned int ref_flags,1507unsigned int pack_flags)1508{1509/* Do not pack per-worktree refs: */1510if(ref_type(refname) != REF_TYPE_NORMAL)1511return0;15121513/* Do not pack non-tags unless PACK_REFS_ALL is set: */1514if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1515return0;15161517/* Do not pack symbolic refs: */1518if(ref_flags & REF_ISSYMREF)1519return0;15201521/* Do not pack broken refs: */1522if(!ref_resolves_to_object(refname, oid, ref_flags))1523return0;15241525return1;1526}15271528static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1529{1530struct files_ref_store *refs =1531files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1532"pack_refs");1533struct ref_iterator *iter;1534struct ref_dir *packed_refs;1535int ok;1536struct ref_to_prune *refs_to_prune = NULL;15371538lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1539 packed_refs =get_packed_refs(refs);15401541 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1542while((ok =ref_iterator_advance(iter)) == ITER_OK) {1543/*1544 * If the loose reference can be packed, add an entry1545 * in the packed ref cache. If the reference should be1546 * pruned, also add it to refs_to_prune.1547 */1548struct ref_entry *packed_entry;15491550if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1551 flags))1552continue;15531554/*1555 * Create an entry in the packed-refs cache equivalent1556 * to the one from the loose ref cache, except that1557 * we don't copy the peeled status, because we want it1558 * to be re-peeled.1559 */1560 packed_entry =find_ref_entry(packed_refs, iter->refname);1561if(packed_entry) {1562/* Overwrite existing packed entry with info from loose entry */1563 packed_entry->flag = REF_ISPACKED;1564oidcpy(&packed_entry->u.value.oid, iter->oid);1565}else{1566 packed_entry =create_ref_entry(iter->refname, iter->oid,1567 REF_ISPACKED);1568add_ref_entry(packed_refs, packed_entry);1569}1570oidclr(&packed_entry->u.value.peeled);15711572/* Schedule the loose reference for pruning if requested. */1573if((flags & PACK_REFS_PRUNE)) {1574struct ref_to_prune *n;1575FLEX_ALLOC_STR(n, name, iter->refname);1576hashcpy(n->sha1, iter->oid->hash);1577 n->next = refs_to_prune;1578 refs_to_prune = n;1579}1580}1581if(ok != ITER_DONE)1582die("error while iterating over references");15831584if(commit_packed_refs(refs))1585die_errno("unable to overwrite old ref-pack file");15861587prune_refs(refs, refs_to_prune);1588return0;1589}15901591/*1592 * Rewrite the packed-refs file, omitting any refs listed in1593 * 'refnames'. On error, leave packed-refs unchanged, write an error1594 * message to 'err', and return a nonzero value.1595 *1596 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1597 */1598static intrepack_without_refs(struct files_ref_store *refs,1599struct string_list *refnames,struct strbuf *err)1600{1601struct ref_dir *packed;1602struct string_list_item *refname;1603int ret, needs_repacking =0, removed =0;16041605files_assert_main_repository(refs,"repack_without_refs");1606assert(err);16071608/* Look for a packed ref */1609for_each_string_list_item(refname, refnames) {1610if(get_packed_ref(refs, refname->string)) {1611 needs_repacking =1;1612break;1613}1614}16151616/* Avoid locking if we have nothing to do */1617if(!needs_repacking)1618return0;/* no refname exists in packed refs */16191620if(lock_packed_refs(refs,0)) {1621unable_to_lock_message(files_packed_refs_path(refs), errno, err);1622return-1;1623}1624 packed =get_packed_refs(refs);16251626/* Remove refnames from the cache */1627for_each_string_list_item(refname, refnames)1628if(remove_entry_from_dir(packed, refname->string) != -1)1629 removed =1;1630if(!removed) {1631/*1632 * All packed entries disappeared while we were1633 * acquiring the lock.1634 */1635rollback_packed_refs(refs);1636return0;1637}16381639/* Write what remains */1640 ret =commit_packed_refs(refs);1641if(ret)1642strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1643strerror(errno));1644return ret;1645}16461647static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1648struct string_list *refnames,unsigned int flags)1649{1650struct files_ref_store *refs =1651files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1652struct strbuf err = STRBUF_INIT;1653int i, result =0;16541655if(!refnames->nr)1656return0;16571658 result =repack_without_refs(refs, refnames, &err);1659if(result) {1660/*1661 * If we failed to rewrite the packed-refs file, then1662 * it is unsafe to try to remove loose refs, because1663 * doing so might expose an obsolete packed value for1664 * a reference that might even point at an object that1665 * has been garbage collected.1666 */1667if(refnames->nr ==1)1668error(_("could not delete reference%s:%s"),1669 refnames->items[0].string, err.buf);1670else1671error(_("could not delete references:%s"), err.buf);16721673goto out;1674}16751676for(i =0; i < refnames->nr; i++) {1677const char*refname = refnames->items[i].string;16781679if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1680 result |=error(_("could not remove reference%s"), refname);1681}16821683out:1684strbuf_release(&err);1685return result;1686}16871688/*1689 * People using contrib's git-new-workdir have .git/logs/refs ->1690 * /some/other/path/.git/logs/refs, and that may live on another device.1691 *1692 * IOW, to avoid cross device rename errors, the temporary renamed log must1693 * live into logs/refs.1694 */1695#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16961697struct rename_cb {1698const char*tmp_renamed_log;1699int true_errno;1700};17011702static intrename_tmp_log_callback(const char*path,void*cb_data)1703{1704struct rename_cb *cb = cb_data;17051706if(rename(cb->tmp_renamed_log, path)) {1707/*1708 * rename(a, b) when b is an existing directory ought1709 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1710 * Sheesh. Record the true errno for error reporting,1711 * but report EISDIR to raceproof_create_file() so1712 * that it knows to retry.1713 */1714 cb->true_errno = errno;1715if(errno == ENOTDIR)1716 errno = EISDIR;1717return-1;1718}else{1719return0;1720}1721}17221723static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1724{1725struct strbuf path = STRBUF_INIT;1726struct strbuf tmp = STRBUF_INIT;1727struct rename_cb cb;1728int ret;17291730files_reflog_path(refs, &path, newrefname);1731files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1732 cb.tmp_renamed_log = tmp.buf;1733 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1734if(ret) {1735if(errno == EISDIR)1736error("directory not empty:%s", path.buf);1737else1738error("unable to move logfile%sto%s:%s",1739 tmp.buf, path.buf,1740strerror(cb.true_errno));1741}17421743strbuf_release(&path);1744strbuf_release(&tmp);1745return ret;1746}17471748static intwrite_ref_to_lockfile(struct ref_lock *lock,1749const struct object_id *oid,struct strbuf *err);1750static intcommit_ref_update(struct files_ref_store *refs,1751struct ref_lock *lock,1752const struct object_id *oid,const char*logmsg,1753struct strbuf *err);17541755static intfiles_rename_ref(struct ref_store *ref_store,1756const char*oldrefname,const char*newrefname,1757const char*logmsg)1758{1759struct files_ref_store *refs =1760files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1761struct object_id oid, orig_oid;1762int flag =0, logmoved =0;1763struct ref_lock *lock;1764struct stat loginfo;1765struct strbuf sb_oldref = STRBUF_INIT;1766struct strbuf sb_newref = STRBUF_INIT;1767struct strbuf tmp_renamed_log = STRBUF_INIT;1768int log, ret;1769struct strbuf err = STRBUF_INIT;17701771files_reflog_path(refs, &sb_oldref, oldrefname);1772files_reflog_path(refs, &sb_newref, newrefname);1773files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17741775 log = !lstat(sb_oldref.buf, &loginfo);1776if(log &&S_ISLNK(loginfo.st_mode)) {1777 ret =error("reflog for%sis a symlink", oldrefname);1778goto out;1779}17801781if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1782 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1783 orig_oid.hash, &flag)) {1784 ret =error("refname%snot found", oldrefname);1785goto out;1786}17871788if(flag & REF_ISSYMREF) {1789 ret =error("refname%sis a symbolic ref, renaming it is not supported",1790 oldrefname);1791goto out;1792}1793if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1794 ret =1;1795goto out;1796}17971798if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1799 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1800 oldrefname,strerror(errno));1801goto out;1802}18031804if(refs_delete_ref(&refs->base, logmsg, oldrefname,1805 orig_oid.hash, REF_NODEREF)) {1806error("unable to delete old%s", oldrefname);1807goto rollback;1808}18091810/*1811 * Since we are doing a shallow lookup, oid is not the1812 * correct value to pass to delete_ref as old_oid. But that1813 * doesn't matter, because an old_oid check wouldn't add to1814 * the safety anyway; we want to delete the reference whatever1815 * its current value.1816 */1817if(!refs_read_ref_full(&refs->base, newrefname,1818 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1819 oid.hash, NULL) &&1820refs_delete_ref(&refs->base, NULL, newrefname,1821 NULL, REF_NODEREF)) {1822if(errno == EISDIR) {1823struct strbuf path = STRBUF_INIT;1824int result;18251826files_ref_path(refs, &path, newrefname);1827 result =remove_empty_directories(&path);1828strbuf_release(&path);18291830if(result) {1831error("Directory not empty:%s", newrefname);1832goto rollback;1833}1834}else{1835error("unable to delete existing%s", newrefname);1836goto rollback;1837}1838}18391840if(log &&rename_tmp_log(refs, newrefname))1841goto rollback;18421843 logmoved = log;18441845 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1846 REF_NODEREF, NULL, &err);1847if(!lock) {1848error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1849strbuf_release(&err);1850goto rollback;1851}1852oidcpy(&lock->old_oid, &orig_oid);18531854if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1855commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1856error("unable to write current sha1 into%s:%s", newrefname, err.buf);1857strbuf_release(&err);1858goto rollback;1859}18601861 ret =0;1862goto out;18631864 rollback:1865 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1866 REF_NODEREF, NULL, &err);1867if(!lock) {1868error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1869strbuf_release(&err);1870goto rollbacklog;1871}18721873 flag = log_all_ref_updates;1874 log_all_ref_updates = LOG_REFS_NONE;1875if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1876commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1877error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1878strbuf_release(&err);1879}1880 log_all_ref_updates = flag;18811882 rollbacklog:1883if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1884error("unable to restore logfile%sfrom%s:%s",1885 oldrefname, newrefname,strerror(errno));1886if(!logmoved && log &&1887rename(tmp_renamed_log.buf, sb_oldref.buf))1888error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1889 oldrefname,strerror(errno));1890 ret =1;1891 out:1892strbuf_release(&sb_newref);1893strbuf_release(&sb_oldref);1894strbuf_release(&tmp_renamed_log);18951896return ret;1897}18981899static intclose_ref(struct ref_lock *lock)1900{1901if(close_lock_file(lock->lk))1902return-1;1903return0;1904}19051906static intcommit_ref(struct ref_lock *lock)1907{1908char*path =get_locked_file_path(lock->lk);1909struct stat st;19101911if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1912/*1913 * There is a directory at the path we want to rename1914 * the lockfile to. Hopefully it is empty; try to1915 * delete it.1916 */1917size_t len =strlen(path);1918struct strbuf sb_path = STRBUF_INIT;19191920strbuf_attach(&sb_path, path, len, len);19211922/*1923 * If this fails, commit_lock_file() will also fail1924 * and will report the problem.1925 */1926remove_empty_directories(&sb_path);1927strbuf_release(&sb_path);1928}else{1929free(path);1930}19311932if(commit_lock_file(lock->lk))1933return-1;1934return0;1935}19361937static intopen_or_create_logfile(const char*path,void*cb)1938{1939int*fd = cb;19401941*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1942return(*fd <0) ? -1:0;1943}19441945/*1946 * Create a reflog for a ref. If force_create = 0, only create the1947 * reflog for certain refs (those for which should_autocreate_reflog1948 * returns non-zero). Otherwise, create it regardless of the reference1949 * name. If the logfile already existed or was created, return 0 and1950 * set *logfd to the file descriptor opened for appending to the file.1951 * If no logfile exists and we decided not to create one, return 0 and1952 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1953 * return -1.1954 */1955static intlog_ref_setup(struct files_ref_store *refs,1956const char*refname,int force_create,1957int*logfd,struct strbuf *err)1958{1959struct strbuf logfile_sb = STRBUF_INIT;1960char*logfile;19611962files_reflog_path(refs, &logfile_sb, refname);1963 logfile =strbuf_detach(&logfile_sb, NULL);19641965if(force_create ||should_autocreate_reflog(refname)) {1966if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1967if(errno == ENOENT)1968strbuf_addf(err,"unable to create directory for '%s': "1969"%s", logfile,strerror(errno));1970else if(errno == EISDIR)1971strbuf_addf(err,"there are still logs under '%s'",1972 logfile);1973else1974strbuf_addf(err,"unable to append to '%s':%s",1975 logfile,strerror(errno));19761977goto error;1978}1979}else{1980*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1981if(*logfd <0) {1982if(errno == ENOENT || errno == EISDIR) {1983/*1984 * The logfile doesn't already exist,1985 * but that is not an error; it only1986 * means that we won't write log1987 * entries to it.1988 */1989;1990}else{1991strbuf_addf(err,"unable to append to '%s':%s",1992 logfile,strerror(errno));1993goto error;1994}1995}1996}19971998if(*logfd >=0)1999adjust_shared_perm(logfile);20002001free(logfile);2002return0;20032004error:2005free(logfile);2006return-1;2007}20082009static intfiles_create_reflog(struct ref_store *ref_store,2010const char*refname,int force_create,2011struct strbuf *err)2012{2013struct files_ref_store *refs =2014files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2015int fd;20162017if(log_ref_setup(refs, refname, force_create, &fd, err))2018return-1;20192020if(fd >=0)2021close(fd);20222023return0;2024}20252026static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2027const struct object_id *new_oid,2028const char*committer,const char*msg)2029{2030int msglen, written;2031unsigned maxlen, len;2032char*logrec;20332034 msglen = msg ?strlen(msg) :0;2035 maxlen =strlen(committer) + msglen +100;2036 logrec =xmalloc(maxlen);2037 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2038oid_to_hex(old_oid),2039oid_to_hex(new_oid),2040 committer);2041if(msglen)2042 len +=copy_reflog_msg(logrec + len -1, msg) -1;20432044 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2045free(logrec);2046if(written != len)2047return-1;20482049return0;2050}20512052static intfiles_log_ref_write(struct files_ref_store *refs,2053const char*refname,const struct object_id *old_oid,2054const struct object_id *new_oid,const char*msg,2055int flags,struct strbuf *err)2056{2057int logfd, result;20582059if(log_all_ref_updates == LOG_REFS_UNSET)2060 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20612062 result =log_ref_setup(refs, refname,2063 flags & REF_FORCE_CREATE_REFLOG,2064&logfd, err);20652066if(result)2067return result;20682069if(logfd <0)2070return0;2071 result =log_ref_write_fd(logfd, old_oid, new_oid,2072git_committer_info(0), msg);2073if(result) {2074struct strbuf sb = STRBUF_INIT;2075int save_errno = errno;20762077files_reflog_path(refs, &sb, refname);2078strbuf_addf(err,"unable to append to '%s':%s",2079 sb.buf,strerror(save_errno));2080strbuf_release(&sb);2081close(logfd);2082return-1;2083}2084if(close(logfd)) {2085struct strbuf sb = STRBUF_INIT;2086int save_errno = errno;20872088files_reflog_path(refs, &sb, refname);2089strbuf_addf(err,"unable to append to '%s':%s",2090 sb.buf,strerror(save_errno));2091strbuf_release(&sb);2092return-1;2093}2094return0;2095}20962097/*2098 * Write sha1 into the open lockfile, then close the lockfile. On2099 * errors, rollback the lockfile, fill in *err and2100 * return -1.2101 */2102static intwrite_ref_to_lockfile(struct ref_lock *lock,2103const struct object_id *oid,struct strbuf *err)2104{2105static char term ='\n';2106struct object *o;2107int fd;21082109 o =parse_object(oid);2110if(!o) {2111strbuf_addf(err,2112"trying to write ref '%s' with nonexistent object%s",2113 lock->ref_name,oid_to_hex(oid));2114unlock_ref(lock);2115return-1;2116}2117if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2118strbuf_addf(err,2119"trying to write non-commit object%sto branch '%s'",2120oid_to_hex(oid), lock->ref_name);2121unlock_ref(lock);2122return-1;2123}2124 fd =get_lock_file_fd(lock->lk);2125if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2126write_in_full(fd, &term,1) !=1||2127close_ref(lock) <0) {2128strbuf_addf(err,2129"couldn't write '%s'",get_lock_file_path(lock->lk));2130unlock_ref(lock);2131return-1;2132}2133return0;2134}21352136/*2137 * Commit a change to a loose reference that has already been written2138 * to the loose reference lockfile. Also update the reflogs if2139 * necessary, using the specified lockmsg (which can be NULL).2140 */2141static intcommit_ref_update(struct files_ref_store *refs,2142struct ref_lock *lock,2143const struct object_id *oid,const char*logmsg,2144struct strbuf *err)2145{2146files_assert_main_repository(refs,"commit_ref_update");21472148clear_loose_ref_cache(refs);2149if(files_log_ref_write(refs, lock->ref_name,2150&lock->old_oid, oid,2151 logmsg,0, err)) {2152char*old_msg =strbuf_detach(err, NULL);2153strbuf_addf(err,"cannot update the ref '%s':%s",2154 lock->ref_name, old_msg);2155free(old_msg);2156unlock_ref(lock);2157return-1;2158}21592160if(strcmp(lock->ref_name,"HEAD") !=0) {2161/*2162 * Special hack: If a branch is updated directly and HEAD2163 * points to it (may happen on the remote side of a push2164 * for example) then logically the HEAD reflog should be2165 * updated too.2166 * A generic solution implies reverse symref information,2167 * but finding all symrefs pointing to the given branch2168 * would be rather costly for this rare event (the direct2169 * update of a branch) to be worth it. So let's cheat and2170 * check with HEAD only which should cover 99% of all usage2171 * scenarios (even 100% of the default ones).2172 */2173struct object_id head_oid;2174int head_flag;2175const char*head_ref;21762177 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2178 RESOLVE_REF_READING,2179 head_oid.hash, &head_flag);2180if(head_ref && (head_flag & REF_ISSYMREF) &&2181!strcmp(head_ref, lock->ref_name)) {2182struct strbuf log_err = STRBUF_INIT;2183if(files_log_ref_write(refs,"HEAD",2184&lock->old_oid, oid,2185 logmsg,0, &log_err)) {2186error("%s", log_err.buf);2187strbuf_release(&log_err);2188}2189}2190}21912192if(commit_ref(lock)) {2193strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2194unlock_ref(lock);2195return-1;2196}21972198unlock_ref(lock);2199return0;2200}22012202static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2203{2204int ret = -1;2205#ifndef NO_SYMLINK_HEAD2206char*ref_path =get_locked_file_path(lock->lk);2207unlink(ref_path);2208 ret =symlink(target, ref_path);2209free(ref_path);22102211if(ret)2212fprintf(stderr,"no symlink - falling back to symbolic ref\n");2213#endif2214return ret;2215}22162217static voidupdate_symref_reflog(struct files_ref_store *refs,2218struct ref_lock *lock,const char*refname,2219const char*target,const char*logmsg)2220{2221struct strbuf err = STRBUF_INIT;2222struct object_id new_oid;2223if(logmsg &&2224!refs_read_ref_full(&refs->base, target,2225 RESOLVE_REF_READING, new_oid.hash, NULL) &&2226files_log_ref_write(refs, refname, &lock->old_oid,2227&new_oid, logmsg,0, &err)) {2228error("%s", err.buf);2229strbuf_release(&err);2230}2231}22322233static intcreate_symref_locked(struct files_ref_store *refs,2234struct ref_lock *lock,const char*refname,2235const char*target,const char*logmsg)2236{2237if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2238update_symref_reflog(refs, lock, refname, target, logmsg);2239return0;2240}22412242if(!fdopen_lock_file(lock->lk,"w"))2243returnerror("unable to fdopen%s:%s",2244 lock->lk->tempfile.filename.buf,strerror(errno));22452246update_symref_reflog(refs, lock, refname, target, logmsg);22472248/* no error check; commit_ref will check ferror */2249fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2250if(commit_ref(lock) <0)2251returnerror("unable to write symref for%s:%s", refname,2252strerror(errno));2253return0;2254}22552256static intfiles_create_symref(struct ref_store *ref_store,2257const char*refname,const char*target,2258const char*logmsg)2259{2260struct files_ref_store *refs =2261files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2262struct strbuf err = STRBUF_INIT;2263struct ref_lock *lock;2264int ret;22652266 lock =lock_ref_sha1_basic(refs, refname, NULL,2267 NULL, NULL, REF_NODEREF, NULL,2268&err);2269if(!lock) {2270error("%s", err.buf);2271strbuf_release(&err);2272return-1;2273}22742275 ret =create_symref_locked(refs, lock, refname, target, logmsg);2276unlock_ref(lock);2277return ret;2278}22792280static intfiles_reflog_exists(struct ref_store *ref_store,2281const char*refname)2282{2283struct files_ref_store *refs =2284files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2285struct strbuf sb = STRBUF_INIT;2286struct stat st;2287int ret;22882289files_reflog_path(refs, &sb, refname);2290 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2291strbuf_release(&sb);2292return ret;2293}22942295static intfiles_delete_reflog(struct ref_store *ref_store,2296const char*refname)2297{2298struct files_ref_store *refs =2299files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2300struct strbuf sb = STRBUF_INIT;2301int ret;23022303files_reflog_path(refs, &sb, refname);2304 ret =remove_path(sb.buf);2305strbuf_release(&sb);2306return ret;2307}23082309static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2310{2311struct object_id ooid, noid;2312char*email_end, *message;2313 timestamp_t timestamp;2314int tz;2315const char*p = sb->buf;23162317/* old SP new SP name <email> SP time TAB msg LF */2318if(!sb->len || sb->buf[sb->len -1] !='\n'||2319parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2320parse_oid_hex(p, &noid, &p) || *p++ !=' '||2321!(email_end =strchr(p,'>')) ||2322 email_end[1] !=' '||2323!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2324!message || message[0] !=' '||2325(message[1] !='+'&& message[1] !='-') ||2326!isdigit(message[2]) || !isdigit(message[3]) ||2327!isdigit(message[4]) || !isdigit(message[5]))2328return0;/* corrupt? */2329 email_end[1] ='\0';2330 tz =strtol(message +1, NULL,10);2331if(message[6] !='\t')2332 message +=6;2333else2334 message +=7;2335returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2336}23372338static char*find_beginning_of_line(char*bob,char*scan)2339{2340while(bob < scan && *(--scan) !='\n')2341;/* keep scanning backwards */2342/*2343 * Return either beginning of the buffer, or LF at the end of2344 * the previous line.2345 */2346return scan;2347}23482349static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2350const char*refname,2351 each_reflog_ent_fn fn,2352void*cb_data)2353{2354struct files_ref_store *refs =2355files_downcast(ref_store, REF_STORE_READ,2356"for_each_reflog_ent_reverse");2357struct strbuf sb = STRBUF_INIT;2358FILE*logfp;2359long pos;2360int ret =0, at_tail =1;23612362files_reflog_path(refs, &sb, refname);2363 logfp =fopen(sb.buf,"r");2364strbuf_release(&sb);2365if(!logfp)2366return-1;23672368/* Jump to the end */2369if(fseek(logfp,0, SEEK_END) <0)2370 ret =error("cannot seek back reflog for%s:%s",2371 refname,strerror(errno));2372 pos =ftell(logfp);2373while(!ret &&0< pos) {2374int cnt;2375size_t nread;2376char buf[BUFSIZ];2377char*endp, *scanp;23782379/* Fill next block from the end */2380 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2381if(fseek(logfp, pos - cnt, SEEK_SET)) {2382 ret =error("cannot seek back reflog for%s:%s",2383 refname,strerror(errno));2384break;2385}2386 nread =fread(buf, cnt,1, logfp);2387if(nread !=1) {2388 ret =error("cannot read%dbytes from reflog for%s:%s",2389 cnt, refname,strerror(errno));2390break;2391}2392 pos -= cnt;23932394 scanp = endp = buf + cnt;2395if(at_tail && scanp[-1] =='\n')2396/* Looking at the final LF at the end of the file */2397 scanp--;2398 at_tail =0;23992400while(buf < scanp) {2401/*2402 * terminating LF of the previous line, or the beginning2403 * of the buffer.2404 */2405char*bp;24062407 bp =find_beginning_of_line(buf, scanp);24082409if(*bp =='\n') {2410/*2411 * The newline is the end of the previous line,2412 * so we know we have complete line starting2413 * at (bp + 1). Prefix it onto any prior data2414 * we collected for the line and process it.2415 */2416strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2417 scanp = bp;2418 endp = bp +1;2419 ret =show_one_reflog_ent(&sb, fn, cb_data);2420strbuf_reset(&sb);2421if(ret)2422break;2423}else if(!pos) {2424/*2425 * We are at the start of the buffer, and the2426 * start of the file; there is no previous2427 * line, and we have everything for this one.2428 * Process it, and we can end the loop.2429 */2430strbuf_splice(&sb,0,0, buf, endp - buf);2431 ret =show_one_reflog_ent(&sb, fn, cb_data);2432strbuf_reset(&sb);2433break;2434}24352436if(bp == buf) {2437/*2438 * We are at the start of the buffer, and there2439 * is more file to read backwards. Which means2440 * we are in the middle of a line. Note that we2441 * may get here even if *bp was a newline; that2442 * just means we are at the exact end of the2443 * previous line, rather than some spot in the2444 * middle.2445 *2446 * Save away what we have to be combined with2447 * the data from the next read.2448 */2449strbuf_splice(&sb,0,0, buf, endp - buf);2450break;2451}2452}24532454}2455if(!ret && sb.len)2456die("BUG: reverse reflog parser had leftover data");24572458fclose(logfp);2459strbuf_release(&sb);2460return ret;2461}24622463static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2464const char*refname,2465 each_reflog_ent_fn fn,void*cb_data)2466{2467struct files_ref_store *refs =2468files_downcast(ref_store, REF_STORE_READ,2469"for_each_reflog_ent");2470FILE*logfp;2471struct strbuf sb = STRBUF_INIT;2472int ret =0;24732474files_reflog_path(refs, &sb, refname);2475 logfp =fopen(sb.buf,"r");2476strbuf_release(&sb);2477if(!logfp)2478return-1;24792480while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2481 ret =show_one_reflog_ent(&sb, fn, cb_data);2482fclose(logfp);2483strbuf_release(&sb);2484return ret;2485}24862487struct files_reflog_iterator {2488struct ref_iterator base;24892490struct ref_store *ref_store;2491struct dir_iterator *dir_iterator;2492struct object_id oid;2493};24942495static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2496{2497struct files_reflog_iterator *iter =2498(struct files_reflog_iterator *)ref_iterator;2499struct dir_iterator *diter = iter->dir_iterator;2500int ok;25012502while((ok =dir_iterator_advance(diter)) == ITER_OK) {2503int flags;25042505if(!S_ISREG(diter->st.st_mode))2506continue;2507if(diter->basename[0] =='.')2508continue;2509if(ends_with(diter->basename,".lock"))2510continue;25112512if(refs_read_ref_full(iter->ref_store,2513 diter->relative_path,0,2514 iter->oid.hash, &flags)) {2515error("bad ref for%s", diter->path.buf);2516continue;2517}25182519 iter->base.refname = diter->relative_path;2520 iter->base.oid = &iter->oid;2521 iter->base.flags = flags;2522return ITER_OK;2523}25242525 iter->dir_iterator = NULL;2526if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2527 ok = ITER_ERROR;2528return ok;2529}25302531static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2532struct object_id *peeled)2533{2534die("BUG: ref_iterator_peel() called for reflog_iterator");2535}25362537static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2538{2539struct files_reflog_iterator *iter =2540(struct files_reflog_iterator *)ref_iterator;2541int ok = ITER_DONE;25422543if(iter->dir_iterator)2544 ok =dir_iterator_abort(iter->dir_iterator);25452546base_ref_iterator_free(ref_iterator);2547return ok;2548}25492550static struct ref_iterator_vtable files_reflog_iterator_vtable = {2551 files_reflog_iterator_advance,2552 files_reflog_iterator_peel,2553 files_reflog_iterator_abort2554};25552556static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2557{2558struct files_ref_store *refs =2559files_downcast(ref_store, REF_STORE_READ,2560"reflog_iterator_begin");2561struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2562struct ref_iterator *ref_iterator = &iter->base;2563struct strbuf sb = STRBUF_INIT;25642565base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2566files_reflog_path(refs, &sb, NULL);2567 iter->dir_iterator =dir_iterator_begin(sb.buf);2568 iter->ref_store = ref_store;2569strbuf_release(&sb);2570return ref_iterator;2571}25722573/*2574 * If update is a direct update of head_ref (the reference pointed to2575 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2576 */2577static intsplit_head_update(struct ref_update *update,2578struct ref_transaction *transaction,2579const char*head_ref,2580struct string_list *affected_refnames,2581struct strbuf *err)2582{2583struct string_list_item *item;2584struct ref_update *new_update;25852586if((update->flags & REF_LOG_ONLY) ||2587(update->flags & REF_ISPRUNING) ||2588(update->flags & REF_UPDATE_VIA_HEAD))2589return0;25902591if(strcmp(update->refname, head_ref))2592return0;25932594/*2595 * First make sure that HEAD is not already in the2596 * transaction. This insertion is O(N) in the transaction2597 * size, but it happens at most once per transaction.2598 */2599 item =string_list_insert(affected_refnames,"HEAD");2600if(item->util) {2601/* An entry already existed */2602strbuf_addf(err,2603"multiple updates for 'HEAD' (including one "2604"via its referent '%s') are not allowed",2605 update->refname);2606return TRANSACTION_NAME_CONFLICT;2607}26082609 new_update =ref_transaction_add_update(2610 transaction,"HEAD",2611 update->flags | REF_LOG_ONLY | REF_NODEREF,2612 update->new_oid.hash, update->old_oid.hash,2613 update->msg);26142615 item->util = new_update;26162617return0;2618}26192620/*2621 * update is for a symref that points at referent and doesn't have2622 * REF_NODEREF set. Split it into two updates:2623 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2624 * - A new, separate update for the referent reference2625 * Note that the new update will itself be subject to splitting when2626 * the iteration gets to it.2627 */2628static intsplit_symref_update(struct files_ref_store *refs,2629struct ref_update *update,2630const char*referent,2631struct ref_transaction *transaction,2632struct string_list *affected_refnames,2633struct strbuf *err)2634{2635struct string_list_item *item;2636struct ref_update *new_update;2637unsigned int new_flags;26382639/*2640 * First make sure that referent is not already in the2641 * transaction. This insertion is O(N) in the transaction2642 * size, but it happens at most once per symref in a2643 * transaction.2644 */2645 item =string_list_insert(affected_refnames, referent);2646if(item->util) {2647/* An entry already existed */2648strbuf_addf(err,2649"multiple updates for '%s' (including one "2650"via symref '%s') are not allowed",2651 referent, update->refname);2652return TRANSACTION_NAME_CONFLICT;2653}26542655 new_flags = update->flags;2656if(!strcmp(update->refname,"HEAD")) {2657/*2658 * Record that the new update came via HEAD, so that2659 * when we process it, split_head_update() doesn't try2660 * to add another reflog update for HEAD. Note that2661 * this bit will be propagated if the new_update2662 * itself needs to be split.2663 */2664 new_flags |= REF_UPDATE_VIA_HEAD;2665}26662667 new_update =ref_transaction_add_update(2668 transaction, referent, new_flags,2669 update->new_oid.hash, update->old_oid.hash,2670 update->msg);26712672 new_update->parent_update = update;26732674/*2675 * Change the symbolic ref update to log only. Also, it2676 * doesn't need to check its old SHA-1 value, as that will be2677 * done when new_update is processed.2678 */2679 update->flags |= REF_LOG_ONLY | REF_NODEREF;2680 update->flags &= ~REF_HAVE_OLD;26812682 item->util = new_update;26832684return0;2685}26862687/*2688 * Return the refname under which update was originally requested.2689 */2690static const char*original_update_refname(struct ref_update *update)2691{2692while(update->parent_update)2693 update = update->parent_update;26942695return update->refname;2696}26972698/*2699 * Check whether the REF_HAVE_OLD and old_oid values stored in update2700 * are consistent with oid, which is the reference's current value. If2701 * everything is OK, return 0; otherwise, write an error message to2702 * err and return -1.2703 */2704static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2705struct strbuf *err)2706{2707if(!(update->flags & REF_HAVE_OLD) ||2708!oidcmp(oid, &update->old_oid))2709return0;27102711if(is_null_oid(&update->old_oid))2712strbuf_addf(err,"cannot lock ref '%s': "2713"reference already exists",2714original_update_refname(update));2715else if(is_null_oid(oid))2716strbuf_addf(err,"cannot lock ref '%s': "2717"reference is missing but expected%s",2718original_update_refname(update),2719oid_to_hex(&update->old_oid));2720else2721strbuf_addf(err,"cannot lock ref '%s': "2722"is at%sbut expected%s",2723original_update_refname(update),2724oid_to_hex(oid),2725oid_to_hex(&update->old_oid));27262727return-1;2728}27292730/*2731 * Prepare for carrying out update:2732 * - Lock the reference referred to by update.2733 * - Read the reference under lock.2734 * - Check that its old SHA-1 value (if specified) is correct, and in2735 * any case record it in update->lock->old_oid for later use when2736 * writing the reflog.2737 * - If it is a symref update without REF_NODEREF, split it up into a2738 * REF_LOG_ONLY update of the symref and add a separate update for2739 * the referent to transaction.2740 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2741 * update of HEAD.2742 */2743static intlock_ref_for_update(struct files_ref_store *refs,2744struct ref_update *update,2745struct ref_transaction *transaction,2746const char*head_ref,2747struct string_list *affected_refnames,2748struct strbuf *err)2749{2750struct strbuf referent = STRBUF_INIT;2751int mustexist = (update->flags & REF_HAVE_OLD) &&2752!is_null_oid(&update->old_oid);2753int ret;2754struct ref_lock *lock;27552756files_assert_main_repository(refs,"lock_ref_for_update");27572758if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2759 update->flags |= REF_DELETING;27602761if(head_ref) {2762 ret =split_head_update(update, transaction, head_ref,2763 affected_refnames, err);2764if(ret)2765return ret;2766}27672768 ret =lock_raw_ref(refs, update->refname, mustexist,2769 affected_refnames, NULL,2770&lock, &referent,2771&update->type, err);2772if(ret) {2773char*reason;27742775 reason =strbuf_detach(err, NULL);2776strbuf_addf(err,"cannot lock ref '%s':%s",2777original_update_refname(update), reason);2778free(reason);2779return ret;2780}27812782 update->backend_data = lock;27832784if(update->type & REF_ISSYMREF) {2785if(update->flags & REF_NODEREF) {2786/*2787 * We won't be reading the referent as part of2788 * the transaction, so we have to read it here2789 * to record and possibly check old_sha1:2790 */2791if(refs_read_ref_full(&refs->base,2792 referent.buf,0,2793 lock->old_oid.hash, NULL)) {2794if(update->flags & REF_HAVE_OLD) {2795strbuf_addf(err,"cannot lock ref '%s': "2796"error reading reference",2797original_update_refname(update));2798return-1;2799}2800}else if(check_old_oid(update, &lock->old_oid, err)) {2801return TRANSACTION_GENERIC_ERROR;2802}2803}else{2804/*2805 * Create a new update for the reference this2806 * symref is pointing at. Also, we will record2807 * and verify old_sha1 for this update as part2808 * of processing the split-off update, so we2809 * don't have to do it here.2810 */2811 ret =split_symref_update(refs, update,2812 referent.buf, transaction,2813 affected_refnames, err);2814if(ret)2815return ret;2816}2817}else{2818struct ref_update *parent_update;28192820if(check_old_oid(update, &lock->old_oid, err))2821return TRANSACTION_GENERIC_ERROR;28222823/*2824 * If this update is happening indirectly because of a2825 * symref update, record the old SHA-1 in the parent2826 * update:2827 */2828for(parent_update = update->parent_update;2829 parent_update;2830 parent_update = parent_update->parent_update) {2831struct ref_lock *parent_lock = parent_update->backend_data;2832oidcpy(&parent_lock->old_oid, &lock->old_oid);2833}2834}28352836if((update->flags & REF_HAVE_NEW) &&2837!(update->flags & REF_DELETING) &&2838!(update->flags & REF_LOG_ONLY)) {2839if(!(update->type & REF_ISSYMREF) &&2840!oidcmp(&lock->old_oid, &update->new_oid)) {2841/*2842 * The reference already has the desired2843 * value, so we don't need to write it.2844 */2845}else if(write_ref_to_lockfile(lock, &update->new_oid,2846 err)) {2847char*write_err =strbuf_detach(err, NULL);28482849/*2850 * The lock was freed upon failure of2851 * write_ref_to_lockfile():2852 */2853 update->backend_data = NULL;2854strbuf_addf(err,2855"cannot update ref '%s':%s",2856 update->refname, write_err);2857free(write_err);2858return TRANSACTION_GENERIC_ERROR;2859}else{2860 update->flags |= REF_NEEDS_COMMIT;2861}2862}2863if(!(update->flags & REF_NEEDS_COMMIT)) {2864/*2865 * We didn't call write_ref_to_lockfile(), so2866 * the lockfile is still open. Close it to2867 * free up the file descriptor:2868 */2869if(close_ref(lock)) {2870strbuf_addf(err,"couldn't close '%s.lock'",2871 update->refname);2872return TRANSACTION_GENERIC_ERROR;2873}2874}2875return0;2876}28772878/*2879 * Unlock any references in `transaction` that are still locked, and2880 * mark the transaction closed.2881 */2882static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2883{2884size_t i;28852886for(i =0; i < transaction->nr; i++) {2887struct ref_update *update = transaction->updates[i];2888struct ref_lock *lock = update->backend_data;28892890if(lock) {2891unlock_ref(lock);2892 update->backend_data = NULL;2893}2894}28952896 transaction->state = REF_TRANSACTION_CLOSED;2897}28982899static intfiles_transaction_prepare(struct ref_store *ref_store,2900struct ref_transaction *transaction,2901struct strbuf *err)2902{2903struct files_ref_store *refs =2904files_downcast(ref_store, REF_STORE_WRITE,2905"ref_transaction_prepare");2906size_t i;2907int ret =0;2908struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2909char*head_ref = NULL;2910int head_type;2911struct object_id head_oid;29122913assert(err);29142915if(!transaction->nr)2916goto cleanup;29172918/*2919 * Fail if a refname appears more than once in the2920 * transaction. (If we end up splitting up any updates using2921 * split_symref_update() or split_head_update(), those2922 * functions will check that the new updates don't have the2923 * same refname as any existing ones.)2924 */2925for(i =0; i < transaction->nr; i++) {2926struct ref_update *update = transaction->updates[i];2927struct string_list_item *item =2928string_list_append(&affected_refnames, update->refname);29292930/*2931 * We store a pointer to update in item->util, but at2932 * the moment we never use the value of this field2933 * except to check whether it is non-NULL.2934 */2935 item->util = update;2936}2937string_list_sort(&affected_refnames);2938if(ref_update_reject_duplicates(&affected_refnames, err)) {2939 ret = TRANSACTION_GENERIC_ERROR;2940goto cleanup;2941}29422943/*2944 * Special hack: If a branch is updated directly and HEAD2945 * points to it (may happen on the remote side of a push2946 * for example) then logically the HEAD reflog should be2947 * updated too.2948 *2949 * A generic solution would require reverse symref lookups,2950 * but finding all symrefs pointing to a given branch would be2951 * rather costly for this rare event (the direct update of a2952 * branch) to be worth it. So let's cheat and check with HEAD2953 * only, which should cover 99% of all usage scenarios (even2954 * 100% of the default ones).2955 *2956 * So if HEAD is a symbolic reference, then record the name of2957 * the reference that it points to. If we see an update of2958 * head_ref within the transaction, then split_head_update()2959 * arranges for the reflog of HEAD to be updated, too.2960 */2961 head_ref =refs_resolve_refdup(ref_store,"HEAD",2962 RESOLVE_REF_NO_RECURSE,2963 head_oid.hash, &head_type);29642965if(head_ref && !(head_type & REF_ISSYMREF)) {2966FREE_AND_NULL(head_ref);2967}29682969/*2970 * Acquire all locks, verify old values if provided, check2971 * that new values are valid, and write new values to the2972 * lockfiles, ready to be activated. Only keep one lockfile2973 * open at a time to avoid running out of file descriptors.2974 * Note that lock_ref_for_update() might append more updates2975 * to the transaction.2976 */2977for(i =0; i < transaction->nr; i++) {2978struct ref_update *update = transaction->updates[i];29792980 ret =lock_ref_for_update(refs, update, transaction,2981 head_ref, &affected_refnames, err);2982if(ret)2983break;2984}29852986cleanup:2987free(head_ref);2988string_list_clear(&affected_refnames,0);29892990if(ret)2991files_transaction_cleanup(transaction);2992else2993 transaction->state = REF_TRANSACTION_PREPARED;29942995return ret;2996}29972998static intfiles_transaction_finish(struct ref_store *ref_store,2999struct ref_transaction *transaction,3000struct strbuf *err)3001{3002struct files_ref_store *refs =3003files_downcast(ref_store,0,"ref_transaction_finish");3004size_t i;3005int ret =0;3006struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3007struct string_list_item *ref_to_delete;3008struct strbuf sb = STRBUF_INIT;30093010assert(err);30113012if(!transaction->nr) {3013 transaction->state = REF_TRANSACTION_CLOSED;3014return0;3015}30163017/* Perform updates first so live commits remain referenced */3018for(i =0; i < transaction->nr; i++) {3019struct ref_update *update = transaction->updates[i];3020struct ref_lock *lock = update->backend_data;30213022if(update->flags & REF_NEEDS_COMMIT ||3023 update->flags & REF_LOG_ONLY) {3024if(files_log_ref_write(refs,3025 lock->ref_name,3026&lock->old_oid,3027&update->new_oid,3028 update->msg, update->flags,3029 err)) {3030char*old_msg =strbuf_detach(err, NULL);30313032strbuf_addf(err,"cannot update the ref '%s':%s",3033 lock->ref_name, old_msg);3034free(old_msg);3035unlock_ref(lock);3036 update->backend_data = NULL;3037 ret = TRANSACTION_GENERIC_ERROR;3038goto cleanup;3039}3040}3041if(update->flags & REF_NEEDS_COMMIT) {3042clear_loose_ref_cache(refs);3043if(commit_ref(lock)) {3044strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3045unlock_ref(lock);3046 update->backend_data = NULL;3047 ret = TRANSACTION_GENERIC_ERROR;3048goto cleanup;3049}3050}3051}3052/* Perform deletes now that updates are safely completed */3053for(i =0; i < transaction->nr; i++) {3054struct ref_update *update = transaction->updates[i];3055struct ref_lock *lock = update->backend_data;30563057if(update->flags & REF_DELETING &&3058!(update->flags & REF_LOG_ONLY)) {3059if(!(update->type & REF_ISPACKED) ||3060 update->type & REF_ISSYMREF) {3061/* It is a loose reference. */3062strbuf_reset(&sb);3063files_ref_path(refs, &sb, lock->ref_name);3064if(unlink_or_msg(sb.buf, err)) {3065 ret = TRANSACTION_GENERIC_ERROR;3066goto cleanup;3067}3068 update->flags |= REF_DELETED_LOOSE;3069}30703071if(!(update->flags & REF_ISPRUNING))3072string_list_append(&refs_to_delete,3073 lock->ref_name);3074}3075}30763077if(repack_without_refs(refs, &refs_to_delete, err)) {3078 ret = TRANSACTION_GENERIC_ERROR;3079goto cleanup;3080}30813082/* Delete the reflogs of any references that were deleted: */3083for_each_string_list_item(ref_to_delete, &refs_to_delete) {3084strbuf_reset(&sb);3085files_reflog_path(refs, &sb, ref_to_delete->string);3086if(!unlink_or_warn(sb.buf))3087try_remove_empty_parents(refs, ref_to_delete->string,3088 REMOVE_EMPTY_PARENTS_REFLOG);3089}30903091clear_loose_ref_cache(refs);30923093cleanup:3094files_transaction_cleanup(transaction);30953096for(i =0; i < transaction->nr; i++) {3097struct ref_update *update = transaction->updates[i];30983099if(update->flags & REF_DELETED_LOOSE) {3100/*3101 * The loose reference was deleted. Delete any3102 * empty parent directories. (Note that this3103 * can only work because we have already3104 * removed the lockfile.)3105 */3106try_remove_empty_parents(refs, update->refname,3107 REMOVE_EMPTY_PARENTS_REF);3108}3109}31103111strbuf_release(&sb);3112string_list_clear(&refs_to_delete,0);3113return ret;3114}31153116static intfiles_transaction_abort(struct ref_store *ref_store,3117struct ref_transaction *transaction,3118struct strbuf *err)3119{3120files_transaction_cleanup(transaction);3121return0;3122}31233124static intref_present(const char*refname,3125const struct object_id *oid,int flags,void*cb_data)3126{3127struct string_list *affected_refnames = cb_data;31283129returnstring_list_has_string(affected_refnames, refname);3130}31313132static intfiles_initial_transaction_commit(struct ref_store *ref_store,3133struct ref_transaction *transaction,3134struct strbuf *err)3135{3136struct files_ref_store *refs =3137files_downcast(ref_store, REF_STORE_WRITE,3138"initial_ref_transaction_commit");3139size_t i;3140int ret =0;3141struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31423143assert(err);31443145if(transaction->state != REF_TRANSACTION_OPEN)3146die("BUG: commit called for transaction that is not open");31473148/* Fail if a refname appears more than once in the transaction: */3149for(i =0; i < transaction->nr; i++)3150string_list_append(&affected_refnames,3151 transaction->updates[i]->refname);3152string_list_sort(&affected_refnames);3153if(ref_update_reject_duplicates(&affected_refnames, err)) {3154 ret = TRANSACTION_GENERIC_ERROR;3155goto cleanup;3156}31573158/*3159 * It's really undefined to call this function in an active3160 * repository or when there are existing references: we are3161 * only locking and changing packed-refs, so (1) any3162 * simultaneous processes might try to change a reference at3163 * the same time we do, and (2) any existing loose versions of3164 * the references that we are setting would have precedence3165 * over our values. But some remote helpers create the remote3166 * "HEAD" and "master" branches before calling this function,3167 * so here we really only check that none of the references3168 * that we are creating already exists.3169 */3170if(refs_for_each_rawref(&refs->base, ref_present,3171&affected_refnames))3172die("BUG: initial ref transaction called with existing refs");31733174for(i =0; i < transaction->nr; i++) {3175struct ref_update *update = transaction->updates[i];31763177if((update->flags & REF_HAVE_OLD) &&3178!is_null_oid(&update->old_oid))3179die("BUG: initial ref transaction with old_sha1 set");3180if(refs_verify_refname_available(&refs->base, update->refname,3181&affected_refnames, NULL,3182 err)) {3183 ret = TRANSACTION_NAME_CONFLICT;3184goto cleanup;3185}3186}31873188if(lock_packed_refs(refs,0)) {3189strbuf_addf(err,"unable to lock packed-refs file:%s",3190strerror(errno));3191 ret = TRANSACTION_GENERIC_ERROR;3192goto cleanup;3193}31943195for(i =0; i < transaction->nr; i++) {3196struct ref_update *update = transaction->updates[i];31973198if((update->flags & REF_HAVE_NEW) &&3199!is_null_oid(&update->new_oid))3200add_packed_ref(refs, update->refname,3201&update->new_oid);3202}32033204if(commit_packed_refs(refs)) {3205strbuf_addf(err,"unable to commit packed-refs file:%s",3206strerror(errno));3207 ret = TRANSACTION_GENERIC_ERROR;3208goto cleanup;3209}32103211cleanup:3212 transaction->state = REF_TRANSACTION_CLOSED;3213string_list_clear(&affected_refnames,0);3214return ret;3215}32163217struct expire_reflog_cb {3218unsigned int flags;3219 reflog_expiry_should_prune_fn *should_prune_fn;3220void*policy_cb;3221FILE*newlog;3222struct object_id last_kept_oid;3223};32243225static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3226const char*email, timestamp_t timestamp,int tz,3227const char*message,void*cb_data)3228{3229struct expire_reflog_cb *cb = cb_data;3230struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32313232if(cb->flags & EXPIRE_REFLOGS_REWRITE)3233 ooid = &cb->last_kept_oid;32343235if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3236 message, policy_cb)) {3237if(!cb->newlog)3238printf("would prune%s", message);3239else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3240printf("prune%s", message);3241}else{3242if(cb->newlog) {3243fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3244oid_to_hex(ooid),oid_to_hex(noid),3245 email, timestamp, tz, message);3246oidcpy(&cb->last_kept_oid, noid);3247}3248if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3249printf("keep%s", message);3250}3251return0;3252}32533254static intfiles_reflog_expire(struct ref_store *ref_store,3255const char*refname,const unsigned char*sha1,3256unsigned int flags,3257 reflog_expiry_prepare_fn prepare_fn,3258 reflog_expiry_should_prune_fn should_prune_fn,3259 reflog_expiry_cleanup_fn cleanup_fn,3260void*policy_cb_data)3261{3262struct files_ref_store *refs =3263files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3264static struct lock_file reflog_lock;3265struct expire_reflog_cb cb;3266struct ref_lock *lock;3267struct strbuf log_file_sb = STRBUF_INIT;3268char*log_file;3269int status =0;3270int type;3271struct strbuf err = STRBUF_INIT;3272struct object_id oid;32733274memset(&cb,0,sizeof(cb));3275 cb.flags = flags;3276 cb.policy_cb = policy_cb_data;3277 cb.should_prune_fn = should_prune_fn;32783279/*3280 * The reflog file is locked by holding the lock on the3281 * reference itself, plus we might need to update the3282 * reference if --updateref was specified:3283 */3284 lock =lock_ref_sha1_basic(refs, refname, sha1,3285 NULL, NULL, REF_NODEREF,3286&type, &err);3287if(!lock) {3288error("cannot lock ref '%s':%s", refname, err.buf);3289strbuf_release(&err);3290return-1;3291}3292if(!refs_reflog_exists(ref_store, refname)) {3293unlock_ref(lock);3294return0;3295}32963297files_reflog_path(refs, &log_file_sb, refname);3298 log_file =strbuf_detach(&log_file_sb, NULL);3299if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3300/*3301 * Even though holding $GIT_DIR/logs/$reflog.lock has3302 * no locking implications, we use the lock_file3303 * machinery here anyway because it does a lot of the3304 * work we need, including cleaning up if the program3305 * exits unexpectedly.3306 */3307if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3308struct strbuf err = STRBUF_INIT;3309unable_to_lock_message(log_file, errno, &err);3310error("%s", err.buf);3311strbuf_release(&err);3312goto failure;3313}3314 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3315if(!cb.newlog) {3316error("cannot fdopen%s(%s)",3317get_lock_file_path(&reflog_lock),strerror(errno));3318goto failure;3319}3320}33213322hashcpy(oid.hash, sha1);33233324(*prepare_fn)(refname, &oid, cb.policy_cb);3325refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3326(*cleanup_fn)(cb.policy_cb);33273328if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3329/*3330 * It doesn't make sense to adjust a reference pointed3331 * to by a symbolic ref based on expiring entries in3332 * the symbolic reference's reflog. Nor can we update3333 * a reference if there are no remaining reflog3334 * entries.3335 */3336int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3337!(type & REF_ISSYMREF) &&3338!is_null_oid(&cb.last_kept_oid);33393340if(close_lock_file(&reflog_lock)) {3341 status |=error("couldn't write%s:%s", log_file,3342strerror(errno));3343}else if(update &&3344(write_in_full(get_lock_file_fd(lock->lk),3345oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3346write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3347close_ref(lock) <0)) {3348 status |=error("couldn't write%s",3349get_lock_file_path(lock->lk));3350rollback_lock_file(&reflog_lock);3351}else if(commit_lock_file(&reflog_lock)) {3352 status |=error("unable to write reflog '%s' (%s)",3353 log_file,strerror(errno));3354}else if(update &&commit_ref(lock)) {3355 status |=error("couldn't set%s", lock->ref_name);3356}3357}3358free(log_file);3359unlock_ref(lock);3360return status;33613362 failure:3363rollback_lock_file(&reflog_lock);3364free(log_file);3365unlock_ref(lock);3366return-1;3367}33683369static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3370{3371struct files_ref_store *refs =3372files_downcast(ref_store, REF_STORE_WRITE,"init_db");3373struct strbuf sb = STRBUF_INIT;33743375/*3376 * Create .git/refs/{heads,tags}3377 */3378files_ref_path(refs, &sb,"refs/heads");3379safe_create_dir(sb.buf,1);33803381strbuf_reset(&sb);3382files_ref_path(refs, &sb,"refs/tags");3383safe_create_dir(sb.buf,1);33843385strbuf_release(&sb);3386return0;3387}33883389struct ref_storage_be refs_be_files = {3390 NULL,3391"files",3392 files_ref_store_create,3393 files_init_db,3394 files_transaction_prepare,3395 files_transaction_finish,3396 files_transaction_abort,3397 files_initial_transaction_commit,33983399 files_pack_refs,3400 files_peel_ref,3401 files_create_symref,3402 files_delete_refs,3403 files_rename_ref,34043405 files_ref_iterator_begin,3406 files_read_raw_ref,34073408 files_reflog_iterator_begin,3409 files_for_each_reflog_ent,3410 files_for_each_reflog_ent_reverse,3411 files_reflog_exists,3412 files_create_reflog,3413 files_delete_reflog,3414 files_reflog_expire3415};