1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * Future: need to be in "struct repository" 52 * when doing a full libification. 53 */ 54struct files_ref_store { 55struct ref_store base; 56unsigned int store_flags; 57 58char*gitdir; 59char*gitcommondir; 60char*packed_refs_path; 61 62struct ref_cache *loose; 63struct packed_ref_cache *packed; 64 65/* 66 * Lock used for the "packed-refs" file. Note that this (and 67 * thus the enclosing `files_ref_store`) must not be freed. 68 */ 69struct lock_file packed_refs_lock; 70}; 71 72/* 73 * Increment the reference count of *packed_refs. 74 */ 75static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 76{ 77 packed_refs->referrers++; 78} 79 80/* 81 * Decrease the reference count of *packed_refs. If it goes to zero, 82 * free *packed_refs and return true; otherwise return false. 83 */ 84static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 85{ 86if(!--packed_refs->referrers) { 87free_ref_cache(packed_refs->cache); 88stat_validity_clear(&packed_refs->validity); 89free(packed_refs); 90return1; 91}else{ 92return0; 93} 94} 95 96static voidclear_packed_ref_cache(struct files_ref_store *refs) 97{ 98if(refs->packed) { 99struct packed_ref_cache *packed_refs = refs->packed; 100 101if(is_lock_file_locked(&refs->packed_refs_lock)) 102die("BUG: packed-ref cache cleared while locked"); 103 refs->packed = NULL; 104release_packed_ref_cache(packed_refs); 105} 106} 107 108static voidclear_loose_ref_cache(struct files_ref_store *refs) 109{ 110if(refs->loose) { 111free_ref_cache(refs->loose); 112 refs->loose = NULL; 113} 114} 115 116/* 117 * Create a new submodule ref cache and add it to the internal 118 * set of caches. 119 */ 120static struct ref_store *files_ref_store_create(const char*gitdir, 121unsigned int flags) 122{ 123struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 124struct ref_store *ref_store = (struct ref_store *)refs; 125struct strbuf sb = STRBUF_INIT; 126 127base_ref_store_init(ref_store, &refs_be_files); 128 refs->store_flags = flags; 129 130 refs->gitdir =xstrdup(gitdir); 131get_common_dir_noenv(&sb, gitdir); 132 refs->gitcommondir =strbuf_detach(&sb, NULL); 133strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 134 refs->packed_refs_path =strbuf_detach(&sb, NULL); 135 136return ref_store; 137} 138 139/* 140 * Die if refs is not the main ref store. caller is used in any 141 * necessary error messages. 142 */ 143static voidfiles_assert_main_repository(struct files_ref_store *refs, 144const char*caller) 145{ 146if(refs->store_flags & REF_STORE_MAIN) 147return; 148 149die("BUG: operation%sonly allowed for main ref store", caller); 150} 151 152/* 153 * Downcast ref_store to files_ref_store. Die if ref_store is not a 154 * files_ref_store. required_flags is compared with ref_store's 155 * store_flags to ensure the ref_store has all required capabilities. 156 * "caller" is used in any necessary error messages. 157 */ 158static struct files_ref_store *files_downcast(struct ref_store *ref_store, 159unsigned int required_flags, 160const char*caller) 161{ 162struct files_ref_store *refs; 163 164if(ref_store->be != &refs_be_files) 165die("BUG: ref_store is type\"%s\"not\"files\"in%s", 166 ref_store->be->name, caller); 167 168 refs = (struct files_ref_store *)ref_store; 169 170if((refs->store_flags & required_flags) != required_flags) 171die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 172 caller, required_flags, refs->store_flags); 173 174return refs; 175} 176 177/* The length of a peeled reference line in packed-refs, including EOL: */ 178#define PEELED_LINE_LENGTH 42 179 180/* 181 * The packed-refs header line that we write out. Perhaps other 182 * traits will be added later. The trailing space is required. 183 */ 184static const char PACKED_REFS_HEADER[] = 185"# pack-refs with: peeled fully-peeled\n"; 186 187/* 188 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 189 * Return a pointer to the refname within the line (null-terminated), 190 * or NULL if there was a problem. 191 */ 192static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 193{ 194const char*ref; 195 196if(parse_oid_hex(line->buf, oid, &ref) <0) 197return NULL; 198if(!isspace(*ref++)) 199return NULL; 200 201if(isspace(*ref)) 202return NULL; 203 204if(line->buf[line->len -1] !='\n') 205return NULL; 206 line->buf[--line->len] =0; 207 208return ref; 209} 210 211/* 212 * Read f, which is a packed-refs file, into dir. 213 * 214 * A comment line of the form "# pack-refs with: " may contain zero or 215 * more traits. We interpret the traits as follows: 216 * 217 * No traits: 218 * 219 * Probably no references are peeled. But if the file contains a 220 * peeled value for a reference, we will use it. 221 * 222 * peeled: 223 * 224 * References under "refs/tags/", if they *can* be peeled, *are* 225 * peeled in this file. References outside of "refs/tags/" are 226 * probably not peeled even if they could have been, but if we find 227 * a peeled value for such a reference we will use it. 228 * 229 * fully-peeled: 230 * 231 * All references in the file that can be peeled are peeled. 232 * Inversely (and this is more important), any references in the 233 * file for which no peeled value is recorded is not peelable. This 234 * trait should typically be written alongside "peeled" for 235 * compatibility with older clients, but we do not require it 236 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 237 */ 238static voidread_packed_refs(FILE*f,struct ref_dir *dir) 239{ 240struct ref_entry *last = NULL; 241struct strbuf line = STRBUF_INIT; 242enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 243 244while(strbuf_getwholeline(&line, f,'\n') != EOF) { 245struct object_id oid; 246const char*refname; 247const char*traits; 248 249if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 250if(strstr(traits," fully-peeled ")) 251 peeled = PEELED_FULLY; 252else if(strstr(traits," peeled ")) 253 peeled = PEELED_TAGS; 254/* perhaps other traits later as well */ 255continue; 256} 257 258 refname =parse_ref_line(&line, &oid); 259if(refname) { 260int flag = REF_ISPACKED; 261 262if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 263if(!refname_is_safe(refname)) 264die("packed refname is dangerous:%s", refname); 265oidclr(&oid); 266 flag |= REF_BAD_NAME | REF_ISBROKEN; 267} 268 last =create_ref_entry(refname, &oid, flag,0); 269if(peeled == PEELED_FULLY || 270(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 271 last->flag |= REF_KNOWS_PEELED; 272add_ref_entry(dir, last); 273continue; 274} 275if(last && 276 line.buf[0] =='^'&& 277 line.len == PEELED_LINE_LENGTH && 278 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 279!get_oid_hex(line.buf +1, &oid)) { 280oidcpy(&last->u.value.peeled, &oid); 281/* 282 * Regardless of what the file header said, 283 * we definitely know the value of *this* 284 * reference: 285 */ 286 last->flag |= REF_KNOWS_PEELED; 287} 288} 289 290strbuf_release(&line); 291} 292 293static const char*files_packed_refs_path(struct files_ref_store *refs) 294{ 295return refs->packed_refs_path; 296} 297 298static voidfiles_reflog_path(struct files_ref_store *refs, 299struct strbuf *sb, 300const char*refname) 301{ 302if(!refname) { 303/* 304 * FIXME: of course this is wrong in multi worktree 305 * setting. To be fixed real soon. 306 */ 307strbuf_addf(sb,"%s/logs", refs->gitcommondir); 308return; 309} 310 311switch(ref_type(refname)) { 312case REF_TYPE_PER_WORKTREE: 313case REF_TYPE_PSEUDOREF: 314strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 315break; 316case REF_TYPE_NORMAL: 317strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 318break; 319default: 320die("BUG: unknown ref type%dof ref%s", 321ref_type(refname), refname); 322} 323} 324 325static voidfiles_ref_path(struct files_ref_store *refs, 326struct strbuf *sb, 327const char*refname) 328{ 329switch(ref_type(refname)) { 330case REF_TYPE_PER_WORKTREE: 331case REF_TYPE_PSEUDOREF: 332strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 333break; 334case REF_TYPE_NORMAL: 335strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 336break; 337default: 338die("BUG: unknown ref type%dof ref%s", 339ref_type(refname), refname); 340} 341} 342 343/* 344 * Get the packed_ref_cache for the specified files_ref_store, 345 * creating it if necessary. 346 */ 347static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 348{ 349const char*packed_refs_file =files_packed_refs_path(refs); 350 351if(refs->packed && 352!stat_validity_check(&refs->packed->validity, packed_refs_file)) 353clear_packed_ref_cache(refs); 354 355if(!refs->packed) { 356FILE*f; 357 358 refs->packed =xcalloc(1,sizeof(*refs->packed)); 359acquire_packed_ref_cache(refs->packed); 360 refs->packed->cache =create_ref_cache(&refs->base, NULL); 361 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 362 f =fopen(packed_refs_file,"r"); 363if(f) { 364stat_validity_update(&refs->packed->validity,fileno(f)); 365read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 366fclose(f); 367} 368} 369return refs->packed; 370} 371 372static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 373{ 374returnget_ref_dir(packed_ref_cache->cache->root); 375} 376 377static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 378{ 379returnget_packed_ref_dir(get_packed_ref_cache(refs)); 380} 381 382/* 383 * Add a reference to the in-memory packed reference cache. This may 384 * only be called while the packed-refs file is locked (see 385 * lock_packed_refs()). To actually write the packed-refs file, call 386 * commit_packed_refs(). 387 */ 388static voidadd_packed_ref(struct files_ref_store *refs, 389const char*refname,const struct object_id *oid) 390{ 391struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 392 393if(!is_lock_file_locked(&refs->packed_refs_lock)) 394die("BUG: packed refs not locked"); 395add_ref_entry(get_packed_ref_dir(packed_ref_cache), 396create_ref_entry(refname, oid, REF_ISPACKED,1)); 397} 398 399/* 400 * Read the loose references from the namespace dirname into dir 401 * (without recursing). dirname must end with '/'. dir must be the 402 * directory entry corresponding to dirname. 403 */ 404static voidloose_fill_ref_dir(struct ref_store *ref_store, 405struct ref_dir *dir,const char*dirname) 406{ 407struct files_ref_store *refs = 408files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 409DIR*d; 410struct dirent *de; 411int dirnamelen =strlen(dirname); 412struct strbuf refname; 413struct strbuf path = STRBUF_INIT; 414size_t path_baselen; 415 416files_ref_path(refs, &path, dirname); 417 path_baselen = path.len; 418 419 d =opendir(path.buf); 420if(!d) { 421strbuf_release(&path); 422return; 423} 424 425strbuf_init(&refname, dirnamelen +257); 426strbuf_add(&refname, dirname, dirnamelen); 427 428while((de =readdir(d)) != NULL) { 429struct object_id oid; 430struct stat st; 431int flag; 432 433if(de->d_name[0] =='.') 434continue; 435if(ends_with(de->d_name,".lock")) 436continue; 437strbuf_addstr(&refname, de->d_name); 438strbuf_addstr(&path, de->d_name); 439if(stat(path.buf, &st) <0) { 440;/* silently ignore */ 441}else if(S_ISDIR(st.st_mode)) { 442strbuf_addch(&refname,'/'); 443add_entry_to_dir(dir, 444create_dir_entry(dir->cache, refname.buf, 445 refname.len,1)); 446}else{ 447if(!refs_resolve_ref_unsafe(&refs->base, 448 refname.buf, 449 RESOLVE_REF_READING, 450 oid.hash, &flag)) { 451oidclr(&oid); 452 flag |= REF_ISBROKEN; 453}else if(is_null_oid(&oid)) { 454/* 455 * It is so astronomically unlikely 456 * that NULL_SHA1 is the SHA-1 of an 457 * actual object that we consider its 458 * appearance in a loose reference 459 * file to be repo corruption 460 * (probably due to a software bug). 461 */ 462 flag |= REF_ISBROKEN; 463} 464 465if(check_refname_format(refname.buf, 466 REFNAME_ALLOW_ONELEVEL)) { 467if(!refname_is_safe(refname.buf)) 468die("loose refname is dangerous:%s", refname.buf); 469oidclr(&oid); 470 flag |= REF_BAD_NAME | REF_ISBROKEN; 471} 472add_entry_to_dir(dir, 473create_ref_entry(refname.buf, &oid, flag,0)); 474} 475strbuf_setlen(&refname, dirnamelen); 476strbuf_setlen(&path, path_baselen); 477} 478strbuf_release(&refname); 479strbuf_release(&path); 480closedir(d); 481 482/* 483 * Manually add refs/bisect, which, being per-worktree, might 484 * not appear in the directory listing for refs/ in the main 485 * repo. 486 */ 487if(!strcmp(dirname,"refs/")) { 488int pos =search_ref_dir(dir,"refs/bisect/",12); 489 490if(pos <0) { 491struct ref_entry *child_entry =create_dir_entry( 492 dir->cache,"refs/bisect/",12,1); 493add_entry_to_dir(dir, child_entry); 494} 495} 496} 497 498static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 499{ 500if(!refs->loose) { 501/* 502 * Mark the top-level directory complete because we 503 * are about to read the only subdirectory that can 504 * hold references: 505 */ 506 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 507 508/* We're going to fill the top level ourselves: */ 509 refs->loose->root->flag &= ~REF_INCOMPLETE; 510 511/* 512 * Add an incomplete entry for "refs/" (to be filled 513 * lazily): 514 */ 515add_entry_to_dir(get_ref_dir(refs->loose->root), 516create_dir_entry(refs->loose,"refs/",5,1)); 517} 518return refs->loose; 519} 520 521/* 522 * Return the ref_entry for the given refname from the packed 523 * references. If it does not exist, return NULL. 524 */ 525static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 526const char*refname) 527{ 528returnfind_ref_entry(get_packed_refs(refs), refname); 529} 530 531/* 532 * A loose ref file doesn't exist; check for a packed ref. 533 */ 534static intresolve_packed_ref(struct files_ref_store *refs, 535const char*refname, 536unsigned char*sha1,unsigned int*flags) 537{ 538struct ref_entry *entry; 539 540/* 541 * The loose reference file does not exist; check for a packed 542 * reference. 543 */ 544 entry =get_packed_ref(refs, refname); 545if(entry) { 546hashcpy(sha1, entry->u.value.oid.hash); 547*flags |= REF_ISPACKED; 548return0; 549} 550/* refname is not a packed reference. */ 551return-1; 552} 553 554static intfiles_read_raw_ref(struct ref_store *ref_store, 555const char*refname,unsigned char*sha1, 556struct strbuf *referent,unsigned int*type) 557{ 558struct files_ref_store *refs = 559files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 560struct strbuf sb_contents = STRBUF_INIT; 561struct strbuf sb_path = STRBUF_INIT; 562const char*path; 563const char*buf; 564struct stat st; 565int fd; 566int ret = -1; 567int save_errno; 568int remaining_retries =3; 569 570*type =0; 571strbuf_reset(&sb_path); 572 573files_ref_path(refs, &sb_path, refname); 574 575 path = sb_path.buf; 576 577stat_ref: 578/* 579 * We might have to loop back here to avoid a race 580 * condition: first we lstat() the file, then we try 581 * to read it as a link or as a file. But if somebody 582 * changes the type of the file (file <-> directory 583 * <-> symlink) between the lstat() and reading, then 584 * we don't want to report that as an error but rather 585 * try again starting with the lstat(). 586 * 587 * We'll keep a count of the retries, though, just to avoid 588 * any confusing situation sending us into an infinite loop. 589 */ 590 591if(remaining_retries-- <=0) 592goto out; 593 594if(lstat(path, &st) <0) { 595if(errno != ENOENT) 596goto out; 597if(resolve_packed_ref(refs, refname, sha1, type)) { 598 errno = ENOENT; 599goto out; 600} 601 ret =0; 602goto out; 603} 604 605/* Follow "normalized" - ie "refs/.." symlinks by hand */ 606if(S_ISLNK(st.st_mode)) { 607strbuf_reset(&sb_contents); 608if(strbuf_readlink(&sb_contents, path,0) <0) { 609if(errno == ENOENT || errno == EINVAL) 610/* inconsistent with lstat; retry */ 611goto stat_ref; 612else 613goto out; 614} 615if(starts_with(sb_contents.buf,"refs/") && 616!check_refname_format(sb_contents.buf,0)) { 617strbuf_swap(&sb_contents, referent); 618*type |= REF_ISSYMREF; 619 ret =0; 620goto out; 621} 622/* 623 * It doesn't look like a refname; fall through to just 624 * treating it like a non-symlink, and reading whatever it 625 * points to. 626 */ 627} 628 629/* Is it a directory? */ 630if(S_ISDIR(st.st_mode)) { 631/* 632 * Even though there is a directory where the loose 633 * ref is supposed to be, there could still be a 634 * packed ref: 635 */ 636if(resolve_packed_ref(refs, refname, sha1, type)) { 637 errno = EISDIR; 638goto out; 639} 640 ret =0; 641goto out; 642} 643 644/* 645 * Anything else, just open it and try to use it as 646 * a ref 647 */ 648 fd =open(path, O_RDONLY); 649if(fd <0) { 650if(errno == ENOENT && !S_ISLNK(st.st_mode)) 651/* inconsistent with lstat; retry */ 652goto stat_ref; 653else 654goto out; 655} 656strbuf_reset(&sb_contents); 657if(strbuf_read(&sb_contents, fd,256) <0) { 658int save_errno = errno; 659close(fd); 660 errno = save_errno; 661goto out; 662} 663close(fd); 664strbuf_rtrim(&sb_contents); 665 buf = sb_contents.buf; 666if(starts_with(buf,"ref:")) { 667 buf +=4; 668while(isspace(*buf)) 669 buf++; 670 671strbuf_reset(referent); 672strbuf_addstr(referent, buf); 673*type |= REF_ISSYMREF; 674 ret =0; 675goto out; 676} 677 678/* 679 * Please note that FETCH_HEAD has additional 680 * data after the sha. 681 */ 682if(get_sha1_hex(buf, sha1) || 683(buf[40] !='\0'&& !isspace(buf[40]))) { 684*type |= REF_ISBROKEN; 685 errno = EINVAL; 686goto out; 687} 688 689 ret =0; 690 691out: 692 save_errno = errno; 693strbuf_release(&sb_path); 694strbuf_release(&sb_contents); 695 errno = save_errno; 696return ret; 697} 698 699static voidunlock_ref(struct ref_lock *lock) 700{ 701/* Do not free lock->lk -- atexit() still looks at them */ 702if(lock->lk) 703rollback_lock_file(lock->lk); 704free(lock->ref_name); 705free(lock); 706} 707 708/* 709 * Lock refname, without following symrefs, and set *lock_p to point 710 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 711 * and type similarly to read_raw_ref(). 712 * 713 * The caller must verify that refname is a "safe" reference name (in 714 * the sense of refname_is_safe()) before calling this function. 715 * 716 * If the reference doesn't already exist, verify that refname doesn't 717 * have a D/F conflict with any existing references. extras and skip 718 * are passed to refs_verify_refname_available() for this check. 719 * 720 * If mustexist is not set and the reference is not found or is 721 * broken, lock the reference anyway but clear sha1. 722 * 723 * Return 0 on success. On failure, write an error message to err and 724 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 725 * 726 * Implementation note: This function is basically 727 * 728 * lock reference 729 * read_raw_ref() 730 * 731 * but it includes a lot more code to 732 * - Deal with possible races with other processes 733 * - Avoid calling refs_verify_refname_available() when it can be 734 * avoided, namely if we were successfully able to read the ref 735 * - Generate informative error messages in the case of failure 736 */ 737static intlock_raw_ref(struct files_ref_store *refs, 738const char*refname,int mustexist, 739const struct string_list *extras, 740const struct string_list *skip, 741struct ref_lock **lock_p, 742struct strbuf *referent, 743unsigned int*type, 744struct strbuf *err) 745{ 746struct ref_lock *lock; 747struct strbuf ref_file = STRBUF_INIT; 748int attempts_remaining =3; 749int ret = TRANSACTION_GENERIC_ERROR; 750 751assert(err); 752files_assert_main_repository(refs,"lock_raw_ref"); 753 754*type =0; 755 756/* First lock the file so it can't change out from under us. */ 757 758*lock_p = lock =xcalloc(1,sizeof(*lock)); 759 760 lock->ref_name =xstrdup(refname); 761files_ref_path(refs, &ref_file, refname); 762 763retry: 764switch(safe_create_leading_directories(ref_file.buf)) { 765case SCLD_OK: 766break;/* success */ 767case SCLD_EXISTS: 768/* 769 * Suppose refname is "refs/foo/bar". We just failed 770 * to create the containing directory, "refs/foo", 771 * because there was a non-directory in the way. This 772 * indicates a D/F conflict, probably because of 773 * another reference such as "refs/foo". There is no 774 * reason to expect this error to be transitory. 775 */ 776if(refs_verify_refname_available(&refs->base, refname, 777 extras, skip, err)) { 778if(mustexist) { 779/* 780 * To the user the relevant error is 781 * that the "mustexist" reference is 782 * missing: 783 */ 784strbuf_reset(err); 785strbuf_addf(err,"unable to resolve reference '%s'", 786 refname); 787}else{ 788/* 789 * The error message set by 790 * refs_verify_refname_available() is 791 * OK. 792 */ 793 ret = TRANSACTION_NAME_CONFLICT; 794} 795}else{ 796/* 797 * The file that is in the way isn't a loose 798 * reference. Report it as a low-level 799 * failure. 800 */ 801strbuf_addf(err,"unable to create lock file%s.lock; " 802"non-directory in the way", 803 ref_file.buf); 804} 805goto error_return; 806case SCLD_VANISHED: 807/* Maybe another process was tidying up. Try again. */ 808if(--attempts_remaining >0) 809goto retry; 810/* fall through */ 811default: 812strbuf_addf(err,"unable to create directory for%s", 813 ref_file.buf); 814goto error_return; 815} 816 817if(!lock->lk) 818 lock->lk =xcalloc(1,sizeof(struct lock_file)); 819 820if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 821if(errno == ENOENT && --attempts_remaining >0) { 822/* 823 * Maybe somebody just deleted one of the 824 * directories leading to ref_file. Try 825 * again: 826 */ 827goto retry; 828}else{ 829unable_to_lock_message(ref_file.buf, errno, err); 830goto error_return; 831} 832} 833 834/* 835 * Now we hold the lock and can read the reference without 836 * fear that its value will change. 837 */ 838 839if(files_read_raw_ref(&refs->base, refname, 840 lock->old_oid.hash, referent, type)) { 841if(errno == ENOENT) { 842if(mustexist) { 843/* Garden variety missing reference. */ 844strbuf_addf(err,"unable to resolve reference '%s'", 845 refname); 846goto error_return; 847}else{ 848/* 849 * Reference is missing, but that's OK. We 850 * know that there is not a conflict with 851 * another loose reference because 852 * (supposing that we are trying to lock 853 * reference "refs/foo/bar"): 854 * 855 * - We were successfully able to create 856 * the lockfile refs/foo/bar.lock, so we 857 * know there cannot be a loose reference 858 * named "refs/foo". 859 * 860 * - We got ENOENT and not EISDIR, so we 861 * know that there cannot be a loose 862 * reference named "refs/foo/bar/baz". 863 */ 864} 865}else if(errno == EISDIR) { 866/* 867 * There is a directory in the way. It might have 868 * contained references that have been deleted. If 869 * we don't require that the reference already 870 * exists, try to remove the directory so that it 871 * doesn't cause trouble when we want to rename the 872 * lockfile into place later. 873 */ 874if(mustexist) { 875/* Garden variety missing reference. */ 876strbuf_addf(err,"unable to resolve reference '%s'", 877 refname); 878goto error_return; 879}else if(remove_dir_recursively(&ref_file, 880 REMOVE_DIR_EMPTY_ONLY)) { 881if(refs_verify_refname_available( 882&refs->base, refname, 883 extras, skip, err)) { 884/* 885 * The error message set by 886 * verify_refname_available() is OK. 887 */ 888 ret = TRANSACTION_NAME_CONFLICT; 889goto error_return; 890}else{ 891/* 892 * We can't delete the directory, 893 * but we also don't know of any 894 * references that it should 895 * contain. 896 */ 897strbuf_addf(err,"there is a non-empty directory '%s' " 898"blocking reference '%s'", 899 ref_file.buf, refname); 900goto error_return; 901} 902} 903}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 904strbuf_addf(err,"unable to resolve reference '%s': " 905"reference broken", refname); 906goto error_return; 907}else{ 908strbuf_addf(err,"unable to resolve reference '%s':%s", 909 refname,strerror(errno)); 910goto error_return; 911} 912 913/* 914 * If the ref did not exist and we are creating it, 915 * make sure there is no existing ref that conflicts 916 * with refname: 917 */ 918if(refs_verify_refname_available( 919&refs->base, refname, 920 extras, skip, err)) 921goto error_return; 922} 923 924 ret =0; 925goto out; 926 927error_return: 928unlock_ref(lock); 929*lock_p = NULL; 930 931out: 932strbuf_release(&ref_file); 933return ret; 934} 935 936static intfiles_peel_ref(struct ref_store *ref_store, 937const char*refname,unsigned char*sha1) 938{ 939struct files_ref_store *refs = 940files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 941"peel_ref"); 942int flag; 943unsigned char base[20]; 944 945if(current_ref_iter && current_ref_iter->refname == refname) { 946struct object_id peeled; 947 948if(ref_iterator_peel(current_ref_iter, &peeled)) 949return-1; 950hashcpy(sha1, peeled.hash); 951return0; 952} 953 954if(refs_read_ref_full(ref_store, refname, 955 RESOLVE_REF_READING, base, &flag)) 956return-1; 957 958/* 959 * If the reference is packed, read its ref_entry from the 960 * cache in the hope that we already know its peeled value. 961 * We only try this optimization on packed references because 962 * (a) forcing the filling of the loose reference cache could 963 * be expensive and (b) loose references anyway usually do not 964 * have REF_KNOWS_PEELED. 965 */ 966if(flag & REF_ISPACKED) { 967struct ref_entry *r =get_packed_ref(refs, refname); 968if(r) { 969if(peel_entry(r,0)) 970return-1; 971hashcpy(sha1, r->u.value.peeled.hash); 972return0; 973} 974} 975 976returnpeel_object(base, sha1); 977} 978 979struct files_ref_iterator { 980struct ref_iterator base; 981 982struct packed_ref_cache *packed_ref_cache; 983struct ref_iterator *iter0; 984unsigned int flags; 985}; 986 987static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 988{ 989struct files_ref_iterator *iter = 990(struct files_ref_iterator *)ref_iterator; 991int ok; 992 993while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 994if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 995ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 996continue; 997 998if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 999!ref_resolves_to_object(iter->iter0->refname,1000 iter->iter0->oid,1001 iter->iter0->flags))1002continue;10031004 iter->base.refname = iter->iter0->refname;1005 iter->base.oid = iter->iter0->oid;1006 iter->base.flags = iter->iter0->flags;1007return ITER_OK;1008}10091010 iter->iter0 = NULL;1011if(ref_iterator_abort(ref_iterator) != ITER_DONE)1012 ok = ITER_ERROR;10131014return ok;1015}10161017static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1018struct object_id *peeled)1019{1020struct files_ref_iterator *iter =1021(struct files_ref_iterator *)ref_iterator;10221023returnref_iterator_peel(iter->iter0, peeled);1024}10251026static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1027{1028struct files_ref_iterator *iter =1029(struct files_ref_iterator *)ref_iterator;1030int ok = ITER_DONE;10311032if(iter->iter0)1033 ok =ref_iterator_abort(iter->iter0);10341035release_packed_ref_cache(iter->packed_ref_cache);1036base_ref_iterator_free(ref_iterator);1037return ok;1038}10391040static struct ref_iterator_vtable files_ref_iterator_vtable = {1041 files_ref_iterator_advance,1042 files_ref_iterator_peel,1043 files_ref_iterator_abort1044};10451046static struct ref_iterator *files_ref_iterator_begin(1047struct ref_store *ref_store,1048const char*prefix,unsigned int flags)1049{1050struct files_ref_store *refs;1051struct ref_iterator *loose_iter, *packed_iter;1052struct files_ref_iterator *iter;1053struct ref_iterator *ref_iterator;10541055if(ref_paranoia <0)1056 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1057if(ref_paranoia)1058 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10591060 refs =files_downcast(ref_store,1061 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1062"ref_iterator_begin");10631064 iter =xcalloc(1,sizeof(*iter));1065 ref_iterator = &iter->base;1066base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10671068/*1069 * We must make sure that all loose refs are read before1070 * accessing the packed-refs file; this avoids a race1071 * condition if loose refs are migrated to the packed-refs1072 * file by a simultaneous process, but our in-memory view is1073 * from before the migration. We ensure this as follows:1074 * First, we call start the loose refs iteration with its1075 * `prime_ref` argument set to true. This causes the loose1076 * references in the subtree to be pre-read into the cache.1077 * (If they've already been read, that's OK; we only need to1078 * guarantee that they're read before the packed refs, not1079 * *how much* before.) After that, we call1080 * get_packed_ref_cache(), which internally checks whether the1081 * packed-ref cache is up to date with what is on disk, and1082 * re-reads it if not.1083 */10841085 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1086 prefix,1);10871088 iter->packed_ref_cache =get_packed_ref_cache(refs);1089acquire_packed_ref_cache(iter->packed_ref_cache);1090 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1091 prefix,0);10921093 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1094 iter->flags = flags;10951096return ref_iterator;1097}10981099/*1100 * Verify that the reference locked by lock has the value old_sha1.1101 * Fail if the reference doesn't exist and mustexist is set. Return 01102 * on success. On error, write an error message to err, set errno, and1103 * return a negative value.1104 */1105static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1106const unsigned char*old_sha1,int mustexist,1107struct strbuf *err)1108{1109assert(err);11101111if(refs_read_ref_full(ref_store, lock->ref_name,1112 mustexist ? RESOLVE_REF_READING :0,1113 lock->old_oid.hash, NULL)) {1114if(old_sha1) {1115int save_errno = errno;1116strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1117 errno = save_errno;1118return-1;1119}else{1120oidclr(&lock->old_oid);1121return0;1122}1123}1124if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1125strbuf_addf(err,"ref '%s' is at%sbut expected%s",1126 lock->ref_name,1127oid_to_hex(&lock->old_oid),1128sha1_to_hex(old_sha1));1129 errno = EBUSY;1130return-1;1131}1132return0;1133}11341135static intremove_empty_directories(struct strbuf *path)1136{1137/*1138 * we want to create a file but there is a directory there;1139 * if that is an empty directory (or a directory that contains1140 * only empty directories), remove them.1141 */1142returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1143}11441145static intcreate_reflock(const char*path,void*cb)1146{1147struct lock_file *lk = cb;11481149returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1150}11511152/*1153 * Locks a ref returning the lock on success and NULL on failure.1154 * On failure errno is set to something meaningful.1155 */1156static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1157const char*refname,1158const unsigned char*old_sha1,1159const struct string_list *extras,1160const struct string_list *skip,1161unsigned int flags,int*type,1162struct strbuf *err)1163{1164struct strbuf ref_file = STRBUF_INIT;1165struct ref_lock *lock;1166int last_errno =0;1167int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1168int resolve_flags = RESOLVE_REF_NO_RECURSE;1169int resolved;11701171files_assert_main_repository(refs,"lock_ref_sha1_basic");1172assert(err);11731174 lock =xcalloc(1,sizeof(struct ref_lock));11751176if(mustexist)1177 resolve_flags |= RESOLVE_REF_READING;1178if(flags & REF_DELETING)1179 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11801181files_ref_path(refs, &ref_file, refname);1182 resolved = !!refs_resolve_ref_unsafe(&refs->base,1183 refname, resolve_flags,1184 lock->old_oid.hash, type);1185if(!resolved && errno == EISDIR) {1186/*1187 * we are trying to lock foo but we used to1188 * have foo/bar which now does not exist;1189 * it is normal for the empty directory 'foo'1190 * to remain.1191 */1192if(remove_empty_directories(&ref_file)) {1193 last_errno = errno;1194if(!refs_verify_refname_available(1195&refs->base,1196 refname, extras, skip, err))1197strbuf_addf(err,"there are still refs under '%s'",1198 refname);1199goto error_return;1200}1201 resolved = !!refs_resolve_ref_unsafe(&refs->base,1202 refname, resolve_flags,1203 lock->old_oid.hash, type);1204}1205if(!resolved) {1206 last_errno = errno;1207if(last_errno != ENOTDIR ||1208!refs_verify_refname_available(&refs->base, refname,1209 extras, skip, err))1210strbuf_addf(err,"unable to resolve reference '%s':%s",1211 refname,strerror(last_errno));12121213goto error_return;1214}12151216/*1217 * If the ref did not exist and we are creating it, make sure1218 * there is no existing packed ref whose name begins with our1219 * refname, nor a packed ref whose name is a proper prefix of1220 * our refname.1221 */1222if(is_null_oid(&lock->old_oid) &&1223refs_verify_refname_available(&refs->base, refname,1224 extras, skip, err)) {1225 last_errno = ENOTDIR;1226goto error_return;1227}12281229 lock->lk =xcalloc(1,sizeof(struct lock_file));12301231 lock->ref_name =xstrdup(refname);12321233if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1234 last_errno = errno;1235unable_to_lock_message(ref_file.buf, errno, err);1236goto error_return;1237}12381239if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1240 last_errno = errno;1241goto error_return;1242}1243goto out;12441245 error_return:1246unlock_ref(lock);1247 lock = NULL;12481249 out:1250strbuf_release(&ref_file);1251 errno = last_errno;1252return lock;1253}12541255/*1256 * Write an entry to the packed-refs file for the specified refname.1257 * If peeled is non-NULL, write it as the entry's peeled value.1258 */1259static voidwrite_packed_entry(FILE*fh,const char*refname,1260const unsigned char*sha1,1261const unsigned char*peeled)1262{1263fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1264if(peeled)1265fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1266}12671268/*1269 * Lock the packed-refs file for writing. Flags is passed to1270 * hold_lock_file_for_update(). Return 0 on success. On errors, set1271 * errno appropriately and return a nonzero value.1272 */1273static intlock_packed_refs(struct files_ref_store *refs,int flags)1274{1275static int timeout_configured =0;1276static int timeout_value =1000;1277struct packed_ref_cache *packed_ref_cache;12781279files_assert_main_repository(refs,"lock_packed_refs");12801281if(!timeout_configured) {1282git_config_get_int("core.packedrefstimeout", &timeout_value);1283 timeout_configured =1;1284}12851286if(hold_lock_file_for_update_timeout(1287&refs->packed_refs_lock,files_packed_refs_path(refs),1288 flags, timeout_value) <0)1289return-1;1290/*1291 * Get the current packed-refs while holding the lock. If the1292 * packed-refs file has been modified since we last read it,1293 * this will automatically invalidate the cache and re-read1294 * the packed-refs file.1295 */1296 packed_ref_cache =get_packed_ref_cache(refs);1297/* Increment the reference count to prevent it from being freed: */1298acquire_packed_ref_cache(packed_ref_cache);1299return0;1300}13011302/*1303 * Write the current version of the packed refs cache from memory to1304 * disk. The packed-refs file must already be locked for writing (see1305 * lock_packed_refs()). Return zero on success. On errors, set errno1306 * and return a nonzero value1307 */1308static intcommit_packed_refs(struct files_ref_store *refs)1309{1310struct packed_ref_cache *packed_ref_cache =1311get_packed_ref_cache(refs);1312int ok, error =0;1313int save_errno =0;1314FILE*out;1315struct ref_iterator *iter;13161317files_assert_main_repository(refs,"commit_packed_refs");13181319if(!is_lock_file_locked(&refs->packed_refs_lock))1320die("BUG: packed-refs not locked");13211322 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1323if(!out)1324die_errno("unable to fdopen packed-refs descriptor");13251326fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13271328 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1329while((ok =ref_iterator_advance(iter)) == ITER_OK) {1330struct object_id peeled;1331int peel_error =ref_iterator_peel(iter, &peeled);13321333write_packed_entry(out, iter->refname, iter->oid->hash,1334 peel_error ? NULL : peeled.hash);1335}13361337if(ok != ITER_DONE)1338die("error while iterating over references");13391340if(commit_lock_file(&refs->packed_refs_lock)) {1341 save_errno = errno;1342 error = -1;1343}1344release_packed_ref_cache(packed_ref_cache);1345 errno = save_errno;1346return error;1347}13481349/*1350 * Rollback the lockfile for the packed-refs file, and discard the1351 * in-memory packed reference cache. (The packed-refs file will be1352 * read anew if it is needed again after this function is called.)1353 */1354static voidrollback_packed_refs(struct files_ref_store *refs)1355{1356struct packed_ref_cache *packed_ref_cache =1357get_packed_ref_cache(refs);13581359files_assert_main_repository(refs,"rollback_packed_refs");13601361if(!is_lock_file_locked(&refs->packed_refs_lock))1362die("BUG: packed-refs not locked");1363rollback_lock_file(&refs->packed_refs_lock);1364release_packed_ref_cache(packed_ref_cache);1365clear_packed_ref_cache(refs);1366}13671368struct ref_to_prune {1369struct ref_to_prune *next;1370unsigned char sha1[20];1371char name[FLEX_ARRAY];1372};13731374enum{1375 REMOVE_EMPTY_PARENTS_REF =0x01,1376 REMOVE_EMPTY_PARENTS_REFLOG =0x021377};13781379/*1380 * Remove empty parent directories associated with the specified1381 * reference and/or its reflog, but spare [logs/]refs/ and immediate1382 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1383 * REMOVE_EMPTY_PARENTS_REFLOG.1384 */1385static voidtry_remove_empty_parents(struct files_ref_store *refs,1386const char*refname,1387unsigned int flags)1388{1389struct strbuf buf = STRBUF_INIT;1390struct strbuf sb = STRBUF_INIT;1391char*p, *q;1392int i;13931394strbuf_addstr(&buf, refname);1395 p = buf.buf;1396for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1397while(*p && *p !='/')1398 p++;1399/* tolerate duplicate slashes; see check_refname_format() */1400while(*p =='/')1401 p++;1402}1403 q = buf.buf + buf.len;1404while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1405while(q > p && *q !='/')1406 q--;1407while(q > p && *(q-1) =='/')1408 q--;1409if(q == p)1410break;1411strbuf_setlen(&buf, q - buf.buf);14121413strbuf_reset(&sb);1414files_ref_path(refs, &sb, buf.buf);1415if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1416 flags &= ~REMOVE_EMPTY_PARENTS_REF;14171418strbuf_reset(&sb);1419files_reflog_path(refs, &sb, buf.buf);1420if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1421 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1422}1423strbuf_release(&buf);1424strbuf_release(&sb);1425}14261427/* make sure nobody touched the ref, and unlink */1428static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1429{1430struct ref_transaction *transaction;1431struct strbuf err = STRBUF_INIT;14321433if(check_refname_format(r->name,0))1434return;14351436 transaction =ref_store_transaction_begin(&refs->base, &err);1437if(!transaction ||1438ref_transaction_delete(transaction, r->name, r->sha1,1439 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1440ref_transaction_commit(transaction, &err)) {1441ref_transaction_free(transaction);1442error("%s", err.buf);1443strbuf_release(&err);1444return;1445}1446ref_transaction_free(transaction);1447strbuf_release(&err);1448}14491450static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1451{1452while(r) {1453prune_ref(refs, r);1454 r = r->next;1455}1456}14571458/*1459 * Return true if the specified reference should be packed.1460 */1461static intshould_pack_ref(const char*refname,1462const struct object_id *oid,unsigned int ref_flags,1463unsigned int pack_flags)1464{1465/* Do not pack per-worktree refs: */1466if(ref_type(refname) != REF_TYPE_NORMAL)1467return0;14681469/* Do not pack non-tags unless PACK_REFS_ALL is set: */1470if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1471return0;14721473/* Do not pack symbolic refs: */1474if(ref_flags & REF_ISSYMREF)1475return0;14761477/* Do not pack broken refs: */1478if(!ref_resolves_to_object(refname, oid, ref_flags))1479return0;14801481return1;1482}14831484static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1485{1486struct files_ref_store *refs =1487files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1488"pack_refs");1489struct ref_iterator *iter;1490struct ref_dir *packed_refs;1491int ok;1492struct ref_to_prune *refs_to_prune = NULL;14931494lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1495 packed_refs =get_packed_refs(refs);14961497 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1498while((ok =ref_iterator_advance(iter)) == ITER_OK) {1499/*1500 * If the loose reference can be packed, add an entry1501 * in the packed ref cache. If the reference should be1502 * pruned, also add it to refs_to_prune.1503 */1504struct ref_entry *packed_entry;15051506if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1507 flags))1508continue;15091510/*1511 * Create an entry in the packed-refs cache equivalent1512 * to the one from the loose ref cache, except that1513 * we don't copy the peeled status, because we want it1514 * to be re-peeled.1515 */1516 packed_entry =find_ref_entry(packed_refs, iter->refname);1517if(packed_entry) {1518/* Overwrite existing packed entry with info from loose entry */1519 packed_entry->flag = REF_ISPACKED;1520oidcpy(&packed_entry->u.value.oid, iter->oid);1521}else{1522 packed_entry =create_ref_entry(iter->refname, iter->oid,1523 REF_ISPACKED,0);1524add_ref_entry(packed_refs, packed_entry);1525}1526oidclr(&packed_entry->u.value.peeled);15271528/* Schedule the loose reference for pruning if requested. */1529if((flags & PACK_REFS_PRUNE)) {1530struct ref_to_prune *n;1531FLEX_ALLOC_STR(n, name, iter->refname);1532hashcpy(n->sha1, iter->oid->hash);1533 n->next = refs_to_prune;1534 refs_to_prune = n;1535}1536}1537if(ok != ITER_DONE)1538die("error while iterating over references");15391540if(commit_packed_refs(refs))1541die_errno("unable to overwrite old ref-pack file");15421543prune_refs(refs, refs_to_prune);1544return0;1545}15461547/*1548 * Rewrite the packed-refs file, omitting any refs listed in1549 * 'refnames'. On error, leave packed-refs unchanged, write an error1550 * message to 'err', and return a nonzero value.1551 *1552 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1553 */1554static intrepack_without_refs(struct files_ref_store *refs,1555struct string_list *refnames,struct strbuf *err)1556{1557struct ref_dir *packed;1558struct string_list_item *refname;1559int ret, needs_repacking =0, removed =0;15601561files_assert_main_repository(refs,"repack_without_refs");1562assert(err);15631564/* Look for a packed ref */1565for_each_string_list_item(refname, refnames) {1566if(get_packed_ref(refs, refname->string)) {1567 needs_repacking =1;1568break;1569}1570}15711572/* Avoid locking if we have nothing to do */1573if(!needs_repacking)1574return0;/* no refname exists in packed refs */15751576if(lock_packed_refs(refs,0)) {1577unable_to_lock_message(files_packed_refs_path(refs), errno, err);1578return-1;1579}1580 packed =get_packed_refs(refs);15811582/* Remove refnames from the cache */1583for_each_string_list_item(refname, refnames)1584if(remove_entry_from_dir(packed, refname->string) != -1)1585 removed =1;1586if(!removed) {1587/*1588 * All packed entries disappeared while we were1589 * acquiring the lock.1590 */1591rollback_packed_refs(refs);1592return0;1593}15941595/* Write what remains */1596 ret =commit_packed_refs(refs);1597if(ret)1598strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1599strerror(errno));1600return ret;1601}16021603static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1604struct string_list *refnames,unsigned int flags)1605{1606struct files_ref_store *refs =1607files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1608struct strbuf err = STRBUF_INIT;1609int i, result =0;16101611if(!refnames->nr)1612return0;16131614 result =repack_without_refs(refs, refnames, &err);1615if(result) {1616/*1617 * If we failed to rewrite the packed-refs file, then1618 * it is unsafe to try to remove loose refs, because1619 * doing so might expose an obsolete packed value for1620 * a reference that might even point at an object that1621 * has been garbage collected.1622 */1623if(refnames->nr ==1)1624error(_("could not delete reference%s:%s"),1625 refnames->items[0].string, err.buf);1626else1627error(_("could not delete references:%s"), err.buf);16281629goto out;1630}16311632for(i =0; i < refnames->nr; i++) {1633const char*refname = refnames->items[i].string;16341635if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1636 result |=error(_("could not remove reference%s"), refname);1637}16381639out:1640strbuf_release(&err);1641return result;1642}16431644/*1645 * People using contrib's git-new-workdir have .git/logs/refs ->1646 * /some/other/path/.git/logs/refs, and that may live on another device.1647 *1648 * IOW, to avoid cross device rename errors, the temporary renamed log must1649 * live into logs/refs.1650 */1651#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16521653struct rename_cb {1654const char*tmp_renamed_log;1655int true_errno;1656};16571658static intrename_tmp_log_callback(const char*path,void*cb_data)1659{1660struct rename_cb *cb = cb_data;16611662if(rename(cb->tmp_renamed_log, path)) {1663/*1664 * rename(a, b) when b is an existing directory ought1665 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1666 * Sheesh. Record the true errno for error reporting,1667 * but report EISDIR to raceproof_create_file() so1668 * that it knows to retry.1669 */1670 cb->true_errno = errno;1671if(errno == ENOTDIR)1672 errno = EISDIR;1673return-1;1674}else{1675return0;1676}1677}16781679static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1680{1681struct strbuf path = STRBUF_INIT;1682struct strbuf tmp = STRBUF_INIT;1683struct rename_cb cb;1684int ret;16851686files_reflog_path(refs, &path, newrefname);1687files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1688 cb.tmp_renamed_log = tmp.buf;1689 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1690if(ret) {1691if(errno == EISDIR)1692error("directory not empty:%s", path.buf);1693else1694error("unable to move logfile%sto%s:%s",1695 tmp.buf, path.buf,1696strerror(cb.true_errno));1697}16981699strbuf_release(&path);1700strbuf_release(&tmp);1701return ret;1702}17031704static intwrite_ref_to_lockfile(struct ref_lock *lock,1705const struct object_id *oid,struct strbuf *err);1706static intcommit_ref_update(struct files_ref_store *refs,1707struct ref_lock *lock,1708const struct object_id *oid,const char*logmsg,1709struct strbuf *err);17101711static intfiles_rename_ref(struct ref_store *ref_store,1712const char*oldrefname,const char*newrefname,1713const char*logmsg)1714{1715struct files_ref_store *refs =1716files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1717struct object_id oid, orig_oid;1718int flag =0, logmoved =0;1719struct ref_lock *lock;1720struct stat loginfo;1721struct strbuf sb_oldref = STRBUF_INIT;1722struct strbuf sb_newref = STRBUF_INIT;1723struct strbuf tmp_renamed_log = STRBUF_INIT;1724int log, ret;1725struct strbuf err = STRBUF_INIT;17261727files_reflog_path(refs, &sb_oldref, oldrefname);1728files_reflog_path(refs, &sb_newref, newrefname);1729files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17301731 log = !lstat(sb_oldref.buf, &loginfo);1732if(log &&S_ISLNK(loginfo.st_mode)) {1733 ret =error("reflog for%sis a symlink", oldrefname);1734goto out;1735}17361737if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1738 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1739 orig_oid.hash, &flag)) {1740 ret =error("refname%snot found", oldrefname);1741goto out;1742}17431744if(flag & REF_ISSYMREF) {1745 ret =error("refname%sis a symbolic ref, renaming it is not supported",1746 oldrefname);1747goto out;1748}1749if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1750 ret =1;1751goto out;1752}17531754if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1755 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1756 oldrefname,strerror(errno));1757goto out;1758}17591760if(refs_delete_ref(&refs->base, logmsg, oldrefname,1761 orig_oid.hash, REF_NODEREF)) {1762error("unable to delete old%s", oldrefname);1763goto rollback;1764}17651766/*1767 * Since we are doing a shallow lookup, oid is not the1768 * correct value to pass to delete_ref as old_oid. But that1769 * doesn't matter, because an old_oid check wouldn't add to1770 * the safety anyway; we want to delete the reference whatever1771 * its current value.1772 */1773if(!refs_read_ref_full(&refs->base, newrefname,1774 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1775 oid.hash, NULL) &&1776refs_delete_ref(&refs->base, NULL, newrefname,1777 NULL, REF_NODEREF)) {1778if(errno == EISDIR) {1779struct strbuf path = STRBUF_INIT;1780int result;17811782files_ref_path(refs, &path, newrefname);1783 result =remove_empty_directories(&path);1784strbuf_release(&path);17851786if(result) {1787error("Directory not empty:%s", newrefname);1788goto rollback;1789}1790}else{1791error("unable to delete existing%s", newrefname);1792goto rollback;1793}1794}17951796if(log &&rename_tmp_log(refs, newrefname))1797goto rollback;17981799 logmoved = log;18001801 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1802 REF_NODEREF, NULL, &err);1803if(!lock) {1804error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1805strbuf_release(&err);1806goto rollback;1807}1808oidcpy(&lock->old_oid, &orig_oid);18091810if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1811commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1812error("unable to write current sha1 into%s:%s", newrefname, err.buf);1813strbuf_release(&err);1814goto rollback;1815}18161817 ret =0;1818goto out;18191820 rollback:1821 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1822 REF_NODEREF, NULL, &err);1823if(!lock) {1824error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1825strbuf_release(&err);1826goto rollbacklog;1827}18281829 flag = log_all_ref_updates;1830 log_all_ref_updates = LOG_REFS_NONE;1831if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1832commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1833error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1834strbuf_release(&err);1835}1836 log_all_ref_updates = flag;18371838 rollbacklog:1839if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1840error("unable to restore logfile%sfrom%s:%s",1841 oldrefname, newrefname,strerror(errno));1842if(!logmoved && log &&1843rename(tmp_renamed_log.buf, sb_oldref.buf))1844error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1845 oldrefname,strerror(errno));1846 ret =1;1847 out:1848strbuf_release(&sb_newref);1849strbuf_release(&sb_oldref);1850strbuf_release(&tmp_renamed_log);18511852return ret;1853}18541855static intclose_ref(struct ref_lock *lock)1856{1857if(close_lock_file(lock->lk))1858return-1;1859return0;1860}18611862static intcommit_ref(struct ref_lock *lock)1863{1864char*path =get_locked_file_path(lock->lk);1865struct stat st;18661867if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1868/*1869 * There is a directory at the path we want to rename1870 * the lockfile to. Hopefully it is empty; try to1871 * delete it.1872 */1873size_t len =strlen(path);1874struct strbuf sb_path = STRBUF_INIT;18751876strbuf_attach(&sb_path, path, len, len);18771878/*1879 * If this fails, commit_lock_file() will also fail1880 * and will report the problem.1881 */1882remove_empty_directories(&sb_path);1883strbuf_release(&sb_path);1884}else{1885free(path);1886}18871888if(commit_lock_file(lock->lk))1889return-1;1890return0;1891}18921893static intopen_or_create_logfile(const char*path,void*cb)1894{1895int*fd = cb;18961897*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1898return(*fd <0) ? -1:0;1899}19001901/*1902 * Create a reflog for a ref. If force_create = 0, only create the1903 * reflog for certain refs (those for which should_autocreate_reflog1904 * returns non-zero). Otherwise, create it regardless of the reference1905 * name. If the logfile already existed or was created, return 0 and1906 * set *logfd to the file descriptor opened for appending to the file.1907 * If no logfile exists and we decided not to create one, return 0 and1908 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1909 * return -1.1910 */1911static intlog_ref_setup(struct files_ref_store *refs,1912const char*refname,int force_create,1913int*logfd,struct strbuf *err)1914{1915struct strbuf logfile_sb = STRBUF_INIT;1916char*logfile;19171918files_reflog_path(refs, &logfile_sb, refname);1919 logfile =strbuf_detach(&logfile_sb, NULL);19201921if(force_create ||should_autocreate_reflog(refname)) {1922if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1923if(errno == ENOENT)1924strbuf_addf(err,"unable to create directory for '%s': "1925"%s", logfile,strerror(errno));1926else if(errno == EISDIR)1927strbuf_addf(err,"there are still logs under '%s'",1928 logfile);1929else1930strbuf_addf(err,"unable to append to '%s':%s",1931 logfile,strerror(errno));19321933goto error;1934}1935}else{1936*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1937if(*logfd <0) {1938if(errno == ENOENT || errno == EISDIR) {1939/*1940 * The logfile doesn't already exist,1941 * but that is not an error; it only1942 * means that we won't write log1943 * entries to it.1944 */1945;1946}else{1947strbuf_addf(err,"unable to append to '%s':%s",1948 logfile,strerror(errno));1949goto error;1950}1951}1952}19531954if(*logfd >=0)1955adjust_shared_perm(logfile);19561957free(logfile);1958return0;19591960error:1961free(logfile);1962return-1;1963}19641965static intfiles_create_reflog(struct ref_store *ref_store,1966const char*refname,int force_create,1967struct strbuf *err)1968{1969struct files_ref_store *refs =1970files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1971int fd;19721973if(log_ref_setup(refs, refname, force_create, &fd, err))1974return-1;19751976if(fd >=0)1977close(fd);19781979return0;1980}19811982static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1983const struct object_id *new_oid,1984const char*committer,const char*msg)1985{1986int msglen, written;1987unsigned maxlen, len;1988char*logrec;19891990 msglen = msg ?strlen(msg) :0;1991 maxlen =strlen(committer) + msglen +100;1992 logrec =xmalloc(maxlen);1993 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1994oid_to_hex(old_oid),1995oid_to_hex(new_oid),1996 committer);1997if(msglen)1998 len +=copy_reflog_msg(logrec + len -1, msg) -1;19992000 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2001free(logrec);2002if(written != len)2003return-1;20042005return0;2006}20072008static intfiles_log_ref_write(struct files_ref_store *refs,2009const char*refname,const struct object_id *old_oid,2010const struct object_id *new_oid,const char*msg,2011int flags,struct strbuf *err)2012{2013int logfd, result;20142015if(log_all_ref_updates == LOG_REFS_UNSET)2016 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20172018 result =log_ref_setup(refs, refname,2019 flags & REF_FORCE_CREATE_REFLOG,2020&logfd, err);20212022if(result)2023return result;20242025if(logfd <0)2026return0;2027 result =log_ref_write_fd(logfd, old_oid, new_oid,2028git_committer_info(0), msg);2029if(result) {2030struct strbuf sb = STRBUF_INIT;2031int save_errno = errno;20322033files_reflog_path(refs, &sb, refname);2034strbuf_addf(err,"unable to append to '%s':%s",2035 sb.buf,strerror(save_errno));2036strbuf_release(&sb);2037close(logfd);2038return-1;2039}2040if(close(logfd)) {2041struct strbuf sb = STRBUF_INIT;2042int save_errno = errno;20432044files_reflog_path(refs, &sb, refname);2045strbuf_addf(err,"unable to append to '%s':%s",2046 sb.buf,strerror(save_errno));2047strbuf_release(&sb);2048return-1;2049}2050return0;2051}20522053/*2054 * Write sha1 into the open lockfile, then close the lockfile. On2055 * errors, rollback the lockfile, fill in *err and2056 * return -1.2057 */2058static intwrite_ref_to_lockfile(struct ref_lock *lock,2059const struct object_id *oid,struct strbuf *err)2060{2061static char term ='\n';2062struct object *o;2063int fd;20642065 o =parse_object(oid);2066if(!o) {2067strbuf_addf(err,2068"trying to write ref '%s' with nonexistent object%s",2069 lock->ref_name,oid_to_hex(oid));2070unlock_ref(lock);2071return-1;2072}2073if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2074strbuf_addf(err,2075"trying to write non-commit object%sto branch '%s'",2076oid_to_hex(oid), lock->ref_name);2077unlock_ref(lock);2078return-1;2079}2080 fd =get_lock_file_fd(lock->lk);2081if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2082write_in_full(fd, &term,1) !=1||2083close_ref(lock) <0) {2084strbuf_addf(err,2085"couldn't write '%s'",get_lock_file_path(lock->lk));2086unlock_ref(lock);2087return-1;2088}2089return0;2090}20912092/*2093 * Commit a change to a loose reference that has already been written2094 * to the loose reference lockfile. Also update the reflogs if2095 * necessary, using the specified lockmsg (which can be NULL).2096 */2097static intcommit_ref_update(struct files_ref_store *refs,2098struct ref_lock *lock,2099const struct object_id *oid,const char*logmsg,2100struct strbuf *err)2101{2102files_assert_main_repository(refs,"commit_ref_update");21032104clear_loose_ref_cache(refs);2105if(files_log_ref_write(refs, lock->ref_name,2106&lock->old_oid, oid,2107 logmsg,0, err)) {2108char*old_msg =strbuf_detach(err, NULL);2109strbuf_addf(err,"cannot update the ref '%s':%s",2110 lock->ref_name, old_msg);2111free(old_msg);2112unlock_ref(lock);2113return-1;2114}21152116if(strcmp(lock->ref_name,"HEAD") !=0) {2117/*2118 * Special hack: If a branch is updated directly and HEAD2119 * points to it (may happen on the remote side of a push2120 * for example) then logically the HEAD reflog should be2121 * updated too.2122 * A generic solution implies reverse symref information,2123 * but finding all symrefs pointing to the given branch2124 * would be rather costly for this rare event (the direct2125 * update of a branch) to be worth it. So let's cheat and2126 * check with HEAD only which should cover 99% of all usage2127 * scenarios (even 100% of the default ones).2128 */2129struct object_id head_oid;2130int head_flag;2131const char*head_ref;21322133 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2134 RESOLVE_REF_READING,2135 head_oid.hash, &head_flag);2136if(head_ref && (head_flag & REF_ISSYMREF) &&2137!strcmp(head_ref, lock->ref_name)) {2138struct strbuf log_err = STRBUF_INIT;2139if(files_log_ref_write(refs,"HEAD",2140&lock->old_oid, oid,2141 logmsg,0, &log_err)) {2142error("%s", log_err.buf);2143strbuf_release(&log_err);2144}2145}2146}21472148if(commit_ref(lock)) {2149strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2150unlock_ref(lock);2151return-1;2152}21532154unlock_ref(lock);2155return0;2156}21572158static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2159{2160int ret = -1;2161#ifndef NO_SYMLINK_HEAD2162char*ref_path =get_locked_file_path(lock->lk);2163unlink(ref_path);2164 ret =symlink(target, ref_path);2165free(ref_path);21662167if(ret)2168fprintf(stderr,"no symlink - falling back to symbolic ref\n");2169#endif2170return ret;2171}21722173static voidupdate_symref_reflog(struct files_ref_store *refs,2174struct ref_lock *lock,const char*refname,2175const char*target,const char*logmsg)2176{2177struct strbuf err = STRBUF_INIT;2178struct object_id new_oid;2179if(logmsg &&2180!refs_read_ref_full(&refs->base, target,2181 RESOLVE_REF_READING, new_oid.hash, NULL) &&2182files_log_ref_write(refs, refname, &lock->old_oid,2183&new_oid, logmsg,0, &err)) {2184error("%s", err.buf);2185strbuf_release(&err);2186}2187}21882189static intcreate_symref_locked(struct files_ref_store *refs,2190struct ref_lock *lock,const char*refname,2191const char*target,const char*logmsg)2192{2193if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2194update_symref_reflog(refs, lock, refname, target, logmsg);2195return0;2196}21972198if(!fdopen_lock_file(lock->lk,"w"))2199returnerror("unable to fdopen%s:%s",2200 lock->lk->tempfile.filename.buf,strerror(errno));22012202update_symref_reflog(refs, lock, refname, target, logmsg);22032204/* no error check; commit_ref will check ferror */2205fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2206if(commit_ref(lock) <0)2207returnerror("unable to write symref for%s:%s", refname,2208strerror(errno));2209return0;2210}22112212static intfiles_create_symref(struct ref_store *ref_store,2213const char*refname,const char*target,2214const char*logmsg)2215{2216struct files_ref_store *refs =2217files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2218struct strbuf err = STRBUF_INIT;2219struct ref_lock *lock;2220int ret;22212222 lock =lock_ref_sha1_basic(refs, refname, NULL,2223 NULL, NULL, REF_NODEREF, NULL,2224&err);2225if(!lock) {2226error("%s", err.buf);2227strbuf_release(&err);2228return-1;2229}22302231 ret =create_symref_locked(refs, lock, refname, target, logmsg);2232unlock_ref(lock);2233return ret;2234}22352236static intfiles_reflog_exists(struct ref_store *ref_store,2237const char*refname)2238{2239struct files_ref_store *refs =2240files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2241struct strbuf sb = STRBUF_INIT;2242struct stat st;2243int ret;22442245files_reflog_path(refs, &sb, refname);2246 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2247strbuf_release(&sb);2248return ret;2249}22502251static intfiles_delete_reflog(struct ref_store *ref_store,2252const char*refname)2253{2254struct files_ref_store *refs =2255files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2256struct strbuf sb = STRBUF_INIT;2257int ret;22582259files_reflog_path(refs, &sb, refname);2260 ret =remove_path(sb.buf);2261strbuf_release(&sb);2262return ret;2263}22642265static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2266{2267struct object_id ooid, noid;2268char*email_end, *message;2269 timestamp_t timestamp;2270int tz;2271const char*p = sb->buf;22722273/* old SP new SP name <email> SP time TAB msg LF */2274if(!sb->len || sb->buf[sb->len -1] !='\n'||2275parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2276parse_oid_hex(p, &noid, &p) || *p++ !=' '||2277!(email_end =strchr(p,'>')) ||2278 email_end[1] !=' '||2279!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2280!message || message[0] !=' '||2281(message[1] !='+'&& message[1] !='-') ||2282!isdigit(message[2]) || !isdigit(message[3]) ||2283!isdigit(message[4]) || !isdigit(message[5]))2284return0;/* corrupt? */2285 email_end[1] ='\0';2286 tz =strtol(message +1, NULL,10);2287if(message[6] !='\t')2288 message +=6;2289else2290 message +=7;2291returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2292}22932294static char*find_beginning_of_line(char*bob,char*scan)2295{2296while(bob < scan && *(--scan) !='\n')2297;/* keep scanning backwards */2298/*2299 * Return either beginning of the buffer, or LF at the end of2300 * the previous line.2301 */2302return scan;2303}23042305static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2306const char*refname,2307 each_reflog_ent_fn fn,2308void*cb_data)2309{2310struct files_ref_store *refs =2311files_downcast(ref_store, REF_STORE_READ,2312"for_each_reflog_ent_reverse");2313struct strbuf sb = STRBUF_INIT;2314FILE*logfp;2315long pos;2316int ret =0, at_tail =1;23172318files_reflog_path(refs, &sb, refname);2319 logfp =fopen(sb.buf,"r");2320strbuf_release(&sb);2321if(!logfp)2322return-1;23232324/* Jump to the end */2325if(fseek(logfp,0, SEEK_END) <0)2326 ret =error("cannot seek back reflog for%s:%s",2327 refname,strerror(errno));2328 pos =ftell(logfp);2329while(!ret &&0< pos) {2330int cnt;2331size_t nread;2332char buf[BUFSIZ];2333char*endp, *scanp;23342335/* Fill next block from the end */2336 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2337if(fseek(logfp, pos - cnt, SEEK_SET)) {2338 ret =error("cannot seek back reflog for%s:%s",2339 refname,strerror(errno));2340break;2341}2342 nread =fread(buf, cnt,1, logfp);2343if(nread !=1) {2344 ret =error("cannot read%dbytes from reflog for%s:%s",2345 cnt, refname,strerror(errno));2346break;2347}2348 pos -= cnt;23492350 scanp = endp = buf + cnt;2351if(at_tail && scanp[-1] =='\n')2352/* Looking at the final LF at the end of the file */2353 scanp--;2354 at_tail =0;23552356while(buf < scanp) {2357/*2358 * terminating LF of the previous line, or the beginning2359 * of the buffer.2360 */2361char*bp;23622363 bp =find_beginning_of_line(buf, scanp);23642365if(*bp =='\n') {2366/*2367 * The newline is the end of the previous line,2368 * so we know we have complete line starting2369 * at (bp + 1). Prefix it onto any prior data2370 * we collected for the line and process it.2371 */2372strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2373 scanp = bp;2374 endp = bp +1;2375 ret =show_one_reflog_ent(&sb, fn, cb_data);2376strbuf_reset(&sb);2377if(ret)2378break;2379}else if(!pos) {2380/*2381 * We are at the start of the buffer, and the2382 * start of the file; there is no previous2383 * line, and we have everything for this one.2384 * Process it, and we can end the loop.2385 */2386strbuf_splice(&sb,0,0, buf, endp - buf);2387 ret =show_one_reflog_ent(&sb, fn, cb_data);2388strbuf_reset(&sb);2389break;2390}23912392if(bp == buf) {2393/*2394 * We are at the start of the buffer, and there2395 * is more file to read backwards. Which means2396 * we are in the middle of a line. Note that we2397 * may get here even if *bp was a newline; that2398 * just means we are at the exact end of the2399 * previous line, rather than some spot in the2400 * middle.2401 *2402 * Save away what we have to be combined with2403 * the data from the next read.2404 */2405strbuf_splice(&sb,0,0, buf, endp - buf);2406break;2407}2408}24092410}2411if(!ret && sb.len)2412die("BUG: reverse reflog parser had leftover data");24132414fclose(logfp);2415strbuf_release(&sb);2416return ret;2417}24182419static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2420const char*refname,2421 each_reflog_ent_fn fn,void*cb_data)2422{2423struct files_ref_store *refs =2424files_downcast(ref_store, REF_STORE_READ,2425"for_each_reflog_ent");2426FILE*logfp;2427struct strbuf sb = STRBUF_INIT;2428int ret =0;24292430files_reflog_path(refs, &sb, refname);2431 logfp =fopen(sb.buf,"r");2432strbuf_release(&sb);2433if(!logfp)2434return-1;24352436while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2437 ret =show_one_reflog_ent(&sb, fn, cb_data);2438fclose(logfp);2439strbuf_release(&sb);2440return ret;2441}24422443struct files_reflog_iterator {2444struct ref_iterator base;24452446struct ref_store *ref_store;2447struct dir_iterator *dir_iterator;2448struct object_id oid;2449};24502451static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2452{2453struct files_reflog_iterator *iter =2454(struct files_reflog_iterator *)ref_iterator;2455struct dir_iterator *diter = iter->dir_iterator;2456int ok;24572458while((ok =dir_iterator_advance(diter)) == ITER_OK) {2459int flags;24602461if(!S_ISREG(diter->st.st_mode))2462continue;2463if(diter->basename[0] =='.')2464continue;2465if(ends_with(diter->basename,".lock"))2466continue;24672468if(refs_read_ref_full(iter->ref_store,2469 diter->relative_path,0,2470 iter->oid.hash, &flags)) {2471error("bad ref for%s", diter->path.buf);2472continue;2473}24742475 iter->base.refname = diter->relative_path;2476 iter->base.oid = &iter->oid;2477 iter->base.flags = flags;2478return ITER_OK;2479}24802481 iter->dir_iterator = NULL;2482if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2483 ok = ITER_ERROR;2484return ok;2485}24862487static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2488struct object_id *peeled)2489{2490die("BUG: ref_iterator_peel() called for reflog_iterator");2491}24922493static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2494{2495struct files_reflog_iterator *iter =2496(struct files_reflog_iterator *)ref_iterator;2497int ok = ITER_DONE;24982499if(iter->dir_iterator)2500 ok =dir_iterator_abort(iter->dir_iterator);25012502base_ref_iterator_free(ref_iterator);2503return ok;2504}25052506static struct ref_iterator_vtable files_reflog_iterator_vtable = {2507 files_reflog_iterator_advance,2508 files_reflog_iterator_peel,2509 files_reflog_iterator_abort2510};25112512static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2513{2514struct files_ref_store *refs =2515files_downcast(ref_store, REF_STORE_READ,2516"reflog_iterator_begin");2517struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2518struct ref_iterator *ref_iterator = &iter->base;2519struct strbuf sb = STRBUF_INIT;25202521base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2522files_reflog_path(refs, &sb, NULL);2523 iter->dir_iterator =dir_iterator_begin(sb.buf);2524 iter->ref_store = ref_store;2525strbuf_release(&sb);2526return ref_iterator;2527}25282529/*2530 * If update is a direct update of head_ref (the reference pointed to2531 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2532 */2533static intsplit_head_update(struct ref_update *update,2534struct ref_transaction *transaction,2535const char*head_ref,2536struct string_list *affected_refnames,2537struct strbuf *err)2538{2539struct string_list_item *item;2540struct ref_update *new_update;25412542if((update->flags & REF_LOG_ONLY) ||2543(update->flags & REF_ISPRUNING) ||2544(update->flags & REF_UPDATE_VIA_HEAD))2545return0;25462547if(strcmp(update->refname, head_ref))2548return0;25492550/*2551 * First make sure that HEAD is not already in the2552 * transaction. This insertion is O(N) in the transaction2553 * size, but it happens at most once per transaction.2554 */2555 item =string_list_insert(affected_refnames,"HEAD");2556if(item->util) {2557/* An entry already existed */2558strbuf_addf(err,2559"multiple updates for 'HEAD' (including one "2560"via its referent '%s') are not allowed",2561 update->refname);2562return TRANSACTION_NAME_CONFLICT;2563}25642565 new_update =ref_transaction_add_update(2566 transaction,"HEAD",2567 update->flags | REF_LOG_ONLY | REF_NODEREF,2568 update->new_oid.hash, update->old_oid.hash,2569 update->msg);25702571 item->util = new_update;25722573return0;2574}25752576/*2577 * update is for a symref that points at referent and doesn't have2578 * REF_NODEREF set. Split it into two updates:2579 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2580 * - A new, separate update for the referent reference2581 * Note that the new update will itself be subject to splitting when2582 * the iteration gets to it.2583 */2584static intsplit_symref_update(struct files_ref_store *refs,2585struct ref_update *update,2586const char*referent,2587struct ref_transaction *transaction,2588struct string_list *affected_refnames,2589struct strbuf *err)2590{2591struct string_list_item *item;2592struct ref_update *new_update;2593unsigned int new_flags;25942595/*2596 * First make sure that referent is not already in the2597 * transaction. This insertion is O(N) in the transaction2598 * size, but it happens at most once per symref in a2599 * transaction.2600 */2601 item =string_list_insert(affected_refnames, referent);2602if(item->util) {2603/* An entry already existed */2604strbuf_addf(err,2605"multiple updates for '%s' (including one "2606"via symref '%s') are not allowed",2607 referent, update->refname);2608return TRANSACTION_NAME_CONFLICT;2609}26102611 new_flags = update->flags;2612if(!strcmp(update->refname,"HEAD")) {2613/*2614 * Record that the new update came via HEAD, so that2615 * when we process it, split_head_update() doesn't try2616 * to add another reflog update for HEAD. Note that2617 * this bit will be propagated if the new_update2618 * itself needs to be split.2619 */2620 new_flags |= REF_UPDATE_VIA_HEAD;2621}26222623 new_update =ref_transaction_add_update(2624 transaction, referent, new_flags,2625 update->new_oid.hash, update->old_oid.hash,2626 update->msg);26272628 new_update->parent_update = update;26292630/*2631 * Change the symbolic ref update to log only. Also, it2632 * doesn't need to check its old SHA-1 value, as that will be2633 * done when new_update is processed.2634 */2635 update->flags |= REF_LOG_ONLY | REF_NODEREF;2636 update->flags &= ~REF_HAVE_OLD;26372638 item->util = new_update;26392640return0;2641}26422643/*2644 * Return the refname under which update was originally requested.2645 */2646static const char*original_update_refname(struct ref_update *update)2647{2648while(update->parent_update)2649 update = update->parent_update;26502651return update->refname;2652}26532654/*2655 * Check whether the REF_HAVE_OLD and old_oid values stored in update2656 * are consistent with oid, which is the reference's current value. If2657 * everything is OK, return 0; otherwise, write an error message to2658 * err and return -1.2659 */2660static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2661struct strbuf *err)2662{2663if(!(update->flags & REF_HAVE_OLD) ||2664!oidcmp(oid, &update->old_oid))2665return0;26662667if(is_null_oid(&update->old_oid))2668strbuf_addf(err,"cannot lock ref '%s': "2669"reference already exists",2670original_update_refname(update));2671else if(is_null_oid(oid))2672strbuf_addf(err,"cannot lock ref '%s': "2673"reference is missing but expected%s",2674original_update_refname(update),2675oid_to_hex(&update->old_oid));2676else2677strbuf_addf(err,"cannot lock ref '%s': "2678"is at%sbut expected%s",2679original_update_refname(update),2680oid_to_hex(oid),2681oid_to_hex(&update->old_oid));26822683return-1;2684}26852686/*2687 * Prepare for carrying out update:2688 * - Lock the reference referred to by update.2689 * - Read the reference under lock.2690 * - Check that its old SHA-1 value (if specified) is correct, and in2691 * any case record it in update->lock->old_oid for later use when2692 * writing the reflog.2693 * - If it is a symref update without REF_NODEREF, split it up into a2694 * REF_LOG_ONLY update of the symref and add a separate update for2695 * the referent to transaction.2696 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2697 * update of HEAD.2698 */2699static intlock_ref_for_update(struct files_ref_store *refs,2700struct ref_update *update,2701struct ref_transaction *transaction,2702const char*head_ref,2703struct string_list *affected_refnames,2704struct strbuf *err)2705{2706struct strbuf referent = STRBUF_INIT;2707int mustexist = (update->flags & REF_HAVE_OLD) &&2708!is_null_oid(&update->old_oid);2709int ret;2710struct ref_lock *lock;27112712files_assert_main_repository(refs,"lock_ref_for_update");27132714if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2715 update->flags |= REF_DELETING;27162717if(head_ref) {2718 ret =split_head_update(update, transaction, head_ref,2719 affected_refnames, err);2720if(ret)2721return ret;2722}27232724 ret =lock_raw_ref(refs, update->refname, mustexist,2725 affected_refnames, NULL,2726&lock, &referent,2727&update->type, err);2728if(ret) {2729char*reason;27302731 reason =strbuf_detach(err, NULL);2732strbuf_addf(err,"cannot lock ref '%s':%s",2733original_update_refname(update), reason);2734free(reason);2735return ret;2736}27372738 update->backend_data = lock;27392740if(update->type & REF_ISSYMREF) {2741if(update->flags & REF_NODEREF) {2742/*2743 * We won't be reading the referent as part of2744 * the transaction, so we have to read it here2745 * to record and possibly check old_sha1:2746 */2747if(refs_read_ref_full(&refs->base,2748 referent.buf,0,2749 lock->old_oid.hash, NULL)) {2750if(update->flags & REF_HAVE_OLD) {2751strbuf_addf(err,"cannot lock ref '%s': "2752"error reading reference",2753original_update_refname(update));2754return-1;2755}2756}else if(check_old_oid(update, &lock->old_oid, err)) {2757return TRANSACTION_GENERIC_ERROR;2758}2759}else{2760/*2761 * Create a new update for the reference this2762 * symref is pointing at. Also, we will record2763 * and verify old_sha1 for this update as part2764 * of processing the split-off update, so we2765 * don't have to do it here.2766 */2767 ret =split_symref_update(refs, update,2768 referent.buf, transaction,2769 affected_refnames, err);2770if(ret)2771return ret;2772}2773}else{2774struct ref_update *parent_update;27752776if(check_old_oid(update, &lock->old_oid, err))2777return TRANSACTION_GENERIC_ERROR;27782779/*2780 * If this update is happening indirectly because of a2781 * symref update, record the old SHA-1 in the parent2782 * update:2783 */2784for(parent_update = update->parent_update;2785 parent_update;2786 parent_update = parent_update->parent_update) {2787struct ref_lock *parent_lock = parent_update->backend_data;2788oidcpy(&parent_lock->old_oid, &lock->old_oid);2789}2790}27912792if((update->flags & REF_HAVE_NEW) &&2793!(update->flags & REF_DELETING) &&2794!(update->flags & REF_LOG_ONLY)) {2795if(!(update->type & REF_ISSYMREF) &&2796!oidcmp(&lock->old_oid, &update->new_oid)) {2797/*2798 * The reference already has the desired2799 * value, so we don't need to write it.2800 */2801}else if(write_ref_to_lockfile(lock, &update->new_oid,2802 err)) {2803char*write_err =strbuf_detach(err, NULL);28042805/*2806 * The lock was freed upon failure of2807 * write_ref_to_lockfile():2808 */2809 update->backend_data = NULL;2810strbuf_addf(err,2811"cannot update ref '%s':%s",2812 update->refname, write_err);2813free(write_err);2814return TRANSACTION_GENERIC_ERROR;2815}else{2816 update->flags |= REF_NEEDS_COMMIT;2817}2818}2819if(!(update->flags & REF_NEEDS_COMMIT)) {2820/*2821 * We didn't call write_ref_to_lockfile(), so2822 * the lockfile is still open. Close it to2823 * free up the file descriptor:2824 */2825if(close_ref(lock)) {2826strbuf_addf(err,"couldn't close '%s.lock'",2827 update->refname);2828return TRANSACTION_GENERIC_ERROR;2829}2830}2831return0;2832}28332834/*2835 * Unlock any references in `transaction` that are still locked, and2836 * mark the transaction closed.2837 */2838static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2839{2840size_t i;28412842for(i =0; i < transaction->nr; i++) {2843struct ref_update *update = transaction->updates[i];2844struct ref_lock *lock = update->backend_data;28452846if(lock) {2847unlock_ref(lock);2848 update->backend_data = NULL;2849}2850}28512852 transaction->state = REF_TRANSACTION_CLOSED;2853}28542855static intfiles_transaction_prepare(struct ref_store *ref_store,2856struct ref_transaction *transaction,2857struct strbuf *err)2858{2859struct files_ref_store *refs =2860files_downcast(ref_store, REF_STORE_WRITE,2861"ref_transaction_prepare");2862size_t i;2863int ret =0;2864struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2865char*head_ref = NULL;2866int head_type;2867struct object_id head_oid;28682869assert(err);28702871if(!transaction->nr)2872goto cleanup;28732874/*2875 * Fail if a refname appears more than once in the2876 * transaction. (If we end up splitting up any updates using2877 * split_symref_update() or split_head_update(), those2878 * functions will check that the new updates don't have the2879 * same refname as any existing ones.)2880 */2881for(i =0; i < transaction->nr; i++) {2882struct ref_update *update = transaction->updates[i];2883struct string_list_item *item =2884string_list_append(&affected_refnames, update->refname);28852886/*2887 * We store a pointer to update in item->util, but at2888 * the moment we never use the value of this field2889 * except to check whether it is non-NULL.2890 */2891 item->util = update;2892}2893string_list_sort(&affected_refnames);2894if(ref_update_reject_duplicates(&affected_refnames, err)) {2895 ret = TRANSACTION_GENERIC_ERROR;2896goto cleanup;2897}28982899/*2900 * Special hack: If a branch is updated directly and HEAD2901 * points to it (may happen on the remote side of a push2902 * for example) then logically the HEAD reflog should be2903 * updated too.2904 *2905 * A generic solution would require reverse symref lookups,2906 * but finding all symrefs pointing to a given branch would be2907 * rather costly for this rare event (the direct update of a2908 * branch) to be worth it. So let's cheat and check with HEAD2909 * only, which should cover 99% of all usage scenarios (even2910 * 100% of the default ones).2911 *2912 * So if HEAD is a symbolic reference, then record the name of2913 * the reference that it points to. If we see an update of2914 * head_ref within the transaction, then split_head_update()2915 * arranges for the reflog of HEAD to be updated, too.2916 */2917 head_ref =refs_resolve_refdup(ref_store,"HEAD",2918 RESOLVE_REF_NO_RECURSE,2919 head_oid.hash, &head_type);29202921if(head_ref && !(head_type & REF_ISSYMREF)) {2922free(head_ref);2923 head_ref = NULL;2924}29252926/*2927 * Acquire all locks, verify old values if provided, check2928 * that new values are valid, and write new values to the2929 * lockfiles, ready to be activated. Only keep one lockfile2930 * open at a time to avoid running out of file descriptors.2931 * Note that lock_ref_for_update() might append more updates2932 * to the transaction.2933 */2934for(i =0; i < transaction->nr; i++) {2935struct ref_update *update = transaction->updates[i];29362937 ret =lock_ref_for_update(refs, update, transaction,2938 head_ref, &affected_refnames, err);2939if(ret)2940break;2941}29422943cleanup:2944free(head_ref);2945string_list_clear(&affected_refnames,0);29462947if(ret)2948files_transaction_cleanup(transaction);2949else2950 transaction->state = REF_TRANSACTION_PREPARED;29512952return ret;2953}29542955static intfiles_transaction_finish(struct ref_store *ref_store,2956struct ref_transaction *transaction,2957struct strbuf *err)2958{2959struct files_ref_store *refs =2960files_downcast(ref_store,0,"ref_transaction_finish");2961size_t i;2962int ret =0;2963struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2964struct string_list_item *ref_to_delete;2965struct strbuf sb = STRBUF_INIT;29662967assert(err);29682969if(!transaction->nr) {2970 transaction->state = REF_TRANSACTION_CLOSED;2971return0;2972}29732974/* Perform updates first so live commits remain referenced */2975for(i =0; i < transaction->nr; i++) {2976struct ref_update *update = transaction->updates[i];2977struct ref_lock *lock = update->backend_data;29782979if(update->flags & REF_NEEDS_COMMIT ||2980 update->flags & REF_LOG_ONLY) {2981if(files_log_ref_write(refs,2982 lock->ref_name,2983&lock->old_oid,2984&update->new_oid,2985 update->msg, update->flags,2986 err)) {2987char*old_msg =strbuf_detach(err, NULL);29882989strbuf_addf(err,"cannot update the ref '%s':%s",2990 lock->ref_name, old_msg);2991free(old_msg);2992unlock_ref(lock);2993 update->backend_data = NULL;2994 ret = TRANSACTION_GENERIC_ERROR;2995goto cleanup;2996}2997}2998if(update->flags & REF_NEEDS_COMMIT) {2999clear_loose_ref_cache(refs);3000if(commit_ref(lock)) {3001strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3002unlock_ref(lock);3003 update->backend_data = NULL;3004 ret = TRANSACTION_GENERIC_ERROR;3005goto cleanup;3006}3007}3008}3009/* Perform deletes now that updates are safely completed */3010for(i =0; i < transaction->nr; i++) {3011struct ref_update *update = transaction->updates[i];3012struct ref_lock *lock = update->backend_data;30133014if(update->flags & REF_DELETING &&3015!(update->flags & REF_LOG_ONLY)) {3016if(!(update->type & REF_ISPACKED) ||3017 update->type & REF_ISSYMREF) {3018/* It is a loose reference. */3019strbuf_reset(&sb);3020files_ref_path(refs, &sb, lock->ref_name);3021if(unlink_or_msg(sb.buf, err)) {3022 ret = TRANSACTION_GENERIC_ERROR;3023goto cleanup;3024}3025 update->flags |= REF_DELETED_LOOSE;3026}30273028if(!(update->flags & REF_ISPRUNING))3029string_list_append(&refs_to_delete,3030 lock->ref_name);3031}3032}30333034if(repack_without_refs(refs, &refs_to_delete, err)) {3035 ret = TRANSACTION_GENERIC_ERROR;3036goto cleanup;3037}30383039/* Delete the reflogs of any references that were deleted: */3040for_each_string_list_item(ref_to_delete, &refs_to_delete) {3041strbuf_reset(&sb);3042files_reflog_path(refs, &sb, ref_to_delete->string);3043if(!unlink_or_warn(sb.buf))3044try_remove_empty_parents(refs, ref_to_delete->string,3045 REMOVE_EMPTY_PARENTS_REFLOG);3046}30473048clear_loose_ref_cache(refs);30493050cleanup:3051files_transaction_cleanup(transaction);30523053for(i =0; i < transaction->nr; i++) {3054struct ref_update *update = transaction->updates[i];30553056if(update->flags & REF_DELETED_LOOSE) {3057/*3058 * The loose reference was deleted. Delete any3059 * empty parent directories. (Note that this3060 * can only work because we have already3061 * removed the lockfile.)3062 */3063try_remove_empty_parents(refs, update->refname,3064 REMOVE_EMPTY_PARENTS_REF);3065}3066}30673068strbuf_release(&sb);3069string_list_clear(&refs_to_delete,0);3070return ret;3071}30723073static intfiles_transaction_abort(struct ref_store *ref_store,3074struct ref_transaction *transaction,3075struct strbuf *err)3076{3077files_transaction_cleanup(transaction);3078return0;3079}30803081static intref_present(const char*refname,3082const struct object_id *oid,int flags,void*cb_data)3083{3084struct string_list *affected_refnames = cb_data;30853086returnstring_list_has_string(affected_refnames, refname);3087}30883089static intfiles_initial_transaction_commit(struct ref_store *ref_store,3090struct ref_transaction *transaction,3091struct strbuf *err)3092{3093struct files_ref_store *refs =3094files_downcast(ref_store, REF_STORE_WRITE,3095"initial_ref_transaction_commit");3096size_t i;3097int ret =0;3098struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30993100assert(err);31013102if(transaction->state != REF_TRANSACTION_OPEN)3103die("BUG: commit called for transaction that is not open");31043105/* Fail if a refname appears more than once in the transaction: */3106for(i =0; i < transaction->nr; i++)3107string_list_append(&affected_refnames,3108 transaction->updates[i]->refname);3109string_list_sort(&affected_refnames);3110if(ref_update_reject_duplicates(&affected_refnames, err)) {3111 ret = TRANSACTION_GENERIC_ERROR;3112goto cleanup;3113}31143115/*3116 * It's really undefined to call this function in an active3117 * repository or when there are existing references: we are3118 * only locking and changing packed-refs, so (1) any3119 * simultaneous processes might try to change a reference at3120 * the same time we do, and (2) any existing loose versions of3121 * the references that we are setting would have precedence3122 * over our values. But some remote helpers create the remote3123 * "HEAD" and "master" branches before calling this function,3124 * so here we really only check that none of the references3125 * that we are creating already exists.3126 */3127if(refs_for_each_rawref(&refs->base, ref_present,3128&affected_refnames))3129die("BUG: initial ref transaction called with existing refs");31303131for(i =0; i < transaction->nr; i++) {3132struct ref_update *update = transaction->updates[i];31333134if((update->flags & REF_HAVE_OLD) &&3135!is_null_oid(&update->old_oid))3136die("BUG: initial ref transaction with old_sha1 set");3137if(refs_verify_refname_available(&refs->base, update->refname,3138&affected_refnames, NULL,3139 err)) {3140 ret = TRANSACTION_NAME_CONFLICT;3141goto cleanup;3142}3143}31443145if(lock_packed_refs(refs,0)) {3146strbuf_addf(err,"unable to lock packed-refs file:%s",3147strerror(errno));3148 ret = TRANSACTION_GENERIC_ERROR;3149goto cleanup;3150}31513152for(i =0; i < transaction->nr; i++) {3153struct ref_update *update = transaction->updates[i];31543155if((update->flags & REF_HAVE_NEW) &&3156!is_null_oid(&update->new_oid))3157add_packed_ref(refs, update->refname,3158&update->new_oid);3159}31603161if(commit_packed_refs(refs)) {3162strbuf_addf(err,"unable to commit packed-refs file:%s",3163strerror(errno));3164 ret = TRANSACTION_GENERIC_ERROR;3165goto cleanup;3166}31673168cleanup:3169 transaction->state = REF_TRANSACTION_CLOSED;3170string_list_clear(&affected_refnames,0);3171return ret;3172}31733174struct expire_reflog_cb {3175unsigned int flags;3176 reflog_expiry_should_prune_fn *should_prune_fn;3177void*policy_cb;3178FILE*newlog;3179struct object_id last_kept_oid;3180};31813182static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3183const char*email, timestamp_t timestamp,int tz,3184const char*message,void*cb_data)3185{3186struct expire_reflog_cb *cb = cb_data;3187struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;31883189if(cb->flags & EXPIRE_REFLOGS_REWRITE)3190 ooid = &cb->last_kept_oid;31913192if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3193 message, policy_cb)) {3194if(!cb->newlog)3195printf("would prune%s", message);3196else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3197printf("prune%s", message);3198}else{3199if(cb->newlog) {3200fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3201oid_to_hex(ooid),oid_to_hex(noid),3202 email, timestamp, tz, message);3203oidcpy(&cb->last_kept_oid, noid);3204}3205if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3206printf("keep%s", message);3207}3208return0;3209}32103211static intfiles_reflog_expire(struct ref_store *ref_store,3212const char*refname,const unsigned char*sha1,3213unsigned int flags,3214 reflog_expiry_prepare_fn prepare_fn,3215 reflog_expiry_should_prune_fn should_prune_fn,3216 reflog_expiry_cleanup_fn cleanup_fn,3217void*policy_cb_data)3218{3219struct files_ref_store *refs =3220files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3221static struct lock_file reflog_lock;3222struct expire_reflog_cb cb;3223struct ref_lock *lock;3224struct strbuf log_file_sb = STRBUF_INIT;3225char*log_file;3226int status =0;3227int type;3228struct strbuf err = STRBUF_INIT;3229struct object_id oid;32303231memset(&cb,0,sizeof(cb));3232 cb.flags = flags;3233 cb.policy_cb = policy_cb_data;3234 cb.should_prune_fn = should_prune_fn;32353236/*3237 * The reflog file is locked by holding the lock on the3238 * reference itself, plus we might need to update the3239 * reference if --updateref was specified:3240 */3241 lock =lock_ref_sha1_basic(refs, refname, sha1,3242 NULL, NULL, REF_NODEREF,3243&type, &err);3244if(!lock) {3245error("cannot lock ref '%s':%s", refname, err.buf);3246strbuf_release(&err);3247return-1;3248}3249if(!refs_reflog_exists(ref_store, refname)) {3250unlock_ref(lock);3251return0;3252}32533254files_reflog_path(refs, &log_file_sb, refname);3255 log_file =strbuf_detach(&log_file_sb, NULL);3256if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3257/*3258 * Even though holding $GIT_DIR/logs/$reflog.lock has3259 * no locking implications, we use the lock_file3260 * machinery here anyway because it does a lot of the3261 * work we need, including cleaning up if the program3262 * exits unexpectedly.3263 */3264if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3265struct strbuf err = STRBUF_INIT;3266unable_to_lock_message(log_file, errno, &err);3267error("%s", err.buf);3268strbuf_release(&err);3269goto failure;3270}3271 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3272if(!cb.newlog) {3273error("cannot fdopen%s(%s)",3274get_lock_file_path(&reflog_lock),strerror(errno));3275goto failure;3276}3277}32783279hashcpy(oid.hash, sha1);32803281(*prepare_fn)(refname, &oid, cb.policy_cb);3282refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3283(*cleanup_fn)(cb.policy_cb);32843285if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3286/*3287 * It doesn't make sense to adjust a reference pointed3288 * to by a symbolic ref based on expiring entries in3289 * the symbolic reference's reflog. Nor can we update3290 * a reference if there are no remaining reflog3291 * entries.3292 */3293int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3294!(type & REF_ISSYMREF) &&3295!is_null_oid(&cb.last_kept_oid);32963297if(close_lock_file(&reflog_lock)) {3298 status |=error("couldn't write%s:%s", log_file,3299strerror(errno));3300}else if(update &&3301(write_in_full(get_lock_file_fd(lock->lk),3302oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3303write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3304close_ref(lock) <0)) {3305 status |=error("couldn't write%s",3306get_lock_file_path(lock->lk));3307rollback_lock_file(&reflog_lock);3308}else if(commit_lock_file(&reflog_lock)) {3309 status |=error("unable to write reflog '%s' (%s)",3310 log_file,strerror(errno));3311}else if(update &&commit_ref(lock)) {3312 status |=error("couldn't set%s", lock->ref_name);3313}3314}3315free(log_file);3316unlock_ref(lock);3317return status;33183319 failure:3320rollback_lock_file(&reflog_lock);3321free(log_file);3322unlock_ref(lock);3323return-1;3324}33253326static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3327{3328struct files_ref_store *refs =3329files_downcast(ref_store, REF_STORE_WRITE,"init_db");3330struct strbuf sb = STRBUF_INIT;33313332/*3333 * Create .git/refs/{heads,tags}3334 */3335files_ref_path(refs, &sb,"refs/heads");3336safe_create_dir(sb.buf,1);33373338strbuf_reset(&sb);3339files_ref_path(refs, &sb,"refs/tags");3340safe_create_dir(sb.buf,1);33413342strbuf_release(&sb);3343return0;3344}33453346struct ref_storage_be refs_be_files = {3347 NULL,3348"files",3349 files_ref_store_create,3350 files_init_db,3351 files_transaction_prepare,3352 files_transaction_finish,3353 files_transaction_abort,3354 files_initial_transaction_commit,33553356 files_pack_refs,3357 files_peel_ref,3358 files_create_symref,3359 files_delete_refs,3360 files_rename_ref,33613362 files_ref_iterator_begin,3363 files_read_raw_ref,33643365 files_reflog_iterator_begin,3366 files_for_each_reflog_ent,3367 files_for_each_reflog_ent_reverse,3368 files_reflog_exists,3369 files_create_reflog,3370 files_delete_reflog,3371 files_reflog_expire3372};