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 * Iff the packed-refs file associated with this instance is 67 * currently locked for writing, this points at the associated 68 * lock (which is owned by somebody else). 69 */ 70struct lock_file *packed_refs_lock; 71}; 72 73/* Lock used for the main packed-refs file: */ 74static struct lock_file packlock; 75 76/* 77 * Increment the reference count of *packed_refs. 78 */ 79static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 80{ 81 packed_refs->referrers++; 82} 83 84/* 85 * Decrease the reference count of *packed_refs. If it goes to zero, 86 * free *packed_refs and return true; otherwise return false. 87 */ 88static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 89{ 90if(!--packed_refs->referrers) { 91free_ref_cache(packed_refs->cache); 92stat_validity_clear(&packed_refs->validity); 93free(packed_refs); 94return1; 95}else{ 96return0; 97} 98} 99 100static voidclear_packed_ref_cache(struct files_ref_store *refs) 101{ 102if(refs->packed) { 103struct packed_ref_cache *packed_refs = refs->packed; 104 105if(refs->packed_refs_lock) 106die("BUG: packed-ref cache cleared while locked"); 107 refs->packed = NULL; 108release_packed_ref_cache(packed_refs); 109} 110} 111 112static voidclear_loose_ref_cache(struct files_ref_store *refs) 113{ 114if(refs->loose) { 115free_ref_cache(refs->loose); 116 refs->loose = NULL; 117} 118} 119 120/* 121 * Create a new submodule ref cache and add it to the internal 122 * set of caches. 123 */ 124static struct ref_store *files_ref_store_create(const char*gitdir, 125unsigned int flags) 126{ 127struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 128struct ref_store *ref_store = (struct ref_store *)refs; 129struct strbuf sb = STRBUF_INIT; 130 131base_ref_store_init(ref_store, &refs_be_files); 132 refs->store_flags = flags; 133 134 refs->gitdir =xstrdup(gitdir); 135get_common_dir_noenv(&sb, gitdir); 136 refs->gitcommondir =strbuf_detach(&sb, NULL); 137strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 138 refs->packed_refs_path =strbuf_detach(&sb, NULL); 139 140return ref_store; 141} 142 143/* 144 * Die if refs is not the main ref store. caller is used in any 145 * necessary error messages. 146 */ 147static voidfiles_assert_main_repository(struct files_ref_store *refs, 148const char*caller) 149{ 150if(refs->store_flags & REF_STORE_MAIN) 151return; 152 153die("BUG: operation%sonly allowed for main ref store", caller); 154} 155 156/* 157 * Downcast ref_store to files_ref_store. Die if ref_store is not a 158 * files_ref_store. required_flags is compared with ref_store's 159 * store_flags to ensure the ref_store has all required capabilities. 160 * "caller" is used in any necessary error messages. 161 */ 162static struct files_ref_store *files_downcast(struct ref_store *ref_store, 163unsigned int required_flags, 164const char*caller) 165{ 166struct files_ref_store *refs; 167 168if(ref_store->be != &refs_be_files) 169die("BUG: ref_store is type\"%s\"not\"files\"in%s", 170 ref_store->be->name, caller); 171 172 refs = (struct files_ref_store *)ref_store; 173 174if((refs->store_flags & required_flags) != required_flags) 175die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 176 caller, required_flags, refs->store_flags); 177 178return refs; 179} 180 181/* The length of a peeled reference line in packed-refs, including EOL: */ 182#define PEELED_LINE_LENGTH 42 183 184/* 185 * The packed-refs header line that we write out. Perhaps other 186 * traits will be added later. The trailing space is required. 187 */ 188static const char PACKED_REFS_HEADER[] = 189"# pack-refs with: peeled fully-peeled\n"; 190 191/* 192 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 193 * Return a pointer to the refname within the line (null-terminated), 194 * or NULL if there was a problem. 195 */ 196static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 197{ 198const char*ref; 199 200if(parse_oid_hex(line->buf, oid, &ref) <0) 201return NULL; 202if(!isspace(*ref++)) 203return NULL; 204 205if(isspace(*ref)) 206return NULL; 207 208if(line->buf[line->len -1] !='\n') 209return NULL; 210 line->buf[--line->len] =0; 211 212return ref; 213} 214 215/* 216 * Read f, which is a packed-refs file, into dir. 217 * 218 * A comment line of the form "# pack-refs with: " may contain zero or 219 * more traits. We interpret the traits as follows: 220 * 221 * No traits: 222 * 223 * Probably no references are peeled. But if the file contains a 224 * peeled value for a reference, we will use it. 225 * 226 * peeled: 227 * 228 * References under "refs/tags/", if they *can* be peeled, *are* 229 * peeled in this file. References outside of "refs/tags/" are 230 * probably not peeled even if they could have been, but if we find 231 * a peeled value for such a reference we will use it. 232 * 233 * fully-peeled: 234 * 235 * All references in the file that can be peeled are peeled. 236 * Inversely (and this is more important), any references in the 237 * file for which no peeled value is recorded is not peelable. This 238 * trait should typically be written alongside "peeled" for 239 * compatibility with older clients, but we do not require it 240 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 241 */ 242static voidread_packed_refs(FILE*f,struct ref_dir *dir) 243{ 244struct ref_entry *last = NULL; 245struct strbuf line = STRBUF_INIT; 246enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 247 248while(strbuf_getwholeline(&line, f,'\n') != EOF) { 249struct object_id oid; 250const char*refname; 251const char*traits; 252 253if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 254if(strstr(traits," fully-peeled ")) 255 peeled = PEELED_FULLY; 256else if(strstr(traits," peeled ")) 257 peeled = PEELED_TAGS; 258/* perhaps other traits later as well */ 259continue; 260} 261 262 refname =parse_ref_line(&line, &oid); 263if(refname) { 264int flag = REF_ISPACKED; 265 266if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 267if(!refname_is_safe(refname)) 268die("packed refname is dangerous:%s", refname); 269oidclr(&oid); 270 flag |= REF_BAD_NAME | REF_ISBROKEN; 271} 272 last =create_ref_entry(refname, &oid, flag,0); 273if(peeled == PEELED_FULLY || 274(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 275 last->flag |= REF_KNOWS_PEELED; 276add_ref_entry(dir, last); 277continue; 278} 279if(last && 280 line.buf[0] =='^'&& 281 line.len == PEELED_LINE_LENGTH && 282 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 283!get_oid_hex(line.buf +1, &oid)) { 284oidcpy(&last->u.value.peeled, &oid); 285/* 286 * Regardless of what the file header said, 287 * we definitely know the value of *this* 288 * reference: 289 */ 290 last->flag |= REF_KNOWS_PEELED; 291} 292} 293 294strbuf_release(&line); 295} 296 297static const char*files_packed_refs_path(struct files_ref_store *refs) 298{ 299return refs->packed_refs_path; 300} 301 302static voidfiles_reflog_path(struct files_ref_store *refs, 303struct strbuf *sb, 304const char*refname) 305{ 306if(!refname) { 307/* 308 * FIXME: of course this is wrong in multi worktree 309 * setting. To be fixed real soon. 310 */ 311strbuf_addf(sb,"%s/logs", refs->gitcommondir); 312return; 313} 314 315switch(ref_type(refname)) { 316case REF_TYPE_PER_WORKTREE: 317case REF_TYPE_PSEUDOREF: 318strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 319break; 320case REF_TYPE_NORMAL: 321strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 322break; 323default: 324die("BUG: unknown ref type%dof ref%s", 325ref_type(refname), refname); 326} 327} 328 329static voidfiles_ref_path(struct files_ref_store *refs, 330struct strbuf *sb, 331const char*refname) 332{ 333switch(ref_type(refname)) { 334case REF_TYPE_PER_WORKTREE: 335case REF_TYPE_PSEUDOREF: 336strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 337break; 338case REF_TYPE_NORMAL: 339strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 340break; 341default: 342die("BUG: unknown ref type%dof ref%s", 343ref_type(refname), refname); 344} 345} 346 347/* 348 * Get the packed_ref_cache for the specified files_ref_store, 349 * creating it if necessary. 350 */ 351static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 352{ 353const char*packed_refs_file =files_packed_refs_path(refs); 354 355if(refs->packed && 356!stat_validity_check(&refs->packed->validity, packed_refs_file)) 357clear_packed_ref_cache(refs); 358 359if(!refs->packed) { 360FILE*f; 361 362 refs->packed =xcalloc(1,sizeof(*refs->packed)); 363acquire_packed_ref_cache(refs->packed); 364 refs->packed->cache =create_ref_cache(&refs->base, NULL); 365 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 366 f =fopen(packed_refs_file,"r"); 367if(f) { 368stat_validity_update(&refs->packed->validity,fileno(f)); 369read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 370fclose(f); 371} 372} 373return refs->packed; 374} 375 376static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 377{ 378returnget_ref_dir(packed_ref_cache->cache->root); 379} 380 381static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 382{ 383returnget_packed_ref_dir(get_packed_ref_cache(refs)); 384} 385 386/* 387 * Add a reference to the in-memory packed reference cache. This may 388 * only be called while the packed-refs file is locked (see 389 * lock_packed_refs()). To actually write the packed-refs file, call 390 * commit_packed_refs(). 391 */ 392static voidadd_packed_ref(struct files_ref_store *refs, 393const char*refname,const struct object_id *oid) 394{ 395struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 396 397if(!refs->packed_refs_lock) 398die("BUG: packed refs not locked"); 399add_ref_entry(get_packed_ref_dir(packed_ref_cache), 400create_ref_entry(refname, oid, REF_ISPACKED,1)); 401} 402 403/* 404 * Read the loose references from the namespace dirname into dir 405 * (without recursing). dirname must end with '/'. dir must be the 406 * directory entry corresponding to dirname. 407 */ 408static voidloose_fill_ref_dir(struct ref_store *ref_store, 409struct ref_dir *dir,const char*dirname) 410{ 411struct files_ref_store *refs = 412files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 413DIR*d; 414struct dirent *de; 415int dirnamelen =strlen(dirname); 416struct strbuf refname; 417struct strbuf path = STRBUF_INIT; 418size_t path_baselen; 419 420files_ref_path(refs, &path, dirname); 421 path_baselen = path.len; 422 423 d =opendir(path.buf); 424if(!d) { 425strbuf_release(&path); 426return; 427} 428 429strbuf_init(&refname, dirnamelen +257); 430strbuf_add(&refname, dirname, dirnamelen); 431 432while((de =readdir(d)) != NULL) { 433struct object_id oid; 434struct stat st; 435int flag; 436 437if(de->d_name[0] =='.') 438continue; 439if(ends_with(de->d_name,".lock")) 440continue; 441strbuf_addstr(&refname, de->d_name); 442strbuf_addstr(&path, de->d_name); 443if(stat(path.buf, &st) <0) { 444;/* silently ignore */ 445}else if(S_ISDIR(st.st_mode)) { 446strbuf_addch(&refname,'/'); 447add_entry_to_dir(dir, 448create_dir_entry(dir->cache, refname.buf, 449 refname.len,1)); 450}else{ 451if(!refs_resolve_ref_unsafe(&refs->base, 452 refname.buf, 453 RESOLVE_REF_READING, 454 oid.hash, &flag)) { 455oidclr(&oid); 456 flag |= REF_ISBROKEN; 457}else if(is_null_oid(&oid)) { 458/* 459 * It is so astronomically unlikely 460 * that NULL_SHA1 is the SHA-1 of an 461 * actual object that we consider its 462 * appearance in a loose reference 463 * file to be repo corruption 464 * (probably due to a software bug). 465 */ 466 flag |= REF_ISBROKEN; 467} 468 469if(check_refname_format(refname.buf, 470 REFNAME_ALLOW_ONELEVEL)) { 471if(!refname_is_safe(refname.buf)) 472die("loose refname is dangerous:%s", refname.buf); 473oidclr(&oid); 474 flag |= REF_BAD_NAME | REF_ISBROKEN; 475} 476add_entry_to_dir(dir, 477create_ref_entry(refname.buf, &oid, flag,0)); 478} 479strbuf_setlen(&refname, dirnamelen); 480strbuf_setlen(&path, path_baselen); 481} 482strbuf_release(&refname); 483strbuf_release(&path); 484closedir(d); 485 486/* 487 * Manually add refs/bisect, which, being per-worktree, might 488 * not appear in the directory listing for refs/ in the main 489 * repo. 490 */ 491if(!strcmp(dirname,"refs/")) { 492int pos =search_ref_dir(dir,"refs/bisect/",12); 493 494if(pos <0) { 495struct ref_entry *child_entry =create_dir_entry( 496 dir->cache,"refs/bisect/",12,1); 497add_entry_to_dir(dir, child_entry); 498} 499} 500} 501 502static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 503{ 504if(!refs->loose) { 505/* 506 * Mark the top-level directory complete because we 507 * are about to read the only subdirectory that can 508 * hold references: 509 */ 510 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 511 512/* We're going to fill the top level ourselves: */ 513 refs->loose->root->flag &= ~REF_INCOMPLETE; 514 515/* 516 * Add an incomplete entry for "refs/" (to be filled 517 * lazily): 518 */ 519add_entry_to_dir(get_ref_dir(refs->loose->root), 520create_dir_entry(refs->loose,"refs/",5,1)); 521} 522return refs->loose; 523} 524 525/* 526 * Return the ref_entry for the given refname from the packed 527 * references. If it does not exist, return NULL. 528 */ 529static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 530const char*refname) 531{ 532returnfind_ref_entry(get_packed_refs(refs), refname); 533} 534 535/* 536 * A loose ref file doesn't exist; check for a packed ref. 537 */ 538static intresolve_packed_ref(struct files_ref_store *refs, 539const char*refname, 540unsigned char*sha1,unsigned int*flags) 541{ 542struct ref_entry *entry; 543 544/* 545 * The loose reference file does not exist; check for a packed 546 * reference. 547 */ 548 entry =get_packed_ref(refs, refname); 549if(entry) { 550hashcpy(sha1, entry->u.value.oid.hash); 551*flags |= REF_ISPACKED; 552return0; 553} 554/* refname is not a packed reference. */ 555return-1; 556} 557 558static intfiles_read_raw_ref(struct ref_store *ref_store, 559const char*refname,unsigned char*sha1, 560struct strbuf *referent,unsigned int*type) 561{ 562struct files_ref_store *refs = 563files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 564struct strbuf sb_contents = STRBUF_INIT; 565struct strbuf sb_path = STRBUF_INIT; 566const char*path; 567const char*buf; 568struct stat st; 569int fd; 570int ret = -1; 571int save_errno; 572int remaining_retries =3; 573 574*type =0; 575strbuf_reset(&sb_path); 576 577files_ref_path(refs, &sb_path, refname); 578 579 path = sb_path.buf; 580 581stat_ref: 582/* 583 * We might have to loop back here to avoid a race 584 * condition: first we lstat() the file, then we try 585 * to read it as a link or as a file. But if somebody 586 * changes the type of the file (file <-> directory 587 * <-> symlink) between the lstat() and reading, then 588 * we don't want to report that as an error but rather 589 * try again starting with the lstat(). 590 * 591 * We'll keep a count of the retries, though, just to avoid 592 * any confusing situation sending us into an infinite loop. 593 */ 594 595if(remaining_retries-- <=0) 596goto out; 597 598if(lstat(path, &st) <0) { 599if(errno != ENOENT) 600goto out; 601if(resolve_packed_ref(refs, refname, sha1, type)) { 602 errno = ENOENT; 603goto out; 604} 605 ret =0; 606goto out; 607} 608 609/* Follow "normalized" - ie "refs/.." symlinks by hand */ 610if(S_ISLNK(st.st_mode)) { 611strbuf_reset(&sb_contents); 612if(strbuf_readlink(&sb_contents, path,0) <0) { 613if(errno == ENOENT || errno == EINVAL) 614/* inconsistent with lstat; retry */ 615goto stat_ref; 616else 617goto out; 618} 619if(starts_with(sb_contents.buf,"refs/") && 620!check_refname_format(sb_contents.buf,0)) { 621strbuf_swap(&sb_contents, referent); 622*type |= REF_ISSYMREF; 623 ret =0; 624goto out; 625} 626/* 627 * It doesn't look like a refname; fall through to just 628 * treating it like a non-symlink, and reading whatever it 629 * points to. 630 */ 631} 632 633/* Is it a directory? */ 634if(S_ISDIR(st.st_mode)) { 635/* 636 * Even though there is a directory where the loose 637 * ref is supposed to be, there could still be a 638 * packed ref: 639 */ 640if(resolve_packed_ref(refs, refname, sha1, type)) { 641 errno = EISDIR; 642goto out; 643} 644 ret =0; 645goto out; 646} 647 648/* 649 * Anything else, just open it and try to use it as 650 * a ref 651 */ 652 fd =open(path, O_RDONLY); 653if(fd <0) { 654if(errno == ENOENT && !S_ISLNK(st.st_mode)) 655/* inconsistent with lstat; retry */ 656goto stat_ref; 657else 658goto out; 659} 660strbuf_reset(&sb_contents); 661if(strbuf_read(&sb_contents, fd,256) <0) { 662int save_errno = errno; 663close(fd); 664 errno = save_errno; 665goto out; 666} 667close(fd); 668strbuf_rtrim(&sb_contents); 669 buf = sb_contents.buf; 670if(starts_with(buf,"ref:")) { 671 buf +=4; 672while(isspace(*buf)) 673 buf++; 674 675strbuf_reset(referent); 676strbuf_addstr(referent, buf); 677*type |= REF_ISSYMREF; 678 ret =0; 679goto out; 680} 681 682/* 683 * Please note that FETCH_HEAD has additional 684 * data after the sha. 685 */ 686if(get_sha1_hex(buf, sha1) || 687(buf[40] !='\0'&& !isspace(buf[40]))) { 688*type |= REF_ISBROKEN; 689 errno = EINVAL; 690goto out; 691} 692 693 ret =0; 694 695out: 696 save_errno = errno; 697strbuf_release(&sb_path); 698strbuf_release(&sb_contents); 699 errno = save_errno; 700return ret; 701} 702 703static voidunlock_ref(struct ref_lock *lock) 704{ 705/* Do not free lock->lk -- atexit() still looks at them */ 706if(lock->lk) 707rollback_lock_file(lock->lk); 708free(lock->ref_name); 709free(lock); 710} 711 712/* 713 * Lock refname, without following symrefs, and set *lock_p to point 714 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 715 * and type similarly to read_raw_ref(). 716 * 717 * The caller must verify that refname is a "safe" reference name (in 718 * the sense of refname_is_safe()) before calling this function. 719 * 720 * If the reference doesn't already exist, verify that refname doesn't 721 * have a D/F conflict with any existing references. extras and skip 722 * are passed to refs_verify_refname_available() for this check. 723 * 724 * If mustexist is not set and the reference is not found or is 725 * broken, lock the reference anyway but clear sha1. 726 * 727 * Return 0 on success. On failure, write an error message to err and 728 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 729 * 730 * Implementation note: This function is basically 731 * 732 * lock reference 733 * read_raw_ref() 734 * 735 * but it includes a lot more code to 736 * - Deal with possible races with other processes 737 * - Avoid calling refs_verify_refname_available() when it can be 738 * avoided, namely if we were successfully able to read the ref 739 * - Generate informative error messages in the case of failure 740 */ 741static intlock_raw_ref(struct files_ref_store *refs, 742const char*refname,int mustexist, 743const struct string_list *extras, 744const struct string_list *skip, 745struct ref_lock **lock_p, 746struct strbuf *referent, 747unsigned int*type, 748struct strbuf *err) 749{ 750struct ref_lock *lock; 751struct strbuf ref_file = STRBUF_INIT; 752int attempts_remaining =3; 753int ret = TRANSACTION_GENERIC_ERROR; 754 755assert(err); 756files_assert_main_repository(refs,"lock_raw_ref"); 757 758*type =0; 759 760/* First lock the file so it can't change out from under us. */ 761 762*lock_p = lock =xcalloc(1,sizeof(*lock)); 763 764 lock->ref_name =xstrdup(refname); 765files_ref_path(refs, &ref_file, refname); 766 767retry: 768switch(safe_create_leading_directories(ref_file.buf)) { 769case SCLD_OK: 770break;/* success */ 771case SCLD_EXISTS: 772/* 773 * Suppose refname is "refs/foo/bar". We just failed 774 * to create the containing directory, "refs/foo", 775 * because there was a non-directory in the way. This 776 * indicates a D/F conflict, probably because of 777 * another reference such as "refs/foo". There is no 778 * reason to expect this error to be transitory. 779 */ 780if(refs_verify_refname_available(&refs->base, refname, 781 extras, skip, err)) { 782if(mustexist) { 783/* 784 * To the user the relevant error is 785 * that the "mustexist" reference is 786 * missing: 787 */ 788strbuf_reset(err); 789strbuf_addf(err,"unable to resolve reference '%s'", 790 refname); 791}else{ 792/* 793 * The error message set by 794 * refs_verify_refname_available() is 795 * OK. 796 */ 797 ret = TRANSACTION_NAME_CONFLICT; 798} 799}else{ 800/* 801 * The file that is in the way isn't a loose 802 * reference. Report it as a low-level 803 * failure. 804 */ 805strbuf_addf(err,"unable to create lock file%s.lock; " 806"non-directory in the way", 807 ref_file.buf); 808} 809goto error_return; 810case SCLD_VANISHED: 811/* Maybe another process was tidying up. Try again. */ 812if(--attempts_remaining >0) 813goto retry; 814/* fall through */ 815default: 816strbuf_addf(err,"unable to create directory for%s", 817 ref_file.buf); 818goto error_return; 819} 820 821if(!lock->lk) 822 lock->lk =xcalloc(1,sizeof(struct lock_file)); 823 824if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 825if(errno == ENOENT && --attempts_remaining >0) { 826/* 827 * Maybe somebody just deleted one of the 828 * directories leading to ref_file. Try 829 * again: 830 */ 831goto retry; 832}else{ 833unable_to_lock_message(ref_file.buf, errno, err); 834goto error_return; 835} 836} 837 838/* 839 * Now we hold the lock and can read the reference without 840 * fear that its value will change. 841 */ 842 843if(files_read_raw_ref(&refs->base, refname, 844 lock->old_oid.hash, referent, type)) { 845if(errno == ENOENT) { 846if(mustexist) { 847/* Garden variety missing reference. */ 848strbuf_addf(err,"unable to resolve reference '%s'", 849 refname); 850goto error_return; 851}else{ 852/* 853 * Reference is missing, but that's OK. We 854 * know that there is not a conflict with 855 * another loose reference because 856 * (supposing that we are trying to lock 857 * reference "refs/foo/bar"): 858 * 859 * - We were successfully able to create 860 * the lockfile refs/foo/bar.lock, so we 861 * know there cannot be a loose reference 862 * named "refs/foo". 863 * 864 * - We got ENOENT and not EISDIR, so we 865 * know that there cannot be a loose 866 * reference named "refs/foo/bar/baz". 867 */ 868} 869}else if(errno == EISDIR) { 870/* 871 * There is a directory in the way. It might have 872 * contained references that have been deleted. If 873 * we don't require that the reference already 874 * exists, try to remove the directory so that it 875 * doesn't cause trouble when we want to rename the 876 * lockfile into place later. 877 */ 878if(mustexist) { 879/* Garden variety missing reference. */ 880strbuf_addf(err,"unable to resolve reference '%s'", 881 refname); 882goto error_return; 883}else if(remove_dir_recursively(&ref_file, 884 REMOVE_DIR_EMPTY_ONLY)) { 885if(refs_verify_refname_available( 886&refs->base, refname, 887 extras, skip, err)) { 888/* 889 * The error message set by 890 * verify_refname_available() is OK. 891 */ 892 ret = TRANSACTION_NAME_CONFLICT; 893goto error_return; 894}else{ 895/* 896 * We can't delete the directory, 897 * but we also don't know of any 898 * references that it should 899 * contain. 900 */ 901strbuf_addf(err,"there is a non-empty directory '%s' " 902"blocking reference '%s'", 903 ref_file.buf, refname); 904goto error_return; 905} 906} 907}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 908strbuf_addf(err,"unable to resolve reference '%s': " 909"reference broken", refname); 910goto error_return; 911}else{ 912strbuf_addf(err,"unable to resolve reference '%s':%s", 913 refname,strerror(errno)); 914goto error_return; 915} 916 917/* 918 * If the ref did not exist and we are creating it, 919 * make sure there is no existing ref that conflicts 920 * with refname: 921 */ 922if(refs_verify_refname_available( 923&refs->base, refname, 924 extras, skip, err)) 925goto error_return; 926} 927 928 ret =0; 929goto out; 930 931error_return: 932unlock_ref(lock); 933*lock_p = NULL; 934 935out: 936strbuf_release(&ref_file); 937return ret; 938} 939 940static intfiles_peel_ref(struct ref_store *ref_store, 941const char*refname,unsigned char*sha1) 942{ 943struct files_ref_store *refs = 944files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 945"peel_ref"); 946int flag; 947unsigned char base[20]; 948 949if(current_ref_iter && current_ref_iter->refname == refname) { 950struct object_id peeled; 951 952if(ref_iterator_peel(current_ref_iter, &peeled)) 953return-1; 954hashcpy(sha1, peeled.hash); 955return0; 956} 957 958if(refs_read_ref_full(ref_store, refname, 959 RESOLVE_REF_READING, base, &flag)) 960return-1; 961 962/* 963 * If the reference is packed, read its ref_entry from the 964 * cache in the hope that we already know its peeled value. 965 * We only try this optimization on packed references because 966 * (a) forcing the filling of the loose reference cache could 967 * be expensive and (b) loose references anyway usually do not 968 * have REF_KNOWS_PEELED. 969 */ 970if(flag & REF_ISPACKED) { 971struct ref_entry *r =get_packed_ref(refs, refname); 972if(r) { 973if(peel_entry(r,0)) 974return-1; 975hashcpy(sha1, r->u.value.peeled.hash); 976return0; 977} 978} 979 980returnpeel_object(base, sha1); 981} 982 983struct files_ref_iterator { 984struct ref_iterator base; 985 986struct packed_ref_cache *packed_ref_cache; 987struct ref_iterator *iter0; 988unsigned int flags; 989}; 990 991static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 992{ 993struct files_ref_iterator *iter = 994(struct files_ref_iterator *)ref_iterator; 995int ok; 996 997while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 998if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 999ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1000continue;10011002if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1003!ref_resolves_to_object(iter->iter0->refname,1004 iter->iter0->oid,1005 iter->iter0->flags))1006continue;10071008 iter->base.refname = iter->iter0->refname;1009 iter->base.oid = iter->iter0->oid;1010 iter->base.flags = iter->iter0->flags;1011return ITER_OK;1012}10131014 iter->iter0 = NULL;1015if(ref_iterator_abort(ref_iterator) != ITER_DONE)1016 ok = ITER_ERROR;10171018return ok;1019}10201021static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1022struct object_id *peeled)1023{1024struct files_ref_iterator *iter =1025(struct files_ref_iterator *)ref_iterator;10261027returnref_iterator_peel(iter->iter0, peeled);1028}10291030static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1031{1032struct files_ref_iterator *iter =1033(struct files_ref_iterator *)ref_iterator;1034int ok = ITER_DONE;10351036if(iter->iter0)1037 ok =ref_iterator_abort(iter->iter0);10381039release_packed_ref_cache(iter->packed_ref_cache);1040base_ref_iterator_free(ref_iterator);1041return ok;1042}10431044static struct ref_iterator_vtable files_ref_iterator_vtable = {1045 files_ref_iterator_advance,1046 files_ref_iterator_peel,1047 files_ref_iterator_abort1048};10491050static struct ref_iterator *files_ref_iterator_begin(1051struct ref_store *ref_store,1052const char*prefix,unsigned int flags)1053{1054struct files_ref_store *refs;1055struct ref_iterator *loose_iter, *packed_iter;1056struct files_ref_iterator *iter;1057struct ref_iterator *ref_iterator;10581059if(ref_paranoia <0)1060 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1061if(ref_paranoia)1062 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10631064 refs =files_downcast(ref_store,1065 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1066"ref_iterator_begin");10671068 iter =xcalloc(1,sizeof(*iter));1069 ref_iterator = &iter->base;1070base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10711072/*1073 * We must make sure that all loose refs are read before1074 * accessing the packed-refs file; this avoids a race1075 * condition if loose refs are migrated to the packed-refs1076 * file by a simultaneous process, but our in-memory view is1077 * from before the migration. We ensure this as follows:1078 * First, we call start the loose refs iteration with its1079 * `prime_ref` argument set to true. This causes the loose1080 * references in the subtree to be pre-read into the cache.1081 * (If they've already been read, that's OK; we only need to1082 * guarantee that they're read before the packed refs, not1083 * *how much* before.) After that, we call1084 * get_packed_ref_cache(), which internally checks whether the1085 * packed-ref cache is up to date with what is on disk, and1086 * re-reads it if not.1087 */10881089 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1090 prefix,1);10911092 iter->packed_ref_cache =get_packed_ref_cache(refs);1093acquire_packed_ref_cache(iter->packed_ref_cache);1094 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1095 prefix,0);10961097 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1098 iter->flags = flags;10991100return ref_iterator;1101}11021103/*1104 * Verify that the reference locked by lock has the value old_sha1.1105 * Fail if the reference doesn't exist and mustexist is set. Return 01106 * on success. On error, write an error message to err, set errno, and1107 * return a negative value.1108 */1109static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1110const unsigned char*old_sha1,int mustexist,1111struct strbuf *err)1112{1113assert(err);11141115if(refs_read_ref_full(ref_store, lock->ref_name,1116 mustexist ? RESOLVE_REF_READING :0,1117 lock->old_oid.hash, NULL)) {1118if(old_sha1) {1119int save_errno = errno;1120strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1121 errno = save_errno;1122return-1;1123}else{1124oidclr(&lock->old_oid);1125return0;1126}1127}1128if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1129strbuf_addf(err,"ref '%s' is at%sbut expected%s",1130 lock->ref_name,1131oid_to_hex(&lock->old_oid),1132sha1_to_hex(old_sha1));1133 errno = EBUSY;1134return-1;1135}1136return0;1137}11381139static intremove_empty_directories(struct strbuf *path)1140{1141/*1142 * we want to create a file but there is a directory there;1143 * if that is an empty directory (or a directory that contains1144 * only empty directories), remove them.1145 */1146returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1147}11481149static intcreate_reflock(const char*path,void*cb)1150{1151struct lock_file *lk = cb;11521153returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1154}11551156/*1157 * Locks a ref returning the lock on success and NULL on failure.1158 * On failure errno is set to something meaningful.1159 */1160static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1161const char*refname,1162const unsigned char*old_sha1,1163const struct string_list *extras,1164const struct string_list *skip,1165unsigned int flags,int*type,1166struct strbuf *err)1167{1168struct strbuf ref_file = STRBUF_INIT;1169struct ref_lock *lock;1170int last_errno =0;1171int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1172int resolve_flags = RESOLVE_REF_NO_RECURSE;1173int resolved;11741175files_assert_main_repository(refs,"lock_ref_sha1_basic");1176assert(err);11771178 lock =xcalloc(1,sizeof(struct ref_lock));11791180if(mustexist)1181 resolve_flags |= RESOLVE_REF_READING;1182if(flags & REF_DELETING)1183 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11841185files_ref_path(refs, &ref_file, refname);1186 resolved = !!refs_resolve_ref_unsafe(&refs->base,1187 refname, resolve_flags,1188 lock->old_oid.hash, type);1189if(!resolved && errno == EISDIR) {1190/*1191 * we are trying to lock foo but we used to1192 * have foo/bar which now does not exist;1193 * it is normal for the empty directory 'foo'1194 * to remain.1195 */1196if(remove_empty_directories(&ref_file)) {1197 last_errno = errno;1198if(!refs_verify_refname_available(1199&refs->base,1200 refname, extras, skip, err))1201strbuf_addf(err,"there are still refs under '%s'",1202 refname);1203goto error_return;1204}1205 resolved = !!refs_resolve_ref_unsafe(&refs->base,1206 refname, resolve_flags,1207 lock->old_oid.hash, type);1208}1209if(!resolved) {1210 last_errno = errno;1211if(last_errno != ENOTDIR ||1212!refs_verify_refname_available(&refs->base, refname,1213 extras, skip, err))1214strbuf_addf(err,"unable to resolve reference '%s':%s",1215 refname,strerror(last_errno));12161217goto error_return;1218}12191220/*1221 * If the ref did not exist and we are creating it, make sure1222 * there is no existing packed ref whose name begins with our1223 * refname, nor a packed ref whose name is a proper prefix of1224 * our refname.1225 */1226if(is_null_oid(&lock->old_oid) &&1227refs_verify_refname_available(&refs->base, refname,1228 extras, skip, err)) {1229 last_errno = ENOTDIR;1230goto error_return;1231}12321233 lock->lk =xcalloc(1,sizeof(struct lock_file));12341235 lock->ref_name =xstrdup(refname);12361237if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1238 last_errno = errno;1239unable_to_lock_message(ref_file.buf, errno, err);1240goto error_return;1241}12421243if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1244 last_errno = errno;1245goto error_return;1246}1247goto out;12481249 error_return:1250unlock_ref(lock);1251 lock = NULL;12521253 out:1254strbuf_release(&ref_file);1255 errno = last_errno;1256return lock;1257}12581259/*1260 * Write an entry to the packed-refs file for the specified refname.1261 * If peeled is non-NULL, write it as the entry's peeled value.1262 */1263static voidwrite_packed_entry(FILE*fh,const char*refname,1264const unsigned char*sha1,1265const unsigned char*peeled)1266{1267fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1268if(peeled)1269fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1270}12711272/*1273 * Lock the packed-refs file for writing. Flags is passed to1274 * hold_lock_file_for_update(). Return 0 on success. On errors, set1275 * errno appropriately and return a nonzero value.1276 */1277static intlock_packed_refs(struct files_ref_store *refs,int flags)1278{1279static int timeout_configured =0;1280static int timeout_value =1000;1281struct packed_ref_cache *packed_ref_cache;12821283files_assert_main_repository(refs,"lock_packed_refs");12841285if(!timeout_configured) {1286git_config_get_int("core.packedrefstimeout", &timeout_value);1287 timeout_configured =1;1288}12891290if(hold_lock_file_for_update_timeout(1291&packlock,files_packed_refs_path(refs),1292 flags, timeout_value) <0)1293return-1;1294/*1295 * Get the current packed-refs while holding the lock. If the1296 * packed-refs file has been modified since we last read it,1297 * this will automatically invalidate the cache and re-read1298 * the packed-refs file.1299 */1300 packed_ref_cache =get_packed_ref_cache(refs);1301 refs->packed_refs_lock = &packlock;1302/* Increment the reference count to prevent it from being freed: */1303acquire_packed_ref_cache(packed_ref_cache);1304return0;1305}13061307/*1308 * Write the current version of the packed refs cache from memory to1309 * disk. The packed-refs file must already be locked for writing (see1310 * lock_packed_refs()). Return zero on success. On errors, set errno1311 * and return a nonzero value1312 */1313static intcommit_packed_refs(struct files_ref_store *refs)1314{1315struct packed_ref_cache *packed_ref_cache =1316get_packed_ref_cache(refs);1317int ok, error =0;1318int save_errno =0;1319FILE*out;1320struct ref_iterator *iter;13211322files_assert_main_repository(refs,"commit_packed_refs");13231324if(!refs->packed_refs_lock)1325die("BUG: packed-refs not locked");13261327 out =fdopen_lock_file(refs->packed_refs_lock,"w");1328if(!out)1329die_errno("unable to fdopen packed-refs descriptor");13301331fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13321333 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1334while((ok =ref_iterator_advance(iter)) == ITER_OK) {1335struct object_id peeled;1336int peel_error =ref_iterator_peel(iter, &peeled);13371338write_packed_entry(out, iter->refname, iter->oid->hash,1339 peel_error ? NULL : peeled.hash);1340}13411342if(ok != ITER_DONE)1343die("error while iterating over references");13441345if(commit_lock_file(refs->packed_refs_lock)) {1346 save_errno = errno;1347 error = -1;1348}1349 refs->packed_refs_lock = NULL;1350release_packed_ref_cache(packed_ref_cache);1351 errno = save_errno;1352return error;1353}13541355/*1356 * Rollback the lockfile for the packed-refs file, and discard the1357 * in-memory packed reference cache. (The packed-refs file will be1358 * read anew if it is needed again after this function is called.)1359 */1360static voidrollback_packed_refs(struct files_ref_store *refs)1361{1362struct packed_ref_cache *packed_ref_cache =1363get_packed_ref_cache(refs);13641365files_assert_main_repository(refs,"rollback_packed_refs");13661367if(!refs->packed_refs_lock)1368die("BUG: packed-refs not locked");1369rollback_lock_file(refs->packed_refs_lock);1370 refs->packed_refs_lock = NULL;1371release_packed_ref_cache(packed_ref_cache);1372clear_packed_ref_cache(refs);1373}13741375struct ref_to_prune {1376struct ref_to_prune *next;1377unsigned char sha1[20];1378char name[FLEX_ARRAY];1379};13801381enum{1382 REMOVE_EMPTY_PARENTS_REF =0x01,1383 REMOVE_EMPTY_PARENTS_REFLOG =0x021384};13851386/*1387 * Remove empty parent directories associated with the specified1388 * reference and/or its reflog, but spare [logs/]refs/ and immediate1389 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1390 * REMOVE_EMPTY_PARENTS_REFLOG.1391 */1392static voidtry_remove_empty_parents(struct files_ref_store *refs,1393const char*refname,1394unsigned int flags)1395{1396struct strbuf buf = STRBUF_INIT;1397struct strbuf sb = STRBUF_INIT;1398char*p, *q;1399int i;14001401strbuf_addstr(&buf, refname);1402 p = buf.buf;1403for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1404while(*p && *p !='/')1405 p++;1406/* tolerate duplicate slashes; see check_refname_format() */1407while(*p =='/')1408 p++;1409}1410 q = buf.buf + buf.len;1411while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1412while(q > p && *q !='/')1413 q--;1414while(q > p && *(q-1) =='/')1415 q--;1416if(q == p)1417break;1418strbuf_setlen(&buf, q - buf.buf);14191420strbuf_reset(&sb);1421files_ref_path(refs, &sb, buf.buf);1422if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1423 flags &= ~REMOVE_EMPTY_PARENTS_REF;14241425strbuf_reset(&sb);1426files_reflog_path(refs, &sb, buf.buf);1427if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1428 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1429}1430strbuf_release(&buf);1431strbuf_release(&sb);1432}14331434/* make sure nobody touched the ref, and unlink */1435static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1436{1437struct ref_transaction *transaction;1438struct strbuf err = STRBUF_INIT;14391440if(check_refname_format(r->name,0))1441return;14421443 transaction =ref_store_transaction_begin(&refs->base, &err);1444if(!transaction ||1445ref_transaction_delete(transaction, r->name, r->sha1,1446 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1447ref_transaction_commit(transaction, &err)) {1448ref_transaction_free(transaction);1449error("%s", err.buf);1450strbuf_release(&err);1451return;1452}1453ref_transaction_free(transaction);1454strbuf_release(&err);1455}14561457static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1458{1459while(r) {1460prune_ref(refs, r);1461 r = r->next;1462}1463}14641465static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1466{1467struct files_ref_store *refs =1468files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1469"pack_refs");1470struct ref_iterator *iter;1471struct ref_dir *packed_refs;1472int ok;1473struct ref_to_prune *refs_to_prune = NULL;14741475lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1476 packed_refs =get_packed_refs(refs);14771478 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1479while((ok =ref_iterator_advance(iter)) == ITER_OK) {1480/*1481 * If the loose reference can be packed, add an entry1482 * in the packed ref cache. If the reference should be1483 * pruned, also add it to refs_to_prune.1484 */1485struct ref_entry *packed_entry;1486int is_tag_ref =starts_with(iter->refname,"refs/tags/");14871488/* Do not pack per-worktree refs: */1489if(ref_type(iter->refname) != REF_TYPE_NORMAL)1490continue;14911492/* ALWAYS pack tags */1493if(!(flags & PACK_REFS_ALL) && !is_tag_ref)1494continue;14951496/* Do not pack symbolic or broken refs: */1497if(iter->flags & REF_ISSYMREF)1498continue;14991500if(!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))1501continue;15021503/*1504 * Create an entry in the packed-refs cache equivalent1505 * to the one from the loose ref cache, except that1506 * we don't copy the peeled status, because we want it1507 * to be re-peeled.1508 */1509 packed_entry =find_ref_entry(packed_refs, iter->refname);1510if(packed_entry) {1511/* Overwrite existing packed entry with info from loose entry */1512 packed_entry->flag = REF_ISPACKED;1513oidcpy(&packed_entry->u.value.oid, iter->oid);1514}else{1515 packed_entry =create_ref_entry(iter->refname, iter->oid,1516 REF_ISPACKED,0);1517add_ref_entry(packed_refs, packed_entry);1518}1519oidclr(&packed_entry->u.value.peeled);15201521/* Schedule the loose reference for pruning if requested. */1522if((flags & PACK_REFS_PRUNE)) {1523struct ref_to_prune *n;1524FLEX_ALLOC_STR(n, name, iter->refname);1525hashcpy(n->sha1, iter->oid->hash);1526 n->next = refs_to_prune;1527 refs_to_prune = n;1528}1529}1530if(ok != ITER_DONE)1531die("error while iterating over references");15321533if(commit_packed_refs(refs))1534die_errno("unable to overwrite old ref-pack file");15351536prune_refs(refs, refs_to_prune);1537return0;1538}15391540/*1541 * Rewrite the packed-refs file, omitting any refs listed in1542 * 'refnames'. On error, leave packed-refs unchanged, write an error1543 * message to 'err', and return a nonzero value.1544 *1545 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1546 */1547static intrepack_without_refs(struct files_ref_store *refs,1548struct string_list *refnames,struct strbuf *err)1549{1550struct ref_dir *packed;1551struct string_list_item *refname;1552int ret, needs_repacking =0, removed =0;15531554files_assert_main_repository(refs,"repack_without_refs");1555assert(err);15561557/* Look for a packed ref */1558for_each_string_list_item(refname, refnames) {1559if(get_packed_ref(refs, refname->string)) {1560 needs_repacking =1;1561break;1562}1563}15641565/* Avoid locking if we have nothing to do */1566if(!needs_repacking)1567return0;/* no refname exists in packed refs */15681569if(lock_packed_refs(refs,0)) {1570unable_to_lock_message(files_packed_refs_path(refs), errno, err);1571return-1;1572}1573 packed =get_packed_refs(refs);15741575/* Remove refnames from the cache */1576for_each_string_list_item(refname, refnames)1577if(remove_entry_from_dir(packed, refname->string) != -1)1578 removed =1;1579if(!removed) {1580/*1581 * All packed entries disappeared while we were1582 * acquiring the lock.1583 */1584rollback_packed_refs(refs);1585return0;1586}15871588/* Write what remains */1589 ret =commit_packed_refs(refs);1590if(ret)1591strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1592strerror(errno));1593return ret;1594}15951596static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1597struct string_list *refnames,unsigned int flags)1598{1599struct files_ref_store *refs =1600files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1601struct strbuf err = STRBUF_INIT;1602int i, result =0;16031604if(!refnames->nr)1605return0;16061607 result =repack_without_refs(refs, refnames, &err);1608if(result) {1609/*1610 * If we failed to rewrite the packed-refs file, then1611 * it is unsafe to try to remove loose refs, because1612 * doing so might expose an obsolete packed value for1613 * a reference that might even point at an object that1614 * has been garbage collected.1615 */1616if(refnames->nr ==1)1617error(_("could not delete reference%s:%s"),1618 refnames->items[0].string, err.buf);1619else1620error(_("could not delete references:%s"), err.buf);16211622goto out;1623}16241625for(i =0; i < refnames->nr; i++) {1626const char*refname = refnames->items[i].string;16271628if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1629 result |=error(_("could not remove reference%s"), refname);1630}16311632out:1633strbuf_release(&err);1634return result;1635}16361637/*1638 * People using contrib's git-new-workdir have .git/logs/refs ->1639 * /some/other/path/.git/logs/refs, and that may live on another device.1640 *1641 * IOW, to avoid cross device rename errors, the temporary renamed log must1642 * live into logs/refs.1643 */1644#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16451646struct rename_cb {1647const char*tmp_renamed_log;1648int true_errno;1649};16501651static intrename_tmp_log_callback(const char*path,void*cb_data)1652{1653struct rename_cb *cb = cb_data;16541655if(rename(cb->tmp_renamed_log, path)) {1656/*1657 * rename(a, b) when b is an existing directory ought1658 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1659 * Sheesh. Record the true errno for error reporting,1660 * but report EISDIR to raceproof_create_file() so1661 * that it knows to retry.1662 */1663 cb->true_errno = errno;1664if(errno == ENOTDIR)1665 errno = EISDIR;1666return-1;1667}else{1668return0;1669}1670}16711672static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1673{1674struct strbuf path = STRBUF_INIT;1675struct strbuf tmp = STRBUF_INIT;1676struct rename_cb cb;1677int ret;16781679files_reflog_path(refs, &path, newrefname);1680files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1681 cb.tmp_renamed_log = tmp.buf;1682 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1683if(ret) {1684if(errno == EISDIR)1685error("directory not empty:%s", path.buf);1686else1687error("unable to move logfile%sto%s:%s",1688 tmp.buf, path.buf,1689strerror(cb.true_errno));1690}16911692strbuf_release(&path);1693strbuf_release(&tmp);1694return ret;1695}16961697static intwrite_ref_to_lockfile(struct ref_lock *lock,1698const struct object_id *oid,struct strbuf *err);1699static intcommit_ref_update(struct files_ref_store *refs,1700struct ref_lock *lock,1701const struct object_id *oid,const char*logmsg,1702struct strbuf *err);17031704static intfiles_rename_ref(struct ref_store *ref_store,1705const char*oldrefname,const char*newrefname,1706const char*logmsg)1707{1708struct files_ref_store *refs =1709files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1710struct object_id oid, orig_oid;1711int flag =0, logmoved =0;1712struct ref_lock *lock;1713struct stat loginfo;1714struct strbuf sb_oldref = STRBUF_INIT;1715struct strbuf sb_newref = STRBUF_INIT;1716struct strbuf tmp_renamed_log = STRBUF_INIT;1717int log, ret;1718struct strbuf err = STRBUF_INIT;17191720files_reflog_path(refs, &sb_oldref, oldrefname);1721files_reflog_path(refs, &sb_newref, newrefname);1722files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17231724 log = !lstat(sb_oldref.buf, &loginfo);1725if(log &&S_ISLNK(loginfo.st_mode)) {1726 ret =error("reflog for%sis a symlink", oldrefname);1727goto out;1728}17291730if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1731 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1732 orig_oid.hash, &flag)) {1733 ret =error("refname%snot found", oldrefname);1734goto out;1735}17361737if(flag & REF_ISSYMREF) {1738 ret =error("refname%sis a symbolic ref, renaming it is not supported",1739 oldrefname);1740goto out;1741}1742if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1743 ret =1;1744goto out;1745}17461747if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1748 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1749 oldrefname,strerror(errno));1750goto out;1751}17521753if(refs_delete_ref(&refs->base, logmsg, oldrefname,1754 orig_oid.hash, REF_NODEREF)) {1755error("unable to delete old%s", oldrefname);1756goto rollback;1757}17581759/*1760 * Since we are doing a shallow lookup, oid is not the1761 * correct value to pass to delete_ref as old_oid. But that1762 * doesn't matter, because an old_oid check wouldn't add to1763 * the safety anyway; we want to delete the reference whatever1764 * its current value.1765 */1766if(!refs_read_ref_full(&refs->base, newrefname,1767 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1768 oid.hash, NULL) &&1769refs_delete_ref(&refs->base, NULL, newrefname,1770 NULL, REF_NODEREF)) {1771if(errno == EISDIR) {1772struct strbuf path = STRBUF_INIT;1773int result;17741775files_ref_path(refs, &path, newrefname);1776 result =remove_empty_directories(&path);1777strbuf_release(&path);17781779if(result) {1780error("Directory not empty:%s", newrefname);1781goto rollback;1782}1783}else{1784error("unable to delete existing%s", newrefname);1785goto rollback;1786}1787}17881789if(log &&rename_tmp_log(refs, newrefname))1790goto rollback;17911792 logmoved = log;17931794 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1795 REF_NODEREF, NULL, &err);1796if(!lock) {1797error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1798strbuf_release(&err);1799goto rollback;1800}1801oidcpy(&lock->old_oid, &orig_oid);18021803if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1804commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1805error("unable to write current sha1 into%s:%s", newrefname, err.buf);1806strbuf_release(&err);1807goto rollback;1808}18091810 ret =0;1811goto out;18121813 rollback:1814 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1815 REF_NODEREF, NULL, &err);1816if(!lock) {1817error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1818strbuf_release(&err);1819goto rollbacklog;1820}18211822 flag = log_all_ref_updates;1823 log_all_ref_updates = LOG_REFS_NONE;1824if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1825commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1826error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1827strbuf_release(&err);1828}1829 log_all_ref_updates = flag;18301831 rollbacklog:1832if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1833error("unable to restore logfile%sfrom%s:%s",1834 oldrefname, newrefname,strerror(errno));1835if(!logmoved && log &&1836rename(tmp_renamed_log.buf, sb_oldref.buf))1837error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1838 oldrefname,strerror(errno));1839 ret =1;1840 out:1841strbuf_release(&sb_newref);1842strbuf_release(&sb_oldref);1843strbuf_release(&tmp_renamed_log);18441845return ret;1846}18471848static intclose_ref(struct ref_lock *lock)1849{1850if(close_lock_file(lock->lk))1851return-1;1852return0;1853}18541855static intcommit_ref(struct ref_lock *lock)1856{1857char*path =get_locked_file_path(lock->lk);1858struct stat st;18591860if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1861/*1862 * There is a directory at the path we want to rename1863 * the lockfile to. Hopefully it is empty; try to1864 * delete it.1865 */1866size_t len =strlen(path);1867struct strbuf sb_path = STRBUF_INIT;18681869strbuf_attach(&sb_path, path, len, len);18701871/*1872 * If this fails, commit_lock_file() will also fail1873 * and will report the problem.1874 */1875remove_empty_directories(&sb_path);1876strbuf_release(&sb_path);1877}else{1878free(path);1879}18801881if(commit_lock_file(lock->lk))1882return-1;1883return0;1884}18851886static intopen_or_create_logfile(const char*path,void*cb)1887{1888int*fd = cb;18891890*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1891return(*fd <0) ? -1:0;1892}18931894/*1895 * Create a reflog for a ref. If force_create = 0, only create the1896 * reflog for certain refs (those for which should_autocreate_reflog1897 * returns non-zero). Otherwise, create it regardless of the reference1898 * name. If the logfile already existed or was created, return 0 and1899 * set *logfd to the file descriptor opened for appending to the file.1900 * If no logfile exists and we decided not to create one, return 0 and1901 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1902 * return -1.1903 */1904static intlog_ref_setup(struct files_ref_store *refs,1905const char*refname,int force_create,1906int*logfd,struct strbuf *err)1907{1908struct strbuf logfile_sb = STRBUF_INIT;1909char*logfile;19101911files_reflog_path(refs, &logfile_sb, refname);1912 logfile =strbuf_detach(&logfile_sb, NULL);19131914if(force_create ||should_autocreate_reflog(refname)) {1915if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1916if(errno == ENOENT)1917strbuf_addf(err,"unable to create directory for '%s': "1918"%s", logfile,strerror(errno));1919else if(errno == EISDIR)1920strbuf_addf(err,"there are still logs under '%s'",1921 logfile);1922else1923strbuf_addf(err,"unable to append to '%s':%s",1924 logfile,strerror(errno));19251926goto error;1927}1928}else{1929*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1930if(*logfd <0) {1931if(errno == ENOENT || errno == EISDIR) {1932/*1933 * The logfile doesn't already exist,1934 * but that is not an error; it only1935 * means that we won't write log1936 * entries to it.1937 */1938;1939}else{1940strbuf_addf(err,"unable to append to '%s':%s",1941 logfile,strerror(errno));1942goto error;1943}1944}1945}19461947if(*logfd >=0)1948adjust_shared_perm(logfile);19491950free(logfile);1951return0;19521953error:1954free(logfile);1955return-1;1956}19571958static intfiles_create_reflog(struct ref_store *ref_store,1959const char*refname,int force_create,1960struct strbuf *err)1961{1962struct files_ref_store *refs =1963files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1964int fd;19651966if(log_ref_setup(refs, refname, force_create, &fd, err))1967return-1;19681969if(fd >=0)1970close(fd);19711972return0;1973}19741975static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1976const struct object_id *new_oid,1977const char*committer,const char*msg)1978{1979int msglen, written;1980unsigned maxlen, len;1981char*logrec;19821983 msglen = msg ?strlen(msg) :0;1984 maxlen =strlen(committer) + msglen +100;1985 logrec =xmalloc(maxlen);1986 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1987oid_to_hex(old_oid),1988oid_to_hex(new_oid),1989 committer);1990if(msglen)1991 len +=copy_reflog_msg(logrec + len -1, msg) -1;19921993 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1994free(logrec);1995if(written != len)1996return-1;19971998return0;1999}20002001static intfiles_log_ref_write(struct files_ref_store *refs,2002const char*refname,const struct object_id *old_oid,2003const struct object_id *new_oid,const char*msg,2004int flags,struct strbuf *err)2005{2006int logfd, result;20072008if(log_all_ref_updates == LOG_REFS_UNSET)2009 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20102011 result =log_ref_setup(refs, refname,2012 flags & REF_FORCE_CREATE_REFLOG,2013&logfd, err);20142015if(result)2016return result;20172018if(logfd <0)2019return0;2020 result =log_ref_write_fd(logfd, old_oid, new_oid,2021git_committer_info(0), msg);2022if(result) {2023struct strbuf sb = STRBUF_INIT;2024int save_errno = errno;20252026files_reflog_path(refs, &sb, refname);2027strbuf_addf(err,"unable to append to '%s':%s",2028 sb.buf,strerror(save_errno));2029strbuf_release(&sb);2030close(logfd);2031return-1;2032}2033if(close(logfd)) {2034struct strbuf sb = STRBUF_INIT;2035int save_errno = errno;20362037files_reflog_path(refs, &sb, refname);2038strbuf_addf(err,"unable to append to '%s':%s",2039 sb.buf,strerror(save_errno));2040strbuf_release(&sb);2041return-1;2042}2043return0;2044}20452046/*2047 * Write sha1 into the open lockfile, then close the lockfile. On2048 * errors, rollback the lockfile, fill in *err and2049 * return -1.2050 */2051static intwrite_ref_to_lockfile(struct ref_lock *lock,2052const struct object_id *oid,struct strbuf *err)2053{2054static char term ='\n';2055struct object *o;2056int fd;20572058 o =parse_object(oid);2059if(!o) {2060strbuf_addf(err,2061"trying to write ref '%s' with nonexistent object%s",2062 lock->ref_name,oid_to_hex(oid));2063unlock_ref(lock);2064return-1;2065}2066if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2067strbuf_addf(err,2068"trying to write non-commit object%sto branch '%s'",2069oid_to_hex(oid), lock->ref_name);2070unlock_ref(lock);2071return-1;2072}2073 fd =get_lock_file_fd(lock->lk);2074if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2075write_in_full(fd, &term,1) !=1||2076close_ref(lock) <0) {2077strbuf_addf(err,2078"couldn't write '%s'",get_lock_file_path(lock->lk));2079unlock_ref(lock);2080return-1;2081}2082return0;2083}20842085/*2086 * Commit a change to a loose reference that has already been written2087 * to the loose reference lockfile. Also update the reflogs if2088 * necessary, using the specified lockmsg (which can be NULL).2089 */2090static intcommit_ref_update(struct files_ref_store *refs,2091struct ref_lock *lock,2092const struct object_id *oid,const char*logmsg,2093struct strbuf *err)2094{2095files_assert_main_repository(refs,"commit_ref_update");20962097clear_loose_ref_cache(refs);2098if(files_log_ref_write(refs, lock->ref_name,2099&lock->old_oid, oid,2100 logmsg,0, err)) {2101char*old_msg =strbuf_detach(err, NULL);2102strbuf_addf(err,"cannot update the ref '%s':%s",2103 lock->ref_name, old_msg);2104free(old_msg);2105unlock_ref(lock);2106return-1;2107}21082109if(strcmp(lock->ref_name,"HEAD") !=0) {2110/*2111 * Special hack: If a branch is updated directly and HEAD2112 * points to it (may happen on the remote side of a push2113 * for example) then logically the HEAD reflog should be2114 * updated too.2115 * A generic solution implies reverse symref information,2116 * but finding all symrefs pointing to the given branch2117 * would be rather costly for this rare event (the direct2118 * update of a branch) to be worth it. So let's cheat and2119 * check with HEAD only which should cover 99% of all usage2120 * scenarios (even 100% of the default ones).2121 */2122struct object_id head_oid;2123int head_flag;2124const char*head_ref;21252126 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2127 RESOLVE_REF_READING,2128 head_oid.hash, &head_flag);2129if(head_ref && (head_flag & REF_ISSYMREF) &&2130!strcmp(head_ref, lock->ref_name)) {2131struct strbuf log_err = STRBUF_INIT;2132if(files_log_ref_write(refs,"HEAD",2133&lock->old_oid, oid,2134 logmsg,0, &log_err)) {2135error("%s", log_err.buf);2136strbuf_release(&log_err);2137}2138}2139}21402141if(commit_ref(lock)) {2142strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2143unlock_ref(lock);2144return-1;2145}21462147unlock_ref(lock);2148return0;2149}21502151static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2152{2153int ret = -1;2154#ifndef NO_SYMLINK_HEAD2155char*ref_path =get_locked_file_path(lock->lk);2156unlink(ref_path);2157 ret =symlink(target, ref_path);2158free(ref_path);21592160if(ret)2161fprintf(stderr,"no symlink - falling back to symbolic ref\n");2162#endif2163return ret;2164}21652166static voidupdate_symref_reflog(struct files_ref_store *refs,2167struct ref_lock *lock,const char*refname,2168const char*target,const char*logmsg)2169{2170struct strbuf err = STRBUF_INIT;2171struct object_id new_oid;2172if(logmsg &&2173!refs_read_ref_full(&refs->base, target,2174 RESOLVE_REF_READING, new_oid.hash, NULL) &&2175files_log_ref_write(refs, refname, &lock->old_oid,2176&new_oid, logmsg,0, &err)) {2177error("%s", err.buf);2178strbuf_release(&err);2179}2180}21812182static intcreate_symref_locked(struct files_ref_store *refs,2183struct ref_lock *lock,const char*refname,2184const char*target,const char*logmsg)2185{2186if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2187update_symref_reflog(refs, lock, refname, target, logmsg);2188return0;2189}21902191if(!fdopen_lock_file(lock->lk,"w"))2192returnerror("unable to fdopen%s:%s",2193 lock->lk->tempfile.filename.buf,strerror(errno));21942195update_symref_reflog(refs, lock, refname, target, logmsg);21962197/* no error check; commit_ref will check ferror */2198fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2199if(commit_ref(lock) <0)2200returnerror("unable to write symref for%s:%s", refname,2201strerror(errno));2202return0;2203}22042205static intfiles_create_symref(struct ref_store *ref_store,2206const char*refname,const char*target,2207const char*logmsg)2208{2209struct files_ref_store *refs =2210files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2211struct strbuf err = STRBUF_INIT;2212struct ref_lock *lock;2213int ret;22142215 lock =lock_ref_sha1_basic(refs, refname, NULL,2216 NULL, NULL, REF_NODEREF, NULL,2217&err);2218if(!lock) {2219error("%s", err.buf);2220strbuf_release(&err);2221return-1;2222}22232224 ret =create_symref_locked(refs, lock, refname, target, logmsg);2225unlock_ref(lock);2226return ret;2227}22282229static intfiles_reflog_exists(struct ref_store *ref_store,2230const char*refname)2231{2232struct files_ref_store *refs =2233files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2234struct strbuf sb = STRBUF_INIT;2235struct stat st;2236int ret;22372238files_reflog_path(refs, &sb, refname);2239 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2240strbuf_release(&sb);2241return ret;2242}22432244static intfiles_delete_reflog(struct ref_store *ref_store,2245const char*refname)2246{2247struct files_ref_store *refs =2248files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2249struct strbuf sb = STRBUF_INIT;2250int ret;22512252files_reflog_path(refs, &sb, refname);2253 ret =remove_path(sb.buf);2254strbuf_release(&sb);2255return ret;2256}22572258static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2259{2260struct object_id ooid, noid;2261char*email_end, *message;2262 timestamp_t timestamp;2263int tz;2264const char*p = sb->buf;22652266/* old SP new SP name <email> SP time TAB msg LF */2267if(!sb->len || sb->buf[sb->len -1] !='\n'||2268parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2269parse_oid_hex(p, &noid, &p) || *p++ !=' '||2270!(email_end =strchr(p,'>')) ||2271 email_end[1] !=' '||2272!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2273!message || message[0] !=' '||2274(message[1] !='+'&& message[1] !='-') ||2275!isdigit(message[2]) || !isdigit(message[3]) ||2276!isdigit(message[4]) || !isdigit(message[5]))2277return0;/* corrupt? */2278 email_end[1] ='\0';2279 tz =strtol(message +1, NULL,10);2280if(message[6] !='\t')2281 message +=6;2282else2283 message +=7;2284returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2285}22862287static char*find_beginning_of_line(char*bob,char*scan)2288{2289while(bob < scan && *(--scan) !='\n')2290;/* keep scanning backwards */2291/*2292 * Return either beginning of the buffer, or LF at the end of2293 * the previous line.2294 */2295return scan;2296}22972298static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2299const char*refname,2300 each_reflog_ent_fn fn,2301void*cb_data)2302{2303struct files_ref_store *refs =2304files_downcast(ref_store, REF_STORE_READ,2305"for_each_reflog_ent_reverse");2306struct strbuf sb = STRBUF_INIT;2307FILE*logfp;2308long pos;2309int ret =0, at_tail =1;23102311files_reflog_path(refs, &sb, refname);2312 logfp =fopen(sb.buf,"r");2313strbuf_release(&sb);2314if(!logfp)2315return-1;23162317/* Jump to the end */2318if(fseek(logfp,0, SEEK_END) <0)2319 ret =error("cannot seek back reflog for%s:%s",2320 refname,strerror(errno));2321 pos =ftell(logfp);2322while(!ret &&0< pos) {2323int cnt;2324size_t nread;2325char buf[BUFSIZ];2326char*endp, *scanp;23272328/* Fill next block from the end */2329 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2330if(fseek(logfp, pos - cnt, SEEK_SET)) {2331 ret =error("cannot seek back reflog for%s:%s",2332 refname,strerror(errno));2333break;2334}2335 nread =fread(buf, cnt,1, logfp);2336if(nread !=1) {2337 ret =error("cannot read%dbytes from reflog for%s:%s",2338 cnt, refname,strerror(errno));2339break;2340}2341 pos -= cnt;23422343 scanp = endp = buf + cnt;2344if(at_tail && scanp[-1] =='\n')2345/* Looking at the final LF at the end of the file */2346 scanp--;2347 at_tail =0;23482349while(buf < scanp) {2350/*2351 * terminating LF of the previous line, or the beginning2352 * of the buffer.2353 */2354char*bp;23552356 bp =find_beginning_of_line(buf, scanp);23572358if(*bp =='\n') {2359/*2360 * The newline is the end of the previous line,2361 * so we know we have complete line starting2362 * at (bp + 1). Prefix it onto any prior data2363 * we collected for the line and process it.2364 */2365strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2366 scanp = bp;2367 endp = bp +1;2368 ret =show_one_reflog_ent(&sb, fn, cb_data);2369strbuf_reset(&sb);2370if(ret)2371break;2372}else if(!pos) {2373/*2374 * We are at the start of the buffer, and the2375 * start of the file; there is no previous2376 * line, and we have everything for this one.2377 * Process it, and we can end the loop.2378 */2379strbuf_splice(&sb,0,0, buf, endp - buf);2380 ret =show_one_reflog_ent(&sb, fn, cb_data);2381strbuf_reset(&sb);2382break;2383}23842385if(bp == buf) {2386/*2387 * We are at the start of the buffer, and there2388 * is more file to read backwards. Which means2389 * we are in the middle of a line. Note that we2390 * may get here even if *bp was a newline; that2391 * just means we are at the exact end of the2392 * previous line, rather than some spot in the2393 * middle.2394 *2395 * Save away what we have to be combined with2396 * the data from the next read.2397 */2398strbuf_splice(&sb,0,0, buf, endp - buf);2399break;2400}2401}24022403}2404if(!ret && sb.len)2405die("BUG: reverse reflog parser had leftover data");24062407fclose(logfp);2408strbuf_release(&sb);2409return ret;2410}24112412static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2413const char*refname,2414 each_reflog_ent_fn fn,void*cb_data)2415{2416struct files_ref_store *refs =2417files_downcast(ref_store, REF_STORE_READ,2418"for_each_reflog_ent");2419FILE*logfp;2420struct strbuf sb = STRBUF_INIT;2421int ret =0;24222423files_reflog_path(refs, &sb, refname);2424 logfp =fopen(sb.buf,"r");2425strbuf_release(&sb);2426if(!logfp)2427return-1;24282429while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2430 ret =show_one_reflog_ent(&sb, fn, cb_data);2431fclose(logfp);2432strbuf_release(&sb);2433return ret;2434}24352436struct files_reflog_iterator {2437struct ref_iterator base;24382439struct ref_store *ref_store;2440struct dir_iterator *dir_iterator;2441struct object_id oid;2442};24432444static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2445{2446struct files_reflog_iterator *iter =2447(struct files_reflog_iterator *)ref_iterator;2448struct dir_iterator *diter = iter->dir_iterator;2449int ok;24502451while((ok =dir_iterator_advance(diter)) == ITER_OK) {2452int flags;24532454if(!S_ISREG(diter->st.st_mode))2455continue;2456if(diter->basename[0] =='.')2457continue;2458if(ends_with(diter->basename,".lock"))2459continue;24602461if(refs_read_ref_full(iter->ref_store,2462 diter->relative_path,0,2463 iter->oid.hash, &flags)) {2464error("bad ref for%s", diter->path.buf);2465continue;2466}24672468 iter->base.refname = diter->relative_path;2469 iter->base.oid = &iter->oid;2470 iter->base.flags = flags;2471return ITER_OK;2472}24732474 iter->dir_iterator = NULL;2475if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2476 ok = ITER_ERROR;2477return ok;2478}24792480static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2481struct object_id *peeled)2482{2483die("BUG: ref_iterator_peel() called for reflog_iterator");2484}24852486static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2487{2488struct files_reflog_iterator *iter =2489(struct files_reflog_iterator *)ref_iterator;2490int ok = ITER_DONE;24912492if(iter->dir_iterator)2493 ok =dir_iterator_abort(iter->dir_iterator);24942495base_ref_iterator_free(ref_iterator);2496return ok;2497}24982499static struct ref_iterator_vtable files_reflog_iterator_vtable = {2500 files_reflog_iterator_advance,2501 files_reflog_iterator_peel,2502 files_reflog_iterator_abort2503};25042505static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2506{2507struct files_ref_store *refs =2508files_downcast(ref_store, REF_STORE_READ,2509"reflog_iterator_begin");2510struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2511struct ref_iterator *ref_iterator = &iter->base;2512struct strbuf sb = STRBUF_INIT;25132514base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2515files_reflog_path(refs, &sb, NULL);2516 iter->dir_iterator =dir_iterator_begin(sb.buf);2517 iter->ref_store = ref_store;2518strbuf_release(&sb);2519return ref_iterator;2520}25212522static intref_update_reject_duplicates(struct string_list *refnames,2523struct strbuf *err)2524{2525int i, n = refnames->nr;25262527assert(err);25282529for(i =1; i < n; i++)2530if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2531strbuf_addf(err,2532"multiple updates for ref '%s' not allowed.",2533 refnames->items[i].string);2534return1;2535}2536return0;2537}25382539/*2540 * If update is a direct update of head_ref (the reference pointed to2541 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2542 */2543static intsplit_head_update(struct ref_update *update,2544struct ref_transaction *transaction,2545const char*head_ref,2546struct string_list *affected_refnames,2547struct strbuf *err)2548{2549struct string_list_item *item;2550struct ref_update *new_update;25512552if((update->flags & REF_LOG_ONLY) ||2553(update->flags & REF_ISPRUNING) ||2554(update->flags & REF_UPDATE_VIA_HEAD))2555return0;25562557if(strcmp(update->refname, head_ref))2558return0;25592560/*2561 * First make sure that HEAD is not already in the2562 * transaction. This insertion is O(N) in the transaction2563 * size, but it happens at most once per transaction.2564 */2565 item =string_list_insert(affected_refnames,"HEAD");2566if(item->util) {2567/* An entry already existed */2568strbuf_addf(err,2569"multiple updates for 'HEAD' (including one "2570"via its referent '%s') are not allowed",2571 update->refname);2572return TRANSACTION_NAME_CONFLICT;2573}25742575 new_update =ref_transaction_add_update(2576 transaction,"HEAD",2577 update->flags | REF_LOG_ONLY | REF_NODEREF,2578 update->new_oid.hash, update->old_oid.hash,2579 update->msg);25802581 item->util = new_update;25822583return0;2584}25852586/*2587 * update is for a symref that points at referent and doesn't have2588 * REF_NODEREF set. Split it into two updates:2589 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2590 * - A new, separate update for the referent reference2591 * Note that the new update will itself be subject to splitting when2592 * the iteration gets to it.2593 */2594static intsplit_symref_update(struct files_ref_store *refs,2595struct ref_update *update,2596const char*referent,2597struct ref_transaction *transaction,2598struct string_list *affected_refnames,2599struct strbuf *err)2600{2601struct string_list_item *item;2602struct ref_update *new_update;2603unsigned int new_flags;26042605/*2606 * First make sure that referent is not already in the2607 * transaction. This insertion is O(N) in the transaction2608 * size, but it happens at most once per symref in a2609 * transaction.2610 */2611 item =string_list_insert(affected_refnames, referent);2612if(item->util) {2613/* An entry already existed */2614strbuf_addf(err,2615"multiple updates for '%s' (including one "2616"via symref '%s') are not allowed",2617 referent, update->refname);2618return TRANSACTION_NAME_CONFLICT;2619}26202621 new_flags = update->flags;2622if(!strcmp(update->refname,"HEAD")) {2623/*2624 * Record that the new update came via HEAD, so that2625 * when we process it, split_head_update() doesn't try2626 * to add another reflog update for HEAD. Note that2627 * this bit will be propagated if the new_update2628 * itself needs to be split.2629 */2630 new_flags |= REF_UPDATE_VIA_HEAD;2631}26322633 new_update =ref_transaction_add_update(2634 transaction, referent, new_flags,2635 update->new_oid.hash, update->old_oid.hash,2636 update->msg);26372638 new_update->parent_update = update;26392640/*2641 * Change the symbolic ref update to log only. Also, it2642 * doesn't need to check its old SHA-1 value, as that will be2643 * done when new_update is processed.2644 */2645 update->flags |= REF_LOG_ONLY | REF_NODEREF;2646 update->flags &= ~REF_HAVE_OLD;26472648 item->util = new_update;26492650return0;2651}26522653/*2654 * Return the refname under which update was originally requested.2655 */2656static const char*original_update_refname(struct ref_update *update)2657{2658while(update->parent_update)2659 update = update->parent_update;26602661return update->refname;2662}26632664/*2665 * Check whether the REF_HAVE_OLD and old_oid values stored in update2666 * are consistent with oid, which is the reference's current value. If2667 * everything is OK, return 0; otherwise, write an error message to2668 * err and return -1.2669 */2670static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2671struct strbuf *err)2672{2673if(!(update->flags & REF_HAVE_OLD) ||2674!oidcmp(oid, &update->old_oid))2675return0;26762677if(is_null_oid(&update->old_oid))2678strbuf_addf(err,"cannot lock ref '%s': "2679"reference already exists",2680original_update_refname(update));2681else if(is_null_oid(oid))2682strbuf_addf(err,"cannot lock ref '%s': "2683"reference is missing but expected%s",2684original_update_refname(update),2685oid_to_hex(&update->old_oid));2686else2687strbuf_addf(err,"cannot lock ref '%s': "2688"is at%sbut expected%s",2689original_update_refname(update),2690oid_to_hex(oid),2691oid_to_hex(&update->old_oid));26922693return-1;2694}26952696/*2697 * Prepare for carrying out update:2698 * - Lock the reference referred to by update.2699 * - Read the reference under lock.2700 * - Check that its old SHA-1 value (if specified) is correct, and in2701 * any case record it in update->lock->old_oid for later use when2702 * writing the reflog.2703 * - If it is a symref update without REF_NODEREF, split it up into a2704 * REF_LOG_ONLY update of the symref and add a separate update for2705 * the referent to transaction.2706 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2707 * update of HEAD.2708 */2709static intlock_ref_for_update(struct files_ref_store *refs,2710struct ref_update *update,2711struct ref_transaction *transaction,2712const char*head_ref,2713struct string_list *affected_refnames,2714struct strbuf *err)2715{2716struct strbuf referent = STRBUF_INIT;2717int mustexist = (update->flags & REF_HAVE_OLD) &&2718!is_null_oid(&update->old_oid);2719int ret;2720struct ref_lock *lock;27212722files_assert_main_repository(refs,"lock_ref_for_update");27232724if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2725 update->flags |= REF_DELETING;27262727if(head_ref) {2728 ret =split_head_update(update, transaction, head_ref,2729 affected_refnames, err);2730if(ret)2731return ret;2732}27332734 ret =lock_raw_ref(refs, update->refname, mustexist,2735 affected_refnames, NULL,2736&lock, &referent,2737&update->type, err);2738if(ret) {2739char*reason;27402741 reason =strbuf_detach(err, NULL);2742strbuf_addf(err,"cannot lock ref '%s':%s",2743original_update_refname(update), reason);2744free(reason);2745return ret;2746}27472748 update->backend_data = lock;27492750if(update->type & REF_ISSYMREF) {2751if(update->flags & REF_NODEREF) {2752/*2753 * We won't be reading the referent as part of2754 * the transaction, so we have to read it here2755 * to record and possibly check old_sha1:2756 */2757if(refs_read_ref_full(&refs->base,2758 referent.buf,0,2759 lock->old_oid.hash, NULL)) {2760if(update->flags & REF_HAVE_OLD) {2761strbuf_addf(err,"cannot lock ref '%s': "2762"error reading reference",2763original_update_refname(update));2764return-1;2765}2766}else if(check_old_oid(update, &lock->old_oid, err)) {2767return TRANSACTION_GENERIC_ERROR;2768}2769}else{2770/*2771 * Create a new update for the reference this2772 * symref is pointing at. Also, we will record2773 * and verify old_sha1 for this update as part2774 * of processing the split-off update, so we2775 * don't have to do it here.2776 */2777 ret =split_symref_update(refs, update,2778 referent.buf, transaction,2779 affected_refnames, err);2780if(ret)2781return ret;2782}2783}else{2784struct ref_update *parent_update;27852786if(check_old_oid(update, &lock->old_oid, err))2787return TRANSACTION_GENERIC_ERROR;27882789/*2790 * If this update is happening indirectly because of a2791 * symref update, record the old SHA-1 in the parent2792 * update:2793 */2794for(parent_update = update->parent_update;2795 parent_update;2796 parent_update = parent_update->parent_update) {2797struct ref_lock *parent_lock = parent_update->backend_data;2798oidcpy(&parent_lock->old_oid, &lock->old_oid);2799}2800}28012802if((update->flags & REF_HAVE_NEW) &&2803!(update->flags & REF_DELETING) &&2804!(update->flags & REF_LOG_ONLY)) {2805if(!(update->type & REF_ISSYMREF) &&2806!oidcmp(&lock->old_oid, &update->new_oid)) {2807/*2808 * The reference already has the desired2809 * value, so we don't need to write it.2810 */2811}else if(write_ref_to_lockfile(lock, &update->new_oid,2812 err)) {2813char*write_err =strbuf_detach(err, NULL);28142815/*2816 * The lock was freed upon failure of2817 * write_ref_to_lockfile():2818 */2819 update->backend_data = NULL;2820strbuf_addf(err,2821"cannot update ref '%s':%s",2822 update->refname, write_err);2823free(write_err);2824return TRANSACTION_GENERIC_ERROR;2825}else{2826 update->flags |= REF_NEEDS_COMMIT;2827}2828}2829if(!(update->flags & REF_NEEDS_COMMIT)) {2830/*2831 * We didn't call write_ref_to_lockfile(), so2832 * the lockfile is still open. Close it to2833 * free up the file descriptor:2834 */2835if(close_ref(lock)) {2836strbuf_addf(err,"couldn't close '%s.lock'",2837 update->refname);2838return TRANSACTION_GENERIC_ERROR;2839}2840}2841return0;2842}28432844static intfiles_transaction_commit(struct ref_store *ref_store,2845struct ref_transaction *transaction,2846struct strbuf *err)2847{2848struct files_ref_store *refs =2849files_downcast(ref_store, REF_STORE_WRITE,2850"ref_transaction_commit");2851size_t i;2852int ret =0;2853struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2854struct string_list_item *ref_to_delete;2855struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2856char*head_ref = NULL;2857int head_type;2858struct object_id head_oid;2859struct strbuf sb = STRBUF_INIT;28602861assert(err);28622863if(transaction->state != REF_TRANSACTION_OPEN)2864die("BUG: commit called for transaction that is not open");28652866if(!transaction->nr) {2867 transaction->state = REF_TRANSACTION_CLOSED;2868return0;2869}28702871/*2872 * Fail if a refname appears more than once in the2873 * transaction. (If we end up splitting up any updates using2874 * split_symref_update() or split_head_update(), those2875 * functions will check that the new updates don't have the2876 * same refname as any existing ones.)2877 */2878for(i =0; i < transaction->nr; i++) {2879struct ref_update *update = transaction->updates[i];2880struct string_list_item *item =2881string_list_append(&affected_refnames, update->refname);28822883/*2884 * We store a pointer to update in item->util, but at2885 * the moment we never use the value of this field2886 * except to check whether it is non-NULL.2887 */2888 item->util = update;2889}2890string_list_sort(&affected_refnames);2891if(ref_update_reject_duplicates(&affected_refnames, err)) {2892 ret = TRANSACTION_GENERIC_ERROR;2893goto cleanup;2894}28952896/*2897 * Special hack: If a branch is updated directly and HEAD2898 * points to it (may happen on the remote side of a push2899 * for example) then logically the HEAD reflog should be2900 * updated too.2901 *2902 * A generic solution would require reverse symref lookups,2903 * but finding all symrefs pointing to a given branch would be2904 * rather costly for this rare event (the direct update of a2905 * branch) to be worth it. So let's cheat and check with HEAD2906 * only, which should cover 99% of all usage scenarios (even2907 * 100% of the default ones).2908 *2909 * So if HEAD is a symbolic reference, then record the name of2910 * the reference that it points to. If we see an update of2911 * head_ref within the transaction, then split_head_update()2912 * arranges for the reflog of HEAD to be updated, too.2913 */2914 head_ref =refs_resolve_refdup(ref_store,"HEAD",2915 RESOLVE_REF_NO_RECURSE,2916 head_oid.hash, &head_type);29172918if(head_ref && !(head_type & REF_ISSYMREF)) {2919free(head_ref);2920 head_ref = NULL;2921}29222923/*2924 * Acquire all locks, verify old values if provided, check2925 * that new values are valid, and write new values to the2926 * lockfiles, ready to be activated. Only keep one lockfile2927 * open at a time to avoid running out of file descriptors.2928 */2929for(i =0; i < transaction->nr; i++) {2930struct ref_update *update = transaction->updates[i];29312932 ret =lock_ref_for_update(refs, update, transaction,2933 head_ref, &affected_refnames, err);2934if(ret)2935goto cleanup;2936}29372938/* Perform updates first so live commits remain referenced */2939for(i =0; i < transaction->nr; i++) {2940struct ref_update *update = transaction->updates[i];2941struct ref_lock *lock = update->backend_data;29422943if(update->flags & REF_NEEDS_COMMIT ||2944 update->flags & REF_LOG_ONLY) {2945if(files_log_ref_write(refs,2946 lock->ref_name,2947&lock->old_oid,2948&update->new_oid,2949 update->msg, update->flags,2950 err)) {2951char*old_msg =strbuf_detach(err, NULL);29522953strbuf_addf(err,"cannot update the ref '%s':%s",2954 lock->ref_name, old_msg);2955free(old_msg);2956unlock_ref(lock);2957 update->backend_data = NULL;2958 ret = TRANSACTION_GENERIC_ERROR;2959goto cleanup;2960}2961}2962if(update->flags & REF_NEEDS_COMMIT) {2963clear_loose_ref_cache(refs);2964if(commit_ref(lock)) {2965strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2966unlock_ref(lock);2967 update->backend_data = NULL;2968 ret = TRANSACTION_GENERIC_ERROR;2969goto cleanup;2970}2971}2972}2973/* Perform deletes now that updates are safely completed */2974for(i =0; i < transaction->nr; i++) {2975struct ref_update *update = transaction->updates[i];2976struct ref_lock *lock = update->backend_data;29772978if(update->flags & REF_DELETING &&2979!(update->flags & REF_LOG_ONLY)) {2980if(!(update->type & REF_ISPACKED) ||2981 update->type & REF_ISSYMREF) {2982/* It is a loose reference. */2983strbuf_reset(&sb);2984files_ref_path(refs, &sb, lock->ref_name);2985if(unlink_or_msg(sb.buf, err)) {2986 ret = TRANSACTION_GENERIC_ERROR;2987goto cleanup;2988}2989 update->flags |= REF_DELETED_LOOSE;2990}29912992if(!(update->flags & REF_ISPRUNING))2993string_list_append(&refs_to_delete,2994 lock->ref_name);2995}2996}29972998if(repack_without_refs(refs, &refs_to_delete, err)) {2999 ret = TRANSACTION_GENERIC_ERROR;3000goto cleanup;3001}30023003/* Delete the reflogs of any references that were deleted: */3004for_each_string_list_item(ref_to_delete, &refs_to_delete) {3005strbuf_reset(&sb);3006files_reflog_path(refs, &sb, ref_to_delete->string);3007if(!unlink_or_warn(sb.buf))3008try_remove_empty_parents(refs, ref_to_delete->string,3009 REMOVE_EMPTY_PARENTS_REFLOG);3010}30113012clear_loose_ref_cache(refs);30133014cleanup:3015strbuf_release(&sb);3016 transaction->state = REF_TRANSACTION_CLOSED;30173018for(i =0; i < transaction->nr; i++) {3019struct ref_update *update = transaction->updates[i];3020struct ref_lock *lock = update->backend_data;30213022if(lock)3023unlock_ref(lock);30243025if(update->flags & REF_DELETED_LOOSE) {3026/*3027 * The loose reference was deleted. Delete any3028 * empty parent directories. (Note that this3029 * can only work because we have already3030 * removed the lockfile.)3031 */3032try_remove_empty_parents(refs, update->refname,3033 REMOVE_EMPTY_PARENTS_REF);3034}3035}30363037string_list_clear(&refs_to_delete,0);3038free(head_ref);3039string_list_clear(&affected_refnames,0);30403041return ret;3042}30433044static intref_present(const char*refname,3045const struct object_id *oid,int flags,void*cb_data)3046{3047struct string_list *affected_refnames = cb_data;30483049returnstring_list_has_string(affected_refnames, refname);3050}30513052static intfiles_initial_transaction_commit(struct ref_store *ref_store,3053struct ref_transaction *transaction,3054struct strbuf *err)3055{3056struct files_ref_store *refs =3057files_downcast(ref_store, REF_STORE_WRITE,3058"initial_ref_transaction_commit");3059size_t i;3060int ret =0;3061struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30623063assert(err);30643065if(transaction->state != REF_TRANSACTION_OPEN)3066die("BUG: commit called for transaction that is not open");30673068/* Fail if a refname appears more than once in the transaction: */3069for(i =0; i < transaction->nr; i++)3070string_list_append(&affected_refnames,3071 transaction->updates[i]->refname);3072string_list_sort(&affected_refnames);3073if(ref_update_reject_duplicates(&affected_refnames, err)) {3074 ret = TRANSACTION_GENERIC_ERROR;3075goto cleanup;3076}30773078/*3079 * It's really undefined to call this function in an active3080 * repository or when there are existing references: we are3081 * only locking and changing packed-refs, so (1) any3082 * simultaneous processes might try to change a reference at3083 * the same time we do, and (2) any existing loose versions of3084 * the references that we are setting would have precedence3085 * over our values. But some remote helpers create the remote3086 * "HEAD" and "master" branches before calling this function,3087 * so here we really only check that none of the references3088 * that we are creating already exists.3089 */3090if(refs_for_each_rawref(&refs->base, ref_present,3091&affected_refnames))3092die("BUG: initial ref transaction called with existing refs");30933094for(i =0; i < transaction->nr; i++) {3095struct ref_update *update = transaction->updates[i];30963097if((update->flags & REF_HAVE_OLD) &&3098!is_null_oid(&update->old_oid))3099die("BUG: initial ref transaction with old_sha1 set");3100if(refs_verify_refname_available(&refs->base, update->refname,3101&affected_refnames, NULL,3102 err)) {3103 ret = TRANSACTION_NAME_CONFLICT;3104goto cleanup;3105}3106}31073108if(lock_packed_refs(refs,0)) {3109strbuf_addf(err,"unable to lock packed-refs file:%s",3110strerror(errno));3111 ret = TRANSACTION_GENERIC_ERROR;3112goto cleanup;3113}31143115for(i =0; i < transaction->nr; i++) {3116struct ref_update *update = transaction->updates[i];31173118if((update->flags & REF_HAVE_NEW) &&3119!is_null_oid(&update->new_oid))3120add_packed_ref(refs, update->refname,3121&update->new_oid);3122}31233124if(commit_packed_refs(refs)) {3125strbuf_addf(err,"unable to commit packed-refs file:%s",3126strerror(errno));3127 ret = TRANSACTION_GENERIC_ERROR;3128goto cleanup;3129}31303131cleanup:3132 transaction->state = REF_TRANSACTION_CLOSED;3133string_list_clear(&affected_refnames,0);3134return ret;3135}31363137struct expire_reflog_cb {3138unsigned int flags;3139 reflog_expiry_should_prune_fn *should_prune_fn;3140void*policy_cb;3141FILE*newlog;3142struct object_id last_kept_oid;3143};31443145static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3146const char*email, timestamp_t timestamp,int tz,3147const char*message,void*cb_data)3148{3149struct expire_reflog_cb *cb = cb_data;3150struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;31513152if(cb->flags & EXPIRE_REFLOGS_REWRITE)3153 ooid = &cb->last_kept_oid;31543155if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3156 message, policy_cb)) {3157if(!cb->newlog)3158printf("would prune%s", message);3159else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3160printf("prune%s", message);3161}else{3162if(cb->newlog) {3163fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3164oid_to_hex(ooid),oid_to_hex(noid),3165 email, timestamp, tz, message);3166oidcpy(&cb->last_kept_oid, noid);3167}3168if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3169printf("keep%s", message);3170}3171return0;3172}31733174static intfiles_reflog_expire(struct ref_store *ref_store,3175const char*refname,const unsigned char*sha1,3176unsigned int flags,3177 reflog_expiry_prepare_fn prepare_fn,3178 reflog_expiry_should_prune_fn should_prune_fn,3179 reflog_expiry_cleanup_fn cleanup_fn,3180void*policy_cb_data)3181{3182struct files_ref_store *refs =3183files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3184static struct lock_file reflog_lock;3185struct expire_reflog_cb cb;3186struct ref_lock *lock;3187struct strbuf log_file_sb = STRBUF_INIT;3188char*log_file;3189int status =0;3190int type;3191struct strbuf err = STRBUF_INIT;3192struct object_id oid;31933194memset(&cb,0,sizeof(cb));3195 cb.flags = flags;3196 cb.policy_cb = policy_cb_data;3197 cb.should_prune_fn = should_prune_fn;31983199/*3200 * The reflog file is locked by holding the lock on the3201 * reference itself, plus we might need to update the3202 * reference if --updateref was specified:3203 */3204 lock =lock_ref_sha1_basic(refs, refname, sha1,3205 NULL, NULL, REF_NODEREF,3206&type, &err);3207if(!lock) {3208error("cannot lock ref '%s':%s", refname, err.buf);3209strbuf_release(&err);3210return-1;3211}3212if(!refs_reflog_exists(ref_store, refname)) {3213unlock_ref(lock);3214return0;3215}32163217files_reflog_path(refs, &log_file_sb, refname);3218 log_file =strbuf_detach(&log_file_sb, NULL);3219if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3220/*3221 * Even though holding $GIT_DIR/logs/$reflog.lock has3222 * no locking implications, we use the lock_file3223 * machinery here anyway because it does a lot of the3224 * work we need, including cleaning up if the program3225 * exits unexpectedly.3226 */3227if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3228struct strbuf err = STRBUF_INIT;3229unable_to_lock_message(log_file, errno, &err);3230error("%s", err.buf);3231strbuf_release(&err);3232goto failure;3233}3234 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3235if(!cb.newlog) {3236error("cannot fdopen%s(%s)",3237get_lock_file_path(&reflog_lock),strerror(errno));3238goto failure;3239}3240}32413242hashcpy(oid.hash, sha1);32433244(*prepare_fn)(refname, &oid, cb.policy_cb);3245refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3246(*cleanup_fn)(cb.policy_cb);32473248if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3249/*3250 * It doesn't make sense to adjust a reference pointed3251 * to by a symbolic ref based on expiring entries in3252 * the symbolic reference's reflog. Nor can we update3253 * a reference if there are no remaining reflog3254 * entries.3255 */3256int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3257!(type & REF_ISSYMREF) &&3258!is_null_oid(&cb.last_kept_oid);32593260if(close_lock_file(&reflog_lock)) {3261 status |=error("couldn't write%s:%s", log_file,3262strerror(errno));3263}else if(update &&3264(write_in_full(get_lock_file_fd(lock->lk),3265oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3266write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3267close_ref(lock) <0)) {3268 status |=error("couldn't write%s",3269get_lock_file_path(lock->lk));3270rollback_lock_file(&reflog_lock);3271}else if(commit_lock_file(&reflog_lock)) {3272 status |=error("unable to write reflog '%s' (%s)",3273 log_file,strerror(errno));3274}else if(update &&commit_ref(lock)) {3275 status |=error("couldn't set%s", lock->ref_name);3276}3277}3278free(log_file);3279unlock_ref(lock);3280return status;32813282 failure:3283rollback_lock_file(&reflog_lock);3284free(log_file);3285unlock_ref(lock);3286return-1;3287}32883289static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3290{3291struct files_ref_store *refs =3292files_downcast(ref_store, REF_STORE_WRITE,"init_db");3293struct strbuf sb = STRBUF_INIT;32943295/*3296 * Create .git/refs/{heads,tags}3297 */3298files_ref_path(refs, &sb,"refs/heads");3299safe_create_dir(sb.buf,1);33003301strbuf_reset(&sb);3302files_ref_path(refs, &sb,"refs/tags");3303safe_create_dir(sb.buf,1);33043305strbuf_release(&sb);3306return0;3307}33083309struct ref_storage_be refs_be_files = {3310 NULL,3311"files",3312 files_ref_store_create,3313 files_init_db,3314 files_transaction_commit,3315 files_initial_transaction_commit,33163317 files_pack_refs,3318 files_peel_ref,3319 files_create_symref,3320 files_delete_refs,3321 files_rename_ref,33223323 files_ref_iterator_begin,3324 files_read_raw_ref,33253326 files_reflog_iterator_begin,3327 files_for_each_reflog_ent,3328 files_for_each_reflog_ent_reverse,3329 files_reflog_exists,3330 files_create_reflog,3331 files_delete_reflog,3332 files_reflog_expire3333};