1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * Future: need to be in "struct repository" 52 * when doing a full libification. 53 */ 54struct files_ref_store { 55struct ref_store base; 56unsigned int store_flags; 57 58char*gitdir; 59char*gitcommondir; 60char*packed_refs_path; 61 62struct ref_cache *loose; 63struct packed_ref_cache *packed; 64 65/* 66 * Lock used for the "packed-refs" file. Note that this (and 67 * thus the enclosing `files_ref_store`) must not be freed. 68 */ 69struct lock_file packed_refs_lock; 70}; 71 72/* 73 * Increment the reference count of *packed_refs. 74 */ 75static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 76{ 77 packed_refs->referrers++; 78} 79 80/* 81 * Decrease the reference count of *packed_refs. If it goes to zero, 82 * free *packed_refs and return true; otherwise return false. 83 */ 84static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 85{ 86if(!--packed_refs->referrers) { 87free_ref_cache(packed_refs->cache); 88stat_validity_clear(&packed_refs->validity); 89free(packed_refs); 90return1; 91}else{ 92return0; 93} 94} 95 96static voidclear_packed_ref_cache(struct files_ref_store *refs) 97{ 98if(refs->packed) { 99struct packed_ref_cache *packed_refs = refs->packed; 100 101if(is_lock_file_locked(&refs->packed_refs_lock)) 102die("BUG: packed-ref cache cleared while locked"); 103 refs->packed = NULL; 104release_packed_ref_cache(packed_refs); 105} 106} 107 108static voidclear_loose_ref_cache(struct files_ref_store *refs) 109{ 110if(refs->loose) { 111free_ref_cache(refs->loose); 112 refs->loose = NULL; 113} 114} 115 116/* 117 * Create a new submodule ref cache and add it to the internal 118 * set of caches. 119 */ 120static struct ref_store *files_ref_store_create(const char*gitdir, 121unsigned int flags) 122{ 123struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 124struct ref_store *ref_store = (struct ref_store *)refs; 125struct strbuf sb = STRBUF_INIT; 126 127base_ref_store_init(ref_store, &refs_be_files); 128 refs->store_flags = flags; 129 130 refs->gitdir =xstrdup(gitdir); 131get_common_dir_noenv(&sb, gitdir); 132 refs->gitcommondir =strbuf_detach(&sb, NULL); 133strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 134 refs->packed_refs_path =strbuf_detach(&sb, NULL); 135 136return ref_store; 137} 138 139/* 140 * Die if refs is not the main ref store. caller is used in any 141 * necessary error messages. 142 */ 143static voidfiles_assert_main_repository(struct files_ref_store *refs, 144const char*caller) 145{ 146if(refs->store_flags & REF_STORE_MAIN) 147return; 148 149die("BUG: operation%sonly allowed for main ref store", caller); 150} 151 152/* 153 * Downcast ref_store to files_ref_store. Die if ref_store is not a 154 * files_ref_store. required_flags is compared with ref_store's 155 * store_flags to ensure the ref_store has all required capabilities. 156 * "caller" is used in any necessary error messages. 157 */ 158static struct files_ref_store *files_downcast(struct ref_store *ref_store, 159unsigned int required_flags, 160const char*caller) 161{ 162struct files_ref_store *refs; 163 164if(ref_store->be != &refs_be_files) 165die("BUG: ref_store is type\"%s\"not\"files\"in%s", 166 ref_store->be->name, caller); 167 168 refs = (struct files_ref_store *)ref_store; 169 170if((refs->store_flags & required_flags) != required_flags) 171die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 172 caller, required_flags, refs->store_flags); 173 174return refs; 175} 176 177/* The length of a peeled reference line in packed-refs, including EOL: */ 178#define PEELED_LINE_LENGTH 42 179 180/* 181 * The packed-refs header line that we write out. Perhaps other 182 * traits will be added later. The trailing space is required. 183 */ 184static const char PACKED_REFS_HEADER[] = 185"# pack-refs with: peeled fully-peeled\n"; 186 187/* 188 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 189 * Return a pointer to the refname within the line (null-terminated), 190 * or NULL if there was a problem. 191 */ 192static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 193{ 194const char*ref; 195 196if(parse_oid_hex(line->buf, oid, &ref) <0) 197return NULL; 198if(!isspace(*ref++)) 199return NULL; 200 201if(isspace(*ref)) 202return NULL; 203 204if(line->buf[line->len -1] !='\n') 205return NULL; 206 line->buf[--line->len] =0; 207 208return ref; 209} 210 211/* 212 * Read f, which is a packed-refs file, into dir. 213 * 214 * A comment line of the form "# pack-refs with: " may contain zero or 215 * more traits. We interpret the traits as follows: 216 * 217 * No traits: 218 * 219 * Probably no references are peeled. But if the file contains a 220 * peeled value for a reference, we will use it. 221 * 222 * peeled: 223 * 224 * References under "refs/tags/", if they *can* be peeled, *are* 225 * peeled in this file. References outside of "refs/tags/" are 226 * probably not peeled even if they could have been, but if we find 227 * a peeled value for such a reference we will use it. 228 * 229 * fully-peeled: 230 * 231 * All references in the file that can be peeled are peeled. 232 * Inversely (and this is more important), any references in the 233 * file for which no peeled value is recorded is not peelable. This 234 * trait should typically be written alongside "peeled" for 235 * compatibility with older clients, but we do not require it 236 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 237 */ 238static voidread_packed_refs(FILE*f,struct ref_dir *dir) 239{ 240struct ref_entry *last = NULL; 241struct strbuf line = STRBUF_INIT; 242enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 243 244while(strbuf_getwholeline(&line, f,'\n') != EOF) { 245struct object_id oid; 246const char*refname; 247const char*traits; 248 249if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 250if(strstr(traits," fully-peeled ")) 251 peeled = PEELED_FULLY; 252else if(strstr(traits," peeled ")) 253 peeled = PEELED_TAGS; 254/* perhaps other traits later as well */ 255continue; 256} 257 258 refname =parse_ref_line(&line, &oid); 259if(refname) { 260int flag = REF_ISPACKED; 261 262if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 263if(!refname_is_safe(refname)) 264die("packed refname is dangerous:%s", refname); 265oidclr(&oid); 266 flag |= REF_BAD_NAME | REF_ISBROKEN; 267} 268 last =create_ref_entry(refname, &oid, flag,0); 269if(peeled == PEELED_FULLY || 270(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 271 last->flag |= REF_KNOWS_PEELED; 272add_ref_entry(dir, last); 273continue; 274} 275if(last && 276 line.buf[0] =='^'&& 277 line.len == PEELED_LINE_LENGTH && 278 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 279!get_oid_hex(line.buf +1, &oid)) { 280oidcpy(&last->u.value.peeled, &oid); 281/* 282 * Regardless of what the file header said, 283 * we definitely know the value of *this* 284 * reference: 285 */ 286 last->flag |= REF_KNOWS_PEELED; 287} 288} 289 290strbuf_release(&line); 291} 292 293static const char*files_packed_refs_path(struct files_ref_store *refs) 294{ 295return refs->packed_refs_path; 296} 297 298static voidfiles_reflog_path(struct files_ref_store *refs, 299struct strbuf *sb, 300const char*refname) 301{ 302if(!refname) { 303/* 304 * FIXME: of course this is wrong in multi worktree 305 * setting. To be fixed real soon. 306 */ 307strbuf_addf(sb,"%s/logs", refs->gitcommondir); 308return; 309} 310 311switch(ref_type(refname)) { 312case REF_TYPE_PER_WORKTREE: 313case REF_TYPE_PSEUDOREF: 314strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 315break; 316case REF_TYPE_NORMAL: 317strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 318break; 319default: 320die("BUG: unknown ref type%dof ref%s", 321ref_type(refname), refname); 322} 323} 324 325static voidfiles_ref_path(struct files_ref_store *refs, 326struct strbuf *sb, 327const char*refname) 328{ 329switch(ref_type(refname)) { 330case REF_TYPE_PER_WORKTREE: 331case REF_TYPE_PSEUDOREF: 332strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 333break; 334case REF_TYPE_NORMAL: 335strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 336break; 337default: 338die("BUG: unknown ref type%dof ref%s", 339ref_type(refname), refname); 340} 341} 342 343/* 344 * Get the packed_ref_cache for the specified files_ref_store, 345 * creating and populating it if it hasn't been read before or if the 346 * file has been changed (according to its `validity` field) since it 347 * was last read. On the other hand, if we hold the lock, then assume 348 * that the file hasn't been changed out from under us, so skip the 349 * extra `stat()` call in `stat_validity_check()`. 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!is_lock_file_locked(&refs->packed_refs_lock) && 357!stat_validity_check(&refs->packed->validity, packed_refs_file)) 358clear_packed_ref_cache(refs); 359 360if(!refs->packed) { 361FILE*f; 362 363 refs->packed =xcalloc(1,sizeof(*refs->packed)); 364acquire_packed_ref_cache(refs->packed); 365 refs->packed->cache =create_ref_cache(&refs->base, NULL); 366 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 367 f =fopen(packed_refs_file,"r"); 368if(f) { 369stat_validity_update(&refs->packed->validity,fileno(f)); 370read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 371fclose(f); 372} 373} 374return refs->packed; 375} 376 377static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 378{ 379returnget_ref_dir(packed_ref_cache->cache->root); 380} 381 382static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 383{ 384returnget_packed_ref_dir(get_packed_ref_cache(refs)); 385} 386 387/* 388 * Add a reference to the in-memory packed reference cache. This may 389 * only be called while the packed-refs file is locked (see 390 * lock_packed_refs()). To actually write the packed-refs file, call 391 * commit_packed_refs(). 392 */ 393static voidadd_packed_ref(struct files_ref_store *refs, 394const char*refname,const struct object_id *oid) 395{ 396struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 397 398if(!is_lock_file_locked(&refs->packed_refs_lock)) 399die("BUG: packed refs not locked"); 400add_ref_entry(get_packed_ref_dir(packed_ref_cache), 401create_ref_entry(refname, oid, REF_ISPACKED,1)); 402} 403 404/* 405 * Read the loose references from the namespace dirname into dir 406 * (without recursing). dirname must end with '/'. dir must be the 407 * directory entry corresponding to dirname. 408 */ 409static voidloose_fill_ref_dir(struct ref_store *ref_store, 410struct ref_dir *dir,const char*dirname) 411{ 412struct files_ref_store *refs = 413files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 414DIR*d; 415struct dirent *de; 416int dirnamelen =strlen(dirname); 417struct strbuf refname; 418struct strbuf path = STRBUF_INIT; 419size_t path_baselen; 420 421files_ref_path(refs, &path, dirname); 422 path_baselen = path.len; 423 424 d =opendir(path.buf); 425if(!d) { 426strbuf_release(&path); 427return; 428} 429 430strbuf_init(&refname, dirnamelen +257); 431strbuf_add(&refname, dirname, dirnamelen); 432 433while((de =readdir(d)) != NULL) { 434struct object_id oid; 435struct stat st; 436int flag; 437 438if(de->d_name[0] =='.') 439continue; 440if(ends_with(de->d_name,".lock")) 441continue; 442strbuf_addstr(&refname, de->d_name); 443strbuf_addstr(&path, de->d_name); 444if(stat(path.buf, &st) <0) { 445;/* silently ignore */ 446}else if(S_ISDIR(st.st_mode)) { 447strbuf_addch(&refname,'/'); 448add_entry_to_dir(dir, 449create_dir_entry(dir->cache, refname.buf, 450 refname.len,1)); 451}else{ 452if(!refs_resolve_ref_unsafe(&refs->base, 453 refname.buf, 454 RESOLVE_REF_READING, 455 oid.hash, &flag)) { 456oidclr(&oid); 457 flag |= REF_ISBROKEN; 458}else if(is_null_oid(&oid)) { 459/* 460 * It is so astronomically unlikely 461 * that NULL_SHA1 is the SHA-1 of an 462 * actual object that we consider its 463 * appearance in a loose reference 464 * file to be repo corruption 465 * (probably due to a software bug). 466 */ 467 flag |= REF_ISBROKEN; 468} 469 470if(check_refname_format(refname.buf, 471 REFNAME_ALLOW_ONELEVEL)) { 472if(!refname_is_safe(refname.buf)) 473die("loose refname is dangerous:%s", refname.buf); 474oidclr(&oid); 475 flag |= REF_BAD_NAME | REF_ISBROKEN; 476} 477add_entry_to_dir(dir, 478create_ref_entry(refname.buf, &oid, flag,0)); 479} 480strbuf_setlen(&refname, dirnamelen); 481strbuf_setlen(&path, path_baselen); 482} 483strbuf_release(&refname); 484strbuf_release(&path); 485closedir(d); 486 487/* 488 * Manually add refs/bisect, which, being per-worktree, might 489 * not appear in the directory listing for refs/ in the main 490 * repo. 491 */ 492if(!strcmp(dirname,"refs/")) { 493int pos =search_ref_dir(dir,"refs/bisect/",12); 494 495if(pos <0) { 496struct ref_entry *child_entry =create_dir_entry( 497 dir->cache,"refs/bisect/",12,1); 498add_entry_to_dir(dir, child_entry); 499} 500} 501} 502 503static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 504{ 505if(!refs->loose) { 506/* 507 * Mark the top-level directory complete because we 508 * are about to read the only subdirectory that can 509 * hold references: 510 */ 511 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 512 513/* We're going to fill the top level ourselves: */ 514 refs->loose->root->flag &= ~REF_INCOMPLETE; 515 516/* 517 * Add an incomplete entry for "refs/" (to be filled 518 * lazily): 519 */ 520add_entry_to_dir(get_ref_dir(refs->loose->root), 521create_dir_entry(refs->loose,"refs/",5,1)); 522} 523return refs->loose; 524} 525 526/* 527 * Return the ref_entry for the given refname from the packed 528 * references. If it does not exist, return NULL. 529 */ 530static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 531const char*refname) 532{ 533returnfind_ref_entry(get_packed_refs(refs), refname); 534} 535 536/* 537 * A loose ref file doesn't exist; check for a packed ref. 538 */ 539static intresolve_packed_ref(struct files_ref_store *refs, 540const char*refname, 541unsigned char*sha1,unsigned int*flags) 542{ 543struct ref_entry *entry; 544 545/* 546 * The loose reference file does not exist; check for a packed 547 * reference. 548 */ 549 entry =get_packed_ref(refs, refname); 550if(entry) { 551hashcpy(sha1, entry->u.value.oid.hash); 552*flags |= REF_ISPACKED; 553return0; 554} 555/* refname is not a packed reference. */ 556return-1; 557} 558 559static intfiles_read_raw_ref(struct ref_store *ref_store, 560const char*refname,unsigned char*sha1, 561struct strbuf *referent,unsigned int*type) 562{ 563struct files_ref_store *refs = 564files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 565struct strbuf sb_contents = STRBUF_INIT; 566struct strbuf sb_path = STRBUF_INIT; 567const char*path; 568const char*buf; 569struct stat st; 570int fd; 571int ret = -1; 572int save_errno; 573int remaining_retries =3; 574 575*type =0; 576strbuf_reset(&sb_path); 577 578files_ref_path(refs, &sb_path, refname); 579 580 path = sb_path.buf; 581 582stat_ref: 583/* 584 * We might have to loop back here to avoid a race 585 * condition: first we lstat() the file, then we try 586 * to read it as a link or as a file. But if somebody 587 * changes the type of the file (file <-> directory 588 * <-> symlink) between the lstat() and reading, then 589 * we don't want to report that as an error but rather 590 * try again starting with the lstat(). 591 * 592 * We'll keep a count of the retries, though, just to avoid 593 * any confusing situation sending us into an infinite loop. 594 */ 595 596if(remaining_retries-- <=0) 597goto out; 598 599if(lstat(path, &st) <0) { 600if(errno != ENOENT) 601goto out; 602if(resolve_packed_ref(refs, refname, sha1, type)) { 603 errno = ENOENT; 604goto out; 605} 606 ret =0; 607goto out; 608} 609 610/* Follow "normalized" - ie "refs/.." symlinks by hand */ 611if(S_ISLNK(st.st_mode)) { 612strbuf_reset(&sb_contents); 613if(strbuf_readlink(&sb_contents, path,0) <0) { 614if(errno == ENOENT || errno == EINVAL) 615/* inconsistent with lstat; retry */ 616goto stat_ref; 617else 618goto out; 619} 620if(starts_with(sb_contents.buf,"refs/") && 621!check_refname_format(sb_contents.buf,0)) { 622strbuf_swap(&sb_contents, referent); 623*type |= REF_ISSYMREF; 624 ret =0; 625goto out; 626} 627/* 628 * It doesn't look like a refname; fall through to just 629 * treating it like a non-symlink, and reading whatever it 630 * points to. 631 */ 632} 633 634/* Is it a directory? */ 635if(S_ISDIR(st.st_mode)) { 636/* 637 * Even though there is a directory where the loose 638 * ref is supposed to be, there could still be a 639 * packed ref: 640 */ 641if(resolve_packed_ref(refs, refname, sha1, type)) { 642 errno = EISDIR; 643goto out; 644} 645 ret =0; 646goto out; 647} 648 649/* 650 * Anything else, just open it and try to use it as 651 * a ref 652 */ 653 fd =open(path, O_RDONLY); 654if(fd <0) { 655if(errno == ENOENT && !S_ISLNK(st.st_mode)) 656/* inconsistent with lstat; retry */ 657goto stat_ref; 658else 659goto out; 660} 661strbuf_reset(&sb_contents); 662if(strbuf_read(&sb_contents, fd,256) <0) { 663int save_errno = errno; 664close(fd); 665 errno = save_errno; 666goto out; 667} 668close(fd); 669strbuf_rtrim(&sb_contents); 670 buf = sb_contents.buf; 671if(starts_with(buf,"ref:")) { 672 buf +=4; 673while(isspace(*buf)) 674 buf++; 675 676strbuf_reset(referent); 677strbuf_addstr(referent, buf); 678*type |= REF_ISSYMREF; 679 ret =0; 680goto out; 681} 682 683/* 684 * Please note that FETCH_HEAD has additional 685 * data after the sha. 686 */ 687if(get_sha1_hex(buf, sha1) || 688(buf[40] !='\0'&& !isspace(buf[40]))) { 689*type |= REF_ISBROKEN; 690 errno = EINVAL; 691goto out; 692} 693 694 ret =0; 695 696out: 697 save_errno = errno; 698strbuf_release(&sb_path); 699strbuf_release(&sb_contents); 700 errno = save_errno; 701return ret; 702} 703 704static voidunlock_ref(struct ref_lock *lock) 705{ 706/* Do not free lock->lk -- atexit() still looks at them */ 707if(lock->lk) 708rollback_lock_file(lock->lk); 709free(lock->ref_name); 710free(lock); 711} 712 713/* 714 * Lock refname, without following symrefs, and set *lock_p to point 715 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 716 * and type similarly to read_raw_ref(). 717 * 718 * The caller must verify that refname is a "safe" reference name (in 719 * the sense of refname_is_safe()) before calling this function. 720 * 721 * If the reference doesn't already exist, verify that refname doesn't 722 * have a D/F conflict with any existing references. extras and skip 723 * are passed to refs_verify_refname_available() for this check. 724 * 725 * If mustexist is not set and the reference is not found or is 726 * broken, lock the reference anyway but clear sha1. 727 * 728 * Return 0 on success. On failure, write an error message to err and 729 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 730 * 731 * Implementation note: This function is basically 732 * 733 * lock reference 734 * read_raw_ref() 735 * 736 * but it includes a lot more code to 737 * - Deal with possible races with other processes 738 * - Avoid calling refs_verify_refname_available() when it can be 739 * avoided, namely if we were successfully able to read the ref 740 * - Generate informative error messages in the case of failure 741 */ 742static intlock_raw_ref(struct files_ref_store *refs, 743const char*refname,int mustexist, 744const struct string_list *extras, 745const struct string_list *skip, 746struct ref_lock **lock_p, 747struct strbuf *referent, 748unsigned int*type, 749struct strbuf *err) 750{ 751struct ref_lock *lock; 752struct strbuf ref_file = STRBUF_INIT; 753int attempts_remaining =3; 754int ret = TRANSACTION_GENERIC_ERROR; 755 756assert(err); 757files_assert_main_repository(refs,"lock_raw_ref"); 758 759*type =0; 760 761/* First lock the file so it can't change out from under us. */ 762 763*lock_p = lock =xcalloc(1,sizeof(*lock)); 764 765 lock->ref_name =xstrdup(refname); 766files_ref_path(refs, &ref_file, refname); 767 768retry: 769switch(safe_create_leading_directories(ref_file.buf)) { 770case SCLD_OK: 771break;/* success */ 772case SCLD_EXISTS: 773/* 774 * Suppose refname is "refs/foo/bar". We just failed 775 * to create the containing directory, "refs/foo", 776 * because there was a non-directory in the way. This 777 * indicates a D/F conflict, probably because of 778 * another reference such as "refs/foo". There is no 779 * reason to expect this error to be transitory. 780 */ 781if(refs_verify_refname_available(&refs->base, refname, 782 extras, skip, err)) { 783if(mustexist) { 784/* 785 * To the user the relevant error is 786 * that the "mustexist" reference is 787 * missing: 788 */ 789strbuf_reset(err); 790strbuf_addf(err,"unable to resolve reference '%s'", 791 refname); 792}else{ 793/* 794 * The error message set by 795 * refs_verify_refname_available() is 796 * OK. 797 */ 798 ret = TRANSACTION_NAME_CONFLICT; 799} 800}else{ 801/* 802 * The file that is in the way isn't a loose 803 * reference. Report it as a low-level 804 * failure. 805 */ 806strbuf_addf(err,"unable to create lock file%s.lock; " 807"non-directory in the way", 808 ref_file.buf); 809} 810goto error_return; 811case SCLD_VANISHED: 812/* Maybe another process was tidying up. Try again. */ 813if(--attempts_remaining >0) 814goto retry; 815/* fall through */ 816default: 817strbuf_addf(err,"unable to create directory for%s", 818 ref_file.buf); 819goto error_return; 820} 821 822if(!lock->lk) 823 lock->lk =xcalloc(1,sizeof(struct lock_file)); 824 825if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 826if(errno == ENOENT && --attempts_remaining >0) { 827/* 828 * Maybe somebody just deleted one of the 829 * directories leading to ref_file. Try 830 * again: 831 */ 832goto retry; 833}else{ 834unable_to_lock_message(ref_file.buf, errno, err); 835goto error_return; 836} 837} 838 839/* 840 * Now we hold the lock and can read the reference without 841 * fear that its value will change. 842 */ 843 844if(files_read_raw_ref(&refs->base, refname, 845 lock->old_oid.hash, referent, type)) { 846if(errno == ENOENT) { 847if(mustexist) { 848/* Garden variety missing reference. */ 849strbuf_addf(err,"unable to resolve reference '%s'", 850 refname); 851goto error_return; 852}else{ 853/* 854 * Reference is missing, but that's OK. We 855 * know that there is not a conflict with 856 * another loose reference because 857 * (supposing that we are trying to lock 858 * reference "refs/foo/bar"): 859 * 860 * - We were successfully able to create 861 * the lockfile refs/foo/bar.lock, so we 862 * know there cannot be a loose reference 863 * named "refs/foo". 864 * 865 * - We got ENOENT and not EISDIR, so we 866 * know that there cannot be a loose 867 * reference named "refs/foo/bar/baz". 868 */ 869} 870}else if(errno == EISDIR) { 871/* 872 * There is a directory in the way. It might have 873 * contained references that have been deleted. If 874 * we don't require that the reference already 875 * exists, try to remove the directory so that it 876 * doesn't cause trouble when we want to rename the 877 * lockfile into place later. 878 */ 879if(mustexist) { 880/* Garden variety missing reference. */ 881strbuf_addf(err,"unable to resolve reference '%s'", 882 refname); 883goto error_return; 884}else if(remove_dir_recursively(&ref_file, 885 REMOVE_DIR_EMPTY_ONLY)) { 886if(refs_verify_refname_available( 887&refs->base, refname, 888 extras, skip, err)) { 889/* 890 * The error message set by 891 * verify_refname_available() is OK. 892 */ 893 ret = TRANSACTION_NAME_CONFLICT; 894goto error_return; 895}else{ 896/* 897 * We can't delete the directory, 898 * but we also don't know of any 899 * references that it should 900 * contain. 901 */ 902strbuf_addf(err,"there is a non-empty directory '%s' " 903"blocking reference '%s'", 904 ref_file.buf, refname); 905goto error_return; 906} 907} 908}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 909strbuf_addf(err,"unable to resolve reference '%s': " 910"reference broken", refname); 911goto error_return; 912}else{ 913strbuf_addf(err,"unable to resolve reference '%s':%s", 914 refname,strerror(errno)); 915goto error_return; 916} 917 918/* 919 * If the ref did not exist and we are creating it, 920 * make sure there is no existing ref that conflicts 921 * with refname: 922 */ 923if(refs_verify_refname_available( 924&refs->base, refname, 925 extras, skip, err)) 926goto error_return; 927} 928 929 ret =0; 930goto out; 931 932error_return: 933unlock_ref(lock); 934*lock_p = NULL; 935 936out: 937strbuf_release(&ref_file); 938return ret; 939} 940 941static intfiles_peel_ref(struct ref_store *ref_store, 942const char*refname,unsigned char*sha1) 943{ 944struct files_ref_store *refs = 945files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 946"peel_ref"); 947int flag; 948unsigned char base[20]; 949 950if(current_ref_iter && current_ref_iter->refname == refname) { 951struct object_id peeled; 952 953if(ref_iterator_peel(current_ref_iter, &peeled)) 954return-1; 955hashcpy(sha1, peeled.hash); 956return0; 957} 958 959if(refs_read_ref_full(ref_store, refname, 960 RESOLVE_REF_READING, base, &flag)) 961return-1; 962 963/* 964 * If the reference is packed, read its ref_entry from the 965 * cache in the hope that we already know its peeled value. 966 * We only try this optimization on packed references because 967 * (a) forcing the filling of the loose reference cache could 968 * be expensive and (b) loose references anyway usually do not 969 * have REF_KNOWS_PEELED. 970 */ 971if(flag & REF_ISPACKED) { 972struct ref_entry *r =get_packed_ref(refs, refname); 973if(r) { 974if(peel_entry(r,0)) 975return-1; 976hashcpy(sha1, r->u.value.peeled.hash); 977return0; 978} 979} 980 981returnpeel_object(base, sha1); 982} 983 984struct files_ref_iterator { 985struct ref_iterator base; 986 987struct packed_ref_cache *packed_ref_cache; 988struct ref_iterator *iter0; 989unsigned int flags; 990}; 991 992static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 993{ 994struct files_ref_iterator *iter = 995(struct files_ref_iterator *)ref_iterator; 996int ok; 997 998while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 999if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1000ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1001continue;10021003if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1004!ref_resolves_to_object(iter->iter0->refname,1005 iter->iter0->oid,1006 iter->iter0->flags))1007continue;10081009 iter->base.refname = iter->iter0->refname;1010 iter->base.oid = iter->iter0->oid;1011 iter->base.flags = iter->iter0->flags;1012return ITER_OK;1013}10141015 iter->iter0 = NULL;1016if(ref_iterator_abort(ref_iterator) != ITER_DONE)1017 ok = ITER_ERROR;10181019return ok;1020}10211022static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1023struct object_id *peeled)1024{1025struct files_ref_iterator *iter =1026(struct files_ref_iterator *)ref_iterator;10271028returnref_iterator_peel(iter->iter0, peeled);1029}10301031static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1032{1033struct files_ref_iterator *iter =1034(struct files_ref_iterator *)ref_iterator;1035int ok = ITER_DONE;10361037if(iter->iter0)1038 ok =ref_iterator_abort(iter->iter0);10391040release_packed_ref_cache(iter->packed_ref_cache);1041base_ref_iterator_free(ref_iterator);1042return ok;1043}10441045static struct ref_iterator_vtable files_ref_iterator_vtable = {1046 files_ref_iterator_advance,1047 files_ref_iterator_peel,1048 files_ref_iterator_abort1049};10501051static struct ref_iterator *files_ref_iterator_begin(1052struct ref_store *ref_store,1053const char*prefix,unsigned int flags)1054{1055struct files_ref_store *refs;1056struct ref_iterator *loose_iter, *packed_iter;1057struct files_ref_iterator *iter;1058struct ref_iterator *ref_iterator;10591060if(ref_paranoia <0)1061 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1062if(ref_paranoia)1063 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10641065 refs =files_downcast(ref_store,1066 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1067"ref_iterator_begin");10681069 iter =xcalloc(1,sizeof(*iter));1070 ref_iterator = &iter->base;1071base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10721073/*1074 * We must make sure that all loose refs are read before1075 * accessing the packed-refs file; this avoids a race1076 * condition if loose refs are migrated to the packed-refs1077 * file by a simultaneous process, but our in-memory view is1078 * from before the migration. We ensure this as follows:1079 * First, we call start the loose refs iteration with its1080 * `prime_ref` argument set to true. This causes the loose1081 * references in the subtree to be pre-read into the cache.1082 * (If they've already been read, that's OK; we only need to1083 * guarantee that they're read before the packed refs, not1084 * *how much* before.) After that, we call1085 * get_packed_ref_cache(), which internally checks whether the1086 * packed-ref cache is up to date with what is on disk, and1087 * re-reads it if not.1088 */10891090 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1091 prefix,1);10921093 iter->packed_ref_cache =get_packed_ref_cache(refs);1094acquire_packed_ref_cache(iter->packed_ref_cache);1095 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1096 prefix,0);10971098 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1099 iter->flags = flags;11001101return ref_iterator;1102}11031104/*1105 * Verify that the reference locked by lock has the value old_sha1.1106 * Fail if the reference doesn't exist and mustexist is set. Return 01107 * on success. On error, write an error message to err, set errno, and1108 * return a negative value.1109 */1110static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1111const unsigned char*old_sha1,int mustexist,1112struct strbuf *err)1113{1114assert(err);11151116if(refs_read_ref_full(ref_store, lock->ref_name,1117 mustexist ? RESOLVE_REF_READING :0,1118 lock->old_oid.hash, NULL)) {1119if(old_sha1) {1120int save_errno = errno;1121strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1122 errno = save_errno;1123return-1;1124}else{1125oidclr(&lock->old_oid);1126return0;1127}1128}1129if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1130strbuf_addf(err,"ref '%s' is at%sbut expected%s",1131 lock->ref_name,1132oid_to_hex(&lock->old_oid),1133sha1_to_hex(old_sha1));1134 errno = EBUSY;1135return-1;1136}1137return0;1138}11391140static intremove_empty_directories(struct strbuf *path)1141{1142/*1143 * we want to create a file but there is a directory there;1144 * if that is an empty directory (or a directory that contains1145 * only empty directories), remove them.1146 */1147returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1148}11491150static intcreate_reflock(const char*path,void*cb)1151{1152struct lock_file *lk = cb;11531154returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1155}11561157/*1158 * Locks a ref returning the lock on success and NULL on failure.1159 * On failure errno is set to something meaningful.1160 */1161static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1162const char*refname,1163const unsigned char*old_sha1,1164const struct string_list *extras,1165const struct string_list *skip,1166unsigned int flags,int*type,1167struct strbuf *err)1168{1169struct strbuf ref_file = STRBUF_INIT;1170struct ref_lock *lock;1171int last_errno =0;1172int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1173int resolve_flags = RESOLVE_REF_NO_RECURSE;1174int resolved;11751176files_assert_main_repository(refs,"lock_ref_sha1_basic");1177assert(err);11781179 lock =xcalloc(1,sizeof(struct ref_lock));11801181if(mustexist)1182 resolve_flags |= RESOLVE_REF_READING;1183if(flags & REF_DELETING)1184 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11851186files_ref_path(refs, &ref_file, refname);1187 resolved = !!refs_resolve_ref_unsafe(&refs->base,1188 refname, resolve_flags,1189 lock->old_oid.hash, type);1190if(!resolved && errno == EISDIR) {1191/*1192 * we are trying to lock foo but we used to1193 * have foo/bar which now does not exist;1194 * it is normal for the empty directory 'foo'1195 * to remain.1196 */1197if(remove_empty_directories(&ref_file)) {1198 last_errno = errno;1199if(!refs_verify_refname_available(1200&refs->base,1201 refname, extras, skip, err))1202strbuf_addf(err,"there are still refs under '%s'",1203 refname);1204goto error_return;1205}1206 resolved = !!refs_resolve_ref_unsafe(&refs->base,1207 refname, resolve_flags,1208 lock->old_oid.hash, type);1209}1210if(!resolved) {1211 last_errno = errno;1212if(last_errno != ENOTDIR ||1213!refs_verify_refname_available(&refs->base, refname,1214 extras, skip, err))1215strbuf_addf(err,"unable to resolve reference '%s':%s",1216 refname,strerror(last_errno));12171218goto error_return;1219}12201221/*1222 * If the ref did not exist and we are creating it, make sure1223 * there is no existing packed ref whose name begins with our1224 * refname, nor a packed ref whose name is a proper prefix of1225 * our refname.1226 */1227if(is_null_oid(&lock->old_oid) &&1228refs_verify_refname_available(&refs->base, refname,1229 extras, skip, err)) {1230 last_errno = ENOTDIR;1231goto error_return;1232}12331234 lock->lk =xcalloc(1,sizeof(struct lock_file));12351236 lock->ref_name =xstrdup(refname);12371238if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1239 last_errno = errno;1240unable_to_lock_message(ref_file.buf, errno, err);1241goto error_return;1242}12431244if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1245 last_errno = errno;1246goto error_return;1247}1248goto out;12491250 error_return:1251unlock_ref(lock);1252 lock = NULL;12531254 out:1255strbuf_release(&ref_file);1256 errno = last_errno;1257return lock;1258}12591260/*1261 * Write an entry to the packed-refs file for the specified refname.1262 * If peeled is non-NULL, write it as the entry's peeled value.1263 */1264static voidwrite_packed_entry(FILE*fh,const char*refname,1265const unsigned char*sha1,1266const unsigned char*peeled)1267{1268fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1269if(peeled)1270fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1271}12721273/*1274 * Lock the packed-refs file for writing. Flags is passed to1275 * hold_lock_file_for_update(). Return 0 on success. On errors, set1276 * errno appropriately and return a nonzero value.1277 */1278static intlock_packed_refs(struct files_ref_store *refs,int flags)1279{1280static int timeout_configured =0;1281static int timeout_value =1000;1282struct packed_ref_cache *packed_ref_cache;12831284files_assert_main_repository(refs,"lock_packed_refs");12851286if(!timeout_configured) {1287git_config_get_int("core.packedrefstimeout", &timeout_value);1288 timeout_configured =1;1289}12901291if(hold_lock_file_for_update_timeout(1292&refs->packed_refs_lock,files_packed_refs_path(refs),1293 flags, timeout_value) <0)1294return-1;1295/*1296 * Get the current packed-refs while holding the lock. It is1297 * important that we call `get_packed_ref_cache()` before1298 * setting `packed_ref_cache->lock`, because otherwise the1299 * former will see that the file is locked and assume that the1300 * cache can't be stale.1301 */1302 packed_ref_cache =get_packed_ref_cache(refs);1303/* Increment the reference count to prevent it from being freed: */1304acquire_packed_ref_cache(packed_ref_cache);1305return0;1306}13071308/*1309 * Write the current version of the packed refs cache from memory to1310 * disk. The packed-refs file must already be locked for writing (see1311 * lock_packed_refs()). Return zero on success. On errors, set errno1312 * and return a nonzero value1313 */1314static intcommit_packed_refs(struct files_ref_store *refs)1315{1316struct packed_ref_cache *packed_ref_cache =1317get_packed_ref_cache(refs);1318int ok, error =0;1319int save_errno =0;1320FILE*out;1321struct ref_iterator *iter;13221323files_assert_main_repository(refs,"commit_packed_refs");13241325if(!is_lock_file_locked(&refs->packed_refs_lock))1326die("BUG: packed-refs not locked");13271328 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1329if(!out)1330die_errno("unable to fdopen packed-refs descriptor");13311332fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13331334 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1335while((ok =ref_iterator_advance(iter)) == ITER_OK) {1336struct object_id peeled;1337int peel_error =ref_iterator_peel(iter, &peeled);13381339write_packed_entry(out, iter->refname, iter->oid->hash,1340 peel_error ? NULL : peeled.hash);1341}13421343if(ok != ITER_DONE)1344die("error while iterating over references");13451346if(commit_lock_file(&refs->packed_refs_lock)) {1347 save_errno = errno;1348 error = -1;1349}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(!is_lock_file_locked(&refs->packed_refs_lock))1368die("BUG: packed-refs not locked");1369rollback_lock_file(&refs->packed_refs_lock);1370release_packed_ref_cache(packed_ref_cache);1371clear_packed_ref_cache(refs);1372}13731374struct ref_to_prune {1375struct ref_to_prune *next;1376unsigned char sha1[20];1377char name[FLEX_ARRAY];1378};13791380enum{1381 REMOVE_EMPTY_PARENTS_REF =0x01,1382 REMOVE_EMPTY_PARENTS_REFLOG =0x021383};13841385/*1386 * Remove empty parent directories associated with the specified1387 * reference and/or its reflog, but spare [logs/]refs/ and immediate1388 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1389 * REMOVE_EMPTY_PARENTS_REFLOG.1390 */1391static voidtry_remove_empty_parents(struct files_ref_store *refs,1392const char*refname,1393unsigned int flags)1394{1395struct strbuf buf = STRBUF_INIT;1396struct strbuf sb = STRBUF_INIT;1397char*p, *q;1398int i;13991400strbuf_addstr(&buf, refname);1401 p = buf.buf;1402for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1403while(*p && *p !='/')1404 p++;1405/* tolerate duplicate slashes; see check_refname_format() */1406while(*p =='/')1407 p++;1408}1409 q = buf.buf + buf.len;1410while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1411while(q > p && *q !='/')1412 q--;1413while(q > p && *(q-1) =='/')1414 q--;1415if(q == p)1416break;1417strbuf_setlen(&buf, q - buf.buf);14181419strbuf_reset(&sb);1420files_ref_path(refs, &sb, buf.buf);1421if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1422 flags &= ~REMOVE_EMPTY_PARENTS_REF;14231424strbuf_reset(&sb);1425files_reflog_path(refs, &sb, buf.buf);1426if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1427 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1428}1429strbuf_release(&buf);1430strbuf_release(&sb);1431}14321433/* make sure nobody touched the ref, and unlink */1434static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1435{1436struct ref_transaction *transaction;1437struct strbuf err = STRBUF_INIT;14381439if(check_refname_format(r->name,0))1440return;14411442 transaction =ref_store_transaction_begin(&refs->base, &err);1443if(!transaction ||1444ref_transaction_delete(transaction, r->name, r->sha1,1445 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1446ref_transaction_commit(transaction, &err)) {1447ref_transaction_free(transaction);1448error("%s", err.buf);1449strbuf_release(&err);1450return;1451}1452ref_transaction_free(transaction);1453strbuf_release(&err);1454}14551456static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1457{1458while(r) {1459prune_ref(refs, r);1460 r = r->next;1461}1462}14631464/*1465 * Return true if the specified reference should be packed.1466 */1467static intshould_pack_ref(const char*refname,1468const struct object_id *oid,unsigned int ref_flags,1469unsigned int pack_flags)1470{1471/* Do not pack per-worktree refs: */1472if(ref_type(refname) != REF_TYPE_NORMAL)1473return0;14741475/* Do not pack non-tags unless PACK_REFS_ALL is set: */1476if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1477return0;14781479/* Do not pack symbolic refs: */1480if(ref_flags & REF_ISSYMREF)1481return0;14821483/* Do not pack broken refs: */1484if(!ref_resolves_to_object(refname, oid, ref_flags))1485return0;14861487return1;1488}14891490static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1491{1492struct files_ref_store *refs =1493files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1494"pack_refs");1495struct ref_iterator *iter;1496struct ref_dir *packed_refs;1497int ok;1498struct ref_to_prune *refs_to_prune = NULL;14991500lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1501 packed_refs =get_packed_refs(refs);15021503 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1504while((ok =ref_iterator_advance(iter)) == ITER_OK) {1505/*1506 * If the loose reference can be packed, add an entry1507 * in the packed ref cache. If the reference should be1508 * pruned, also add it to refs_to_prune.1509 */1510struct ref_entry *packed_entry;15111512if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1513 flags))1514continue;15151516/*1517 * Create an entry in the packed-refs cache equivalent1518 * to the one from the loose ref cache, except that1519 * we don't copy the peeled status, because we want it1520 * to be re-peeled.1521 */1522 packed_entry =find_ref_entry(packed_refs, iter->refname);1523if(packed_entry) {1524/* Overwrite existing packed entry with info from loose entry */1525 packed_entry->flag = REF_ISPACKED;1526oidcpy(&packed_entry->u.value.oid, iter->oid);1527}else{1528 packed_entry =create_ref_entry(iter->refname, iter->oid,1529 REF_ISPACKED,0);1530add_ref_entry(packed_refs, packed_entry);1531}1532oidclr(&packed_entry->u.value.peeled);15331534/* Schedule the loose reference for pruning if requested. */1535if((flags & PACK_REFS_PRUNE)) {1536struct ref_to_prune *n;1537FLEX_ALLOC_STR(n, name, iter->refname);1538hashcpy(n->sha1, iter->oid->hash);1539 n->next = refs_to_prune;1540 refs_to_prune = n;1541}1542}1543if(ok != ITER_DONE)1544die("error while iterating over references");15451546if(commit_packed_refs(refs))1547die_errno("unable to overwrite old ref-pack file");15481549prune_refs(refs, refs_to_prune);1550return0;1551}15521553/*1554 * Rewrite the packed-refs file, omitting any refs listed in1555 * 'refnames'. On error, leave packed-refs unchanged, write an error1556 * message to 'err', and return a nonzero value.1557 *1558 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1559 */1560static intrepack_without_refs(struct files_ref_store *refs,1561struct string_list *refnames,struct strbuf *err)1562{1563struct ref_dir *packed;1564struct string_list_item *refname;1565int ret, needs_repacking =0, removed =0;15661567files_assert_main_repository(refs,"repack_without_refs");1568assert(err);15691570/* Look for a packed ref */1571for_each_string_list_item(refname, refnames) {1572if(get_packed_ref(refs, refname->string)) {1573 needs_repacking =1;1574break;1575}1576}15771578/* Avoid locking if we have nothing to do */1579if(!needs_repacking)1580return0;/* no refname exists in packed refs */15811582if(lock_packed_refs(refs,0)) {1583unable_to_lock_message(files_packed_refs_path(refs), errno, err);1584return-1;1585}1586 packed =get_packed_refs(refs);15871588/* Remove refnames from the cache */1589for_each_string_list_item(refname, refnames)1590if(remove_entry_from_dir(packed, refname->string) != -1)1591 removed =1;1592if(!removed) {1593/*1594 * All packed entries disappeared while we were1595 * acquiring the lock.1596 */1597rollback_packed_refs(refs);1598return0;1599}16001601/* Write what remains */1602 ret =commit_packed_refs(refs);1603if(ret)1604strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1605strerror(errno));1606return ret;1607}16081609static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1610struct string_list *refnames,unsigned int flags)1611{1612struct files_ref_store *refs =1613files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1614struct strbuf err = STRBUF_INIT;1615int i, result =0;16161617if(!refnames->nr)1618return0;16191620 result =repack_without_refs(refs, refnames, &err);1621if(result) {1622/*1623 * If we failed to rewrite the packed-refs file, then1624 * it is unsafe to try to remove loose refs, because1625 * doing so might expose an obsolete packed value for1626 * a reference that might even point at an object that1627 * has been garbage collected.1628 */1629if(refnames->nr ==1)1630error(_("could not delete reference%s:%s"),1631 refnames->items[0].string, err.buf);1632else1633error(_("could not delete references:%s"), err.buf);16341635goto out;1636}16371638for(i =0; i < refnames->nr; i++) {1639const char*refname = refnames->items[i].string;16401641if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1642 result |=error(_("could not remove reference%s"), refname);1643}16441645out:1646strbuf_release(&err);1647return result;1648}16491650/*1651 * People using contrib's git-new-workdir have .git/logs/refs ->1652 * /some/other/path/.git/logs/refs, and that may live on another device.1653 *1654 * IOW, to avoid cross device rename errors, the temporary renamed log must1655 * live into logs/refs.1656 */1657#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16581659struct rename_cb {1660const char*tmp_renamed_log;1661int true_errno;1662};16631664static intrename_tmp_log_callback(const char*path,void*cb_data)1665{1666struct rename_cb *cb = cb_data;16671668if(rename(cb->tmp_renamed_log, path)) {1669/*1670 * rename(a, b) when b is an existing directory ought1671 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1672 * Sheesh. Record the true errno for error reporting,1673 * but report EISDIR to raceproof_create_file() so1674 * that it knows to retry.1675 */1676 cb->true_errno = errno;1677if(errno == ENOTDIR)1678 errno = EISDIR;1679return-1;1680}else{1681return0;1682}1683}16841685static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1686{1687struct strbuf path = STRBUF_INIT;1688struct strbuf tmp = STRBUF_INIT;1689struct rename_cb cb;1690int ret;16911692files_reflog_path(refs, &path, newrefname);1693files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1694 cb.tmp_renamed_log = tmp.buf;1695 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1696if(ret) {1697if(errno == EISDIR)1698error("directory not empty:%s", path.buf);1699else1700error("unable to move logfile%sto%s:%s",1701 tmp.buf, path.buf,1702strerror(cb.true_errno));1703}17041705strbuf_release(&path);1706strbuf_release(&tmp);1707return ret;1708}17091710static intwrite_ref_to_lockfile(struct ref_lock *lock,1711const struct object_id *oid,struct strbuf *err);1712static intcommit_ref_update(struct files_ref_store *refs,1713struct ref_lock *lock,1714const struct object_id *oid,const char*logmsg,1715struct strbuf *err);17161717static intfiles_rename_ref(struct ref_store *ref_store,1718const char*oldrefname,const char*newrefname,1719const char*logmsg)1720{1721struct files_ref_store *refs =1722files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1723struct object_id oid, orig_oid;1724int flag =0, logmoved =0;1725struct ref_lock *lock;1726struct stat loginfo;1727struct strbuf sb_oldref = STRBUF_INIT;1728struct strbuf sb_newref = STRBUF_INIT;1729struct strbuf tmp_renamed_log = STRBUF_INIT;1730int log, ret;1731struct strbuf err = STRBUF_INIT;17321733files_reflog_path(refs, &sb_oldref, oldrefname);1734files_reflog_path(refs, &sb_newref, newrefname);1735files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17361737 log = !lstat(sb_oldref.buf, &loginfo);1738if(log &&S_ISLNK(loginfo.st_mode)) {1739 ret =error("reflog for%sis a symlink", oldrefname);1740goto out;1741}17421743if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1744 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1745 orig_oid.hash, &flag)) {1746 ret =error("refname%snot found", oldrefname);1747goto out;1748}17491750if(flag & REF_ISSYMREF) {1751 ret =error("refname%sis a symbolic ref, renaming it is not supported",1752 oldrefname);1753goto out;1754}1755if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1756 ret =1;1757goto out;1758}17591760if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1761 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1762 oldrefname,strerror(errno));1763goto out;1764}17651766if(refs_delete_ref(&refs->base, logmsg, oldrefname,1767 orig_oid.hash, REF_NODEREF)) {1768error("unable to delete old%s", oldrefname);1769goto rollback;1770}17711772/*1773 * Since we are doing a shallow lookup, oid is not the1774 * correct value to pass to delete_ref as old_oid. But that1775 * doesn't matter, because an old_oid check wouldn't add to1776 * the safety anyway; we want to delete the reference whatever1777 * its current value.1778 */1779if(!refs_read_ref_full(&refs->base, newrefname,1780 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1781 oid.hash, NULL) &&1782refs_delete_ref(&refs->base, NULL, newrefname,1783 NULL, REF_NODEREF)) {1784if(errno == EISDIR) {1785struct strbuf path = STRBUF_INIT;1786int result;17871788files_ref_path(refs, &path, newrefname);1789 result =remove_empty_directories(&path);1790strbuf_release(&path);17911792if(result) {1793error("Directory not empty:%s", newrefname);1794goto rollback;1795}1796}else{1797error("unable to delete existing%s", newrefname);1798goto rollback;1799}1800}18011802if(log &&rename_tmp_log(refs, newrefname))1803goto rollback;18041805 logmoved = log;18061807 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1808 REF_NODEREF, NULL, &err);1809if(!lock) {1810error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1811strbuf_release(&err);1812goto rollback;1813}1814oidcpy(&lock->old_oid, &orig_oid);18151816if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1817commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1818error("unable to write current sha1 into%s:%s", newrefname, err.buf);1819strbuf_release(&err);1820goto rollback;1821}18221823 ret =0;1824goto out;18251826 rollback:1827 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1828 REF_NODEREF, NULL, &err);1829if(!lock) {1830error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1831strbuf_release(&err);1832goto rollbacklog;1833}18341835 flag = log_all_ref_updates;1836 log_all_ref_updates = LOG_REFS_NONE;1837if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1838commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1839error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1840strbuf_release(&err);1841}1842 log_all_ref_updates = flag;18431844 rollbacklog:1845if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1846error("unable to restore logfile%sfrom%s:%s",1847 oldrefname, newrefname,strerror(errno));1848if(!logmoved && log &&1849rename(tmp_renamed_log.buf, sb_oldref.buf))1850error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1851 oldrefname,strerror(errno));1852 ret =1;1853 out:1854strbuf_release(&sb_newref);1855strbuf_release(&sb_oldref);1856strbuf_release(&tmp_renamed_log);18571858return ret;1859}18601861static intclose_ref(struct ref_lock *lock)1862{1863if(close_lock_file(lock->lk))1864return-1;1865return0;1866}18671868static intcommit_ref(struct ref_lock *lock)1869{1870char*path =get_locked_file_path(lock->lk);1871struct stat st;18721873if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1874/*1875 * There is a directory at the path we want to rename1876 * the lockfile to. Hopefully it is empty; try to1877 * delete it.1878 */1879size_t len =strlen(path);1880struct strbuf sb_path = STRBUF_INIT;18811882strbuf_attach(&sb_path, path, len, len);18831884/*1885 * If this fails, commit_lock_file() will also fail1886 * and will report the problem.1887 */1888remove_empty_directories(&sb_path);1889strbuf_release(&sb_path);1890}else{1891free(path);1892}18931894if(commit_lock_file(lock->lk))1895return-1;1896return0;1897}18981899static intopen_or_create_logfile(const char*path,void*cb)1900{1901int*fd = cb;19021903*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1904return(*fd <0) ? -1:0;1905}19061907/*1908 * Create a reflog for a ref. If force_create = 0, only create the1909 * reflog for certain refs (those for which should_autocreate_reflog1910 * returns non-zero). Otherwise, create it regardless of the reference1911 * name. If the logfile already existed or was created, return 0 and1912 * set *logfd to the file descriptor opened for appending to the file.1913 * If no logfile exists and we decided not to create one, return 0 and1914 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1915 * return -1.1916 */1917static intlog_ref_setup(struct files_ref_store *refs,1918const char*refname,int force_create,1919int*logfd,struct strbuf *err)1920{1921struct strbuf logfile_sb = STRBUF_INIT;1922char*logfile;19231924files_reflog_path(refs, &logfile_sb, refname);1925 logfile =strbuf_detach(&logfile_sb, NULL);19261927if(force_create ||should_autocreate_reflog(refname)) {1928if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1929if(errno == ENOENT)1930strbuf_addf(err,"unable to create directory for '%s': "1931"%s", logfile,strerror(errno));1932else if(errno == EISDIR)1933strbuf_addf(err,"there are still logs under '%s'",1934 logfile);1935else1936strbuf_addf(err,"unable to append to '%s':%s",1937 logfile,strerror(errno));19381939goto error;1940}1941}else{1942*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1943if(*logfd <0) {1944if(errno == ENOENT || errno == EISDIR) {1945/*1946 * The logfile doesn't already exist,1947 * but that is not an error; it only1948 * means that we won't write log1949 * entries to it.1950 */1951;1952}else{1953strbuf_addf(err,"unable to append to '%s':%s",1954 logfile,strerror(errno));1955goto error;1956}1957}1958}19591960if(*logfd >=0)1961adjust_shared_perm(logfile);19621963free(logfile);1964return0;19651966error:1967free(logfile);1968return-1;1969}19701971static intfiles_create_reflog(struct ref_store *ref_store,1972const char*refname,int force_create,1973struct strbuf *err)1974{1975struct files_ref_store *refs =1976files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1977int fd;19781979if(log_ref_setup(refs, refname, force_create, &fd, err))1980return-1;19811982if(fd >=0)1983close(fd);19841985return0;1986}19871988static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1989const struct object_id *new_oid,1990const char*committer,const char*msg)1991{1992int msglen, written;1993unsigned maxlen, len;1994char*logrec;19951996 msglen = msg ?strlen(msg) :0;1997 maxlen =strlen(committer) + msglen +100;1998 logrec =xmalloc(maxlen);1999 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2000oid_to_hex(old_oid),2001oid_to_hex(new_oid),2002 committer);2003if(msglen)2004 len +=copy_reflog_msg(logrec + len -1, msg) -1;20052006 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2007free(logrec);2008if(written != len)2009return-1;20102011return0;2012}20132014static intfiles_log_ref_write(struct files_ref_store *refs,2015const char*refname,const struct object_id *old_oid,2016const struct object_id *new_oid,const char*msg,2017int flags,struct strbuf *err)2018{2019int logfd, result;20202021if(log_all_ref_updates == LOG_REFS_UNSET)2022 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20232024 result =log_ref_setup(refs, refname,2025 flags & REF_FORCE_CREATE_REFLOG,2026&logfd, err);20272028if(result)2029return result;20302031if(logfd <0)2032return0;2033 result =log_ref_write_fd(logfd, old_oid, new_oid,2034git_committer_info(0), msg);2035if(result) {2036struct strbuf sb = STRBUF_INIT;2037int save_errno = errno;20382039files_reflog_path(refs, &sb, refname);2040strbuf_addf(err,"unable to append to '%s':%s",2041 sb.buf,strerror(save_errno));2042strbuf_release(&sb);2043close(logfd);2044return-1;2045}2046if(close(logfd)) {2047struct strbuf sb = STRBUF_INIT;2048int save_errno = errno;20492050files_reflog_path(refs, &sb, refname);2051strbuf_addf(err,"unable to append to '%s':%s",2052 sb.buf,strerror(save_errno));2053strbuf_release(&sb);2054return-1;2055}2056return0;2057}20582059/*2060 * Write sha1 into the open lockfile, then close the lockfile. On2061 * errors, rollback the lockfile, fill in *err and2062 * return -1.2063 */2064static intwrite_ref_to_lockfile(struct ref_lock *lock,2065const struct object_id *oid,struct strbuf *err)2066{2067static char term ='\n';2068struct object *o;2069int fd;20702071 o =parse_object(oid);2072if(!o) {2073strbuf_addf(err,2074"trying to write ref '%s' with nonexistent object%s",2075 lock->ref_name,oid_to_hex(oid));2076unlock_ref(lock);2077return-1;2078}2079if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2080strbuf_addf(err,2081"trying to write non-commit object%sto branch '%s'",2082oid_to_hex(oid), lock->ref_name);2083unlock_ref(lock);2084return-1;2085}2086 fd =get_lock_file_fd(lock->lk);2087if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2088write_in_full(fd, &term,1) !=1||2089close_ref(lock) <0) {2090strbuf_addf(err,2091"couldn't write '%s'",get_lock_file_path(lock->lk));2092unlock_ref(lock);2093return-1;2094}2095return0;2096}20972098/*2099 * Commit a change to a loose reference that has already been written2100 * to the loose reference lockfile. Also update the reflogs if2101 * necessary, using the specified lockmsg (which can be NULL).2102 */2103static intcommit_ref_update(struct files_ref_store *refs,2104struct ref_lock *lock,2105const struct object_id *oid,const char*logmsg,2106struct strbuf *err)2107{2108files_assert_main_repository(refs,"commit_ref_update");21092110clear_loose_ref_cache(refs);2111if(files_log_ref_write(refs, lock->ref_name,2112&lock->old_oid, oid,2113 logmsg,0, err)) {2114char*old_msg =strbuf_detach(err, NULL);2115strbuf_addf(err,"cannot update the ref '%s':%s",2116 lock->ref_name, old_msg);2117free(old_msg);2118unlock_ref(lock);2119return-1;2120}21212122if(strcmp(lock->ref_name,"HEAD") !=0) {2123/*2124 * Special hack: If a branch is updated directly and HEAD2125 * points to it (may happen on the remote side of a push2126 * for example) then logically the HEAD reflog should be2127 * updated too.2128 * A generic solution implies reverse symref information,2129 * but finding all symrefs pointing to the given branch2130 * would be rather costly for this rare event (the direct2131 * update of a branch) to be worth it. So let's cheat and2132 * check with HEAD only which should cover 99% of all usage2133 * scenarios (even 100% of the default ones).2134 */2135struct object_id head_oid;2136int head_flag;2137const char*head_ref;21382139 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2140 RESOLVE_REF_READING,2141 head_oid.hash, &head_flag);2142if(head_ref && (head_flag & REF_ISSYMREF) &&2143!strcmp(head_ref, lock->ref_name)) {2144struct strbuf log_err = STRBUF_INIT;2145if(files_log_ref_write(refs,"HEAD",2146&lock->old_oid, oid,2147 logmsg,0, &log_err)) {2148error("%s", log_err.buf);2149strbuf_release(&log_err);2150}2151}2152}21532154if(commit_ref(lock)) {2155strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2156unlock_ref(lock);2157return-1;2158}21592160unlock_ref(lock);2161return0;2162}21632164static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2165{2166int ret = -1;2167#ifndef NO_SYMLINK_HEAD2168char*ref_path =get_locked_file_path(lock->lk);2169unlink(ref_path);2170 ret =symlink(target, ref_path);2171free(ref_path);21722173if(ret)2174fprintf(stderr,"no symlink - falling back to symbolic ref\n");2175#endif2176return ret;2177}21782179static voidupdate_symref_reflog(struct files_ref_store *refs,2180struct ref_lock *lock,const char*refname,2181const char*target,const char*logmsg)2182{2183struct strbuf err = STRBUF_INIT;2184struct object_id new_oid;2185if(logmsg &&2186!refs_read_ref_full(&refs->base, target,2187 RESOLVE_REF_READING, new_oid.hash, NULL) &&2188files_log_ref_write(refs, refname, &lock->old_oid,2189&new_oid, logmsg,0, &err)) {2190error("%s", err.buf);2191strbuf_release(&err);2192}2193}21942195static intcreate_symref_locked(struct files_ref_store *refs,2196struct ref_lock *lock,const char*refname,2197const char*target,const char*logmsg)2198{2199if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2200update_symref_reflog(refs, lock, refname, target, logmsg);2201return0;2202}22032204if(!fdopen_lock_file(lock->lk,"w"))2205returnerror("unable to fdopen%s:%s",2206 lock->lk->tempfile.filename.buf,strerror(errno));22072208update_symref_reflog(refs, lock, refname, target, logmsg);22092210/* no error check; commit_ref will check ferror */2211fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2212if(commit_ref(lock) <0)2213returnerror("unable to write symref for%s:%s", refname,2214strerror(errno));2215return0;2216}22172218static intfiles_create_symref(struct ref_store *ref_store,2219const char*refname,const char*target,2220const char*logmsg)2221{2222struct files_ref_store *refs =2223files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2224struct strbuf err = STRBUF_INIT;2225struct ref_lock *lock;2226int ret;22272228 lock =lock_ref_sha1_basic(refs, refname, NULL,2229 NULL, NULL, REF_NODEREF, NULL,2230&err);2231if(!lock) {2232error("%s", err.buf);2233strbuf_release(&err);2234return-1;2235}22362237 ret =create_symref_locked(refs, lock, refname, target, logmsg);2238unlock_ref(lock);2239return ret;2240}22412242static intfiles_reflog_exists(struct ref_store *ref_store,2243const char*refname)2244{2245struct files_ref_store *refs =2246files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2247struct strbuf sb = STRBUF_INIT;2248struct stat st;2249int ret;22502251files_reflog_path(refs, &sb, refname);2252 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2253strbuf_release(&sb);2254return ret;2255}22562257static intfiles_delete_reflog(struct ref_store *ref_store,2258const char*refname)2259{2260struct files_ref_store *refs =2261files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2262struct strbuf sb = STRBUF_INIT;2263int ret;22642265files_reflog_path(refs, &sb, refname);2266 ret =remove_path(sb.buf);2267strbuf_release(&sb);2268return ret;2269}22702271static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2272{2273struct object_id ooid, noid;2274char*email_end, *message;2275 timestamp_t timestamp;2276int tz;2277const char*p = sb->buf;22782279/* old SP new SP name <email> SP time TAB msg LF */2280if(!sb->len || sb->buf[sb->len -1] !='\n'||2281parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2282parse_oid_hex(p, &noid, &p) || *p++ !=' '||2283!(email_end =strchr(p,'>')) ||2284 email_end[1] !=' '||2285!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2286!message || message[0] !=' '||2287(message[1] !='+'&& message[1] !='-') ||2288!isdigit(message[2]) || !isdigit(message[3]) ||2289!isdigit(message[4]) || !isdigit(message[5]))2290return0;/* corrupt? */2291 email_end[1] ='\0';2292 tz =strtol(message +1, NULL,10);2293if(message[6] !='\t')2294 message +=6;2295else2296 message +=7;2297returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2298}22992300static char*find_beginning_of_line(char*bob,char*scan)2301{2302while(bob < scan && *(--scan) !='\n')2303;/* keep scanning backwards */2304/*2305 * Return either beginning of the buffer, or LF at the end of2306 * the previous line.2307 */2308return scan;2309}23102311static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2312const char*refname,2313 each_reflog_ent_fn fn,2314void*cb_data)2315{2316struct files_ref_store *refs =2317files_downcast(ref_store, REF_STORE_READ,2318"for_each_reflog_ent_reverse");2319struct strbuf sb = STRBUF_INIT;2320FILE*logfp;2321long pos;2322int ret =0, at_tail =1;23232324files_reflog_path(refs, &sb, refname);2325 logfp =fopen(sb.buf,"r");2326strbuf_release(&sb);2327if(!logfp)2328return-1;23292330/* Jump to the end */2331if(fseek(logfp,0, SEEK_END) <0)2332 ret =error("cannot seek back reflog for%s:%s",2333 refname,strerror(errno));2334 pos =ftell(logfp);2335while(!ret &&0< pos) {2336int cnt;2337size_t nread;2338char buf[BUFSIZ];2339char*endp, *scanp;23402341/* Fill next block from the end */2342 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2343if(fseek(logfp, pos - cnt, SEEK_SET)) {2344 ret =error("cannot seek back reflog for%s:%s",2345 refname,strerror(errno));2346break;2347}2348 nread =fread(buf, cnt,1, logfp);2349if(nread !=1) {2350 ret =error("cannot read%dbytes from reflog for%s:%s",2351 cnt, refname,strerror(errno));2352break;2353}2354 pos -= cnt;23552356 scanp = endp = buf + cnt;2357if(at_tail && scanp[-1] =='\n')2358/* Looking at the final LF at the end of the file */2359 scanp--;2360 at_tail =0;23612362while(buf < scanp) {2363/*2364 * terminating LF of the previous line, or the beginning2365 * of the buffer.2366 */2367char*bp;23682369 bp =find_beginning_of_line(buf, scanp);23702371if(*bp =='\n') {2372/*2373 * The newline is the end of the previous line,2374 * so we know we have complete line starting2375 * at (bp + 1). Prefix it onto any prior data2376 * we collected for the line and process it.2377 */2378strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2379 scanp = bp;2380 endp = bp +1;2381 ret =show_one_reflog_ent(&sb, fn, cb_data);2382strbuf_reset(&sb);2383if(ret)2384break;2385}else if(!pos) {2386/*2387 * We are at the start of the buffer, and the2388 * start of the file; there is no previous2389 * line, and we have everything for this one.2390 * Process it, and we can end the loop.2391 */2392strbuf_splice(&sb,0,0, buf, endp - buf);2393 ret =show_one_reflog_ent(&sb, fn, cb_data);2394strbuf_reset(&sb);2395break;2396}23972398if(bp == buf) {2399/*2400 * We are at the start of the buffer, and there2401 * is more file to read backwards. Which means2402 * we are in the middle of a line. Note that we2403 * may get here even if *bp was a newline; that2404 * just means we are at the exact end of the2405 * previous line, rather than some spot in the2406 * middle.2407 *2408 * Save away what we have to be combined with2409 * the data from the next read.2410 */2411strbuf_splice(&sb,0,0, buf, endp - buf);2412break;2413}2414}24152416}2417if(!ret && sb.len)2418die("BUG: reverse reflog parser had leftover data");24192420fclose(logfp);2421strbuf_release(&sb);2422return ret;2423}24242425static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2426const char*refname,2427 each_reflog_ent_fn fn,void*cb_data)2428{2429struct files_ref_store *refs =2430files_downcast(ref_store, REF_STORE_READ,2431"for_each_reflog_ent");2432FILE*logfp;2433struct strbuf sb = STRBUF_INIT;2434int ret =0;24352436files_reflog_path(refs, &sb, refname);2437 logfp =fopen(sb.buf,"r");2438strbuf_release(&sb);2439if(!logfp)2440return-1;24412442while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2443 ret =show_one_reflog_ent(&sb, fn, cb_data);2444fclose(logfp);2445strbuf_release(&sb);2446return ret;2447}24482449struct files_reflog_iterator {2450struct ref_iterator base;24512452struct ref_store *ref_store;2453struct dir_iterator *dir_iterator;2454struct object_id oid;2455};24562457static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2458{2459struct files_reflog_iterator *iter =2460(struct files_reflog_iterator *)ref_iterator;2461struct dir_iterator *diter = iter->dir_iterator;2462int ok;24632464while((ok =dir_iterator_advance(diter)) == ITER_OK) {2465int flags;24662467if(!S_ISREG(diter->st.st_mode))2468continue;2469if(diter->basename[0] =='.')2470continue;2471if(ends_with(diter->basename,".lock"))2472continue;24732474if(refs_read_ref_full(iter->ref_store,2475 diter->relative_path,0,2476 iter->oid.hash, &flags)) {2477error("bad ref for%s", diter->path.buf);2478continue;2479}24802481 iter->base.refname = diter->relative_path;2482 iter->base.oid = &iter->oid;2483 iter->base.flags = flags;2484return ITER_OK;2485}24862487 iter->dir_iterator = NULL;2488if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2489 ok = ITER_ERROR;2490return ok;2491}24922493static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2494struct object_id *peeled)2495{2496die("BUG: ref_iterator_peel() called for reflog_iterator");2497}24982499static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2500{2501struct files_reflog_iterator *iter =2502(struct files_reflog_iterator *)ref_iterator;2503int ok = ITER_DONE;25042505if(iter->dir_iterator)2506 ok =dir_iterator_abort(iter->dir_iterator);25072508base_ref_iterator_free(ref_iterator);2509return ok;2510}25112512static struct ref_iterator_vtable files_reflog_iterator_vtable = {2513 files_reflog_iterator_advance,2514 files_reflog_iterator_peel,2515 files_reflog_iterator_abort2516};25172518static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2519{2520struct files_ref_store *refs =2521files_downcast(ref_store, REF_STORE_READ,2522"reflog_iterator_begin");2523struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2524struct ref_iterator *ref_iterator = &iter->base;2525struct strbuf sb = STRBUF_INIT;25262527base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2528files_reflog_path(refs, &sb, NULL);2529 iter->dir_iterator =dir_iterator_begin(sb.buf);2530 iter->ref_store = ref_store;2531strbuf_release(&sb);2532return ref_iterator;2533}25342535/*2536 * If update is a direct update of head_ref (the reference pointed to2537 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2538 */2539static intsplit_head_update(struct ref_update *update,2540struct ref_transaction *transaction,2541const char*head_ref,2542struct string_list *affected_refnames,2543struct strbuf *err)2544{2545struct string_list_item *item;2546struct ref_update *new_update;25472548if((update->flags & REF_LOG_ONLY) ||2549(update->flags & REF_ISPRUNING) ||2550(update->flags & REF_UPDATE_VIA_HEAD))2551return0;25522553if(strcmp(update->refname, head_ref))2554return0;25552556/*2557 * First make sure that HEAD is not already in the2558 * transaction. This insertion is O(N) in the transaction2559 * size, but it happens at most once per transaction.2560 */2561 item =string_list_insert(affected_refnames,"HEAD");2562if(item->util) {2563/* An entry already existed */2564strbuf_addf(err,2565"multiple updates for 'HEAD' (including one "2566"via its referent '%s') are not allowed",2567 update->refname);2568return TRANSACTION_NAME_CONFLICT;2569}25702571 new_update =ref_transaction_add_update(2572 transaction,"HEAD",2573 update->flags | REF_LOG_ONLY | REF_NODEREF,2574 update->new_oid.hash, update->old_oid.hash,2575 update->msg);25762577 item->util = new_update;25782579return0;2580}25812582/*2583 * update is for a symref that points at referent and doesn't have2584 * REF_NODEREF set. Split it into two updates:2585 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2586 * - A new, separate update for the referent reference2587 * Note that the new update will itself be subject to splitting when2588 * the iteration gets to it.2589 */2590static intsplit_symref_update(struct files_ref_store *refs,2591struct ref_update *update,2592const char*referent,2593struct ref_transaction *transaction,2594struct string_list *affected_refnames,2595struct strbuf *err)2596{2597struct string_list_item *item;2598struct ref_update *new_update;2599unsigned int new_flags;26002601/*2602 * First make sure that referent is not already in the2603 * transaction. This insertion is O(N) in the transaction2604 * size, but it happens at most once per symref in a2605 * transaction.2606 */2607 item =string_list_insert(affected_refnames, referent);2608if(item->util) {2609/* An entry already existed */2610strbuf_addf(err,2611"multiple updates for '%s' (including one "2612"via symref '%s') are not allowed",2613 referent, update->refname);2614return TRANSACTION_NAME_CONFLICT;2615}26162617 new_flags = update->flags;2618if(!strcmp(update->refname,"HEAD")) {2619/*2620 * Record that the new update came via HEAD, so that2621 * when we process it, split_head_update() doesn't try2622 * to add another reflog update for HEAD. Note that2623 * this bit will be propagated if the new_update2624 * itself needs to be split.2625 */2626 new_flags |= REF_UPDATE_VIA_HEAD;2627}26282629 new_update =ref_transaction_add_update(2630 transaction, referent, new_flags,2631 update->new_oid.hash, update->old_oid.hash,2632 update->msg);26332634 new_update->parent_update = update;26352636/*2637 * Change the symbolic ref update to log only. Also, it2638 * doesn't need to check its old SHA-1 value, as that will be2639 * done when new_update is processed.2640 */2641 update->flags |= REF_LOG_ONLY | REF_NODEREF;2642 update->flags &= ~REF_HAVE_OLD;26432644 item->util = new_update;26452646return0;2647}26482649/*2650 * Return the refname under which update was originally requested.2651 */2652static const char*original_update_refname(struct ref_update *update)2653{2654while(update->parent_update)2655 update = update->parent_update;26562657return update->refname;2658}26592660/*2661 * Check whether the REF_HAVE_OLD and old_oid values stored in update2662 * are consistent with oid, which is the reference's current value. If2663 * everything is OK, return 0; otherwise, write an error message to2664 * err and return -1.2665 */2666static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2667struct strbuf *err)2668{2669if(!(update->flags & REF_HAVE_OLD) ||2670!oidcmp(oid, &update->old_oid))2671return0;26722673if(is_null_oid(&update->old_oid))2674strbuf_addf(err,"cannot lock ref '%s': "2675"reference already exists",2676original_update_refname(update));2677else if(is_null_oid(oid))2678strbuf_addf(err,"cannot lock ref '%s': "2679"reference is missing but expected%s",2680original_update_refname(update),2681oid_to_hex(&update->old_oid));2682else2683strbuf_addf(err,"cannot lock ref '%s': "2684"is at%sbut expected%s",2685original_update_refname(update),2686oid_to_hex(oid),2687oid_to_hex(&update->old_oid));26882689return-1;2690}26912692/*2693 * Prepare for carrying out update:2694 * - Lock the reference referred to by update.2695 * - Read the reference under lock.2696 * - Check that its old SHA-1 value (if specified) is correct, and in2697 * any case record it in update->lock->old_oid for later use when2698 * writing the reflog.2699 * - If it is a symref update without REF_NODEREF, split it up into a2700 * REF_LOG_ONLY update of the symref and add a separate update for2701 * the referent to transaction.2702 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2703 * update of HEAD.2704 */2705static intlock_ref_for_update(struct files_ref_store *refs,2706struct ref_update *update,2707struct ref_transaction *transaction,2708const char*head_ref,2709struct string_list *affected_refnames,2710struct strbuf *err)2711{2712struct strbuf referent = STRBUF_INIT;2713int mustexist = (update->flags & REF_HAVE_OLD) &&2714!is_null_oid(&update->old_oid);2715int ret;2716struct ref_lock *lock;27172718files_assert_main_repository(refs,"lock_ref_for_update");27192720if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2721 update->flags |= REF_DELETING;27222723if(head_ref) {2724 ret =split_head_update(update, transaction, head_ref,2725 affected_refnames, err);2726if(ret)2727return ret;2728}27292730 ret =lock_raw_ref(refs, update->refname, mustexist,2731 affected_refnames, NULL,2732&lock, &referent,2733&update->type, err);2734if(ret) {2735char*reason;27362737 reason =strbuf_detach(err, NULL);2738strbuf_addf(err,"cannot lock ref '%s':%s",2739original_update_refname(update), reason);2740free(reason);2741return ret;2742}27432744 update->backend_data = lock;27452746if(update->type & REF_ISSYMREF) {2747if(update->flags & REF_NODEREF) {2748/*2749 * We won't be reading the referent as part of2750 * the transaction, so we have to read it here2751 * to record and possibly check old_sha1:2752 */2753if(refs_read_ref_full(&refs->base,2754 referent.buf,0,2755 lock->old_oid.hash, NULL)) {2756if(update->flags & REF_HAVE_OLD) {2757strbuf_addf(err,"cannot lock ref '%s': "2758"error reading reference",2759original_update_refname(update));2760return-1;2761}2762}else if(check_old_oid(update, &lock->old_oid, err)) {2763return TRANSACTION_GENERIC_ERROR;2764}2765}else{2766/*2767 * Create a new update for the reference this2768 * symref is pointing at. Also, we will record2769 * and verify old_sha1 for this update as part2770 * of processing the split-off update, so we2771 * don't have to do it here.2772 */2773 ret =split_symref_update(refs, update,2774 referent.buf, transaction,2775 affected_refnames, err);2776if(ret)2777return ret;2778}2779}else{2780struct ref_update *parent_update;27812782if(check_old_oid(update, &lock->old_oid, err))2783return TRANSACTION_GENERIC_ERROR;27842785/*2786 * If this update is happening indirectly because of a2787 * symref update, record the old SHA-1 in the parent2788 * update:2789 */2790for(parent_update = update->parent_update;2791 parent_update;2792 parent_update = parent_update->parent_update) {2793struct ref_lock *parent_lock = parent_update->backend_data;2794oidcpy(&parent_lock->old_oid, &lock->old_oid);2795}2796}27972798if((update->flags & REF_HAVE_NEW) &&2799!(update->flags & REF_DELETING) &&2800!(update->flags & REF_LOG_ONLY)) {2801if(!(update->type & REF_ISSYMREF) &&2802!oidcmp(&lock->old_oid, &update->new_oid)) {2803/*2804 * The reference already has the desired2805 * value, so we don't need to write it.2806 */2807}else if(write_ref_to_lockfile(lock, &update->new_oid,2808 err)) {2809char*write_err =strbuf_detach(err, NULL);28102811/*2812 * The lock was freed upon failure of2813 * write_ref_to_lockfile():2814 */2815 update->backend_data = NULL;2816strbuf_addf(err,2817"cannot update ref '%s':%s",2818 update->refname, write_err);2819free(write_err);2820return TRANSACTION_GENERIC_ERROR;2821}else{2822 update->flags |= REF_NEEDS_COMMIT;2823}2824}2825if(!(update->flags & REF_NEEDS_COMMIT)) {2826/*2827 * We didn't call write_ref_to_lockfile(), so2828 * the lockfile is still open. Close it to2829 * free up the file descriptor:2830 */2831if(close_ref(lock)) {2832strbuf_addf(err,"couldn't close '%s.lock'",2833 update->refname);2834return TRANSACTION_GENERIC_ERROR;2835}2836}2837return0;2838}28392840/*2841 * Unlock any references in `transaction` that are still locked, and2842 * mark the transaction closed.2843 */2844static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2845{2846size_t i;28472848for(i =0; i < transaction->nr; i++) {2849struct ref_update *update = transaction->updates[i];2850struct ref_lock *lock = update->backend_data;28512852if(lock) {2853unlock_ref(lock);2854 update->backend_data = NULL;2855}2856}28572858 transaction->state = REF_TRANSACTION_CLOSED;2859}28602861static intfiles_transaction_prepare(struct ref_store *ref_store,2862struct ref_transaction *transaction,2863struct strbuf *err)2864{2865struct files_ref_store *refs =2866files_downcast(ref_store, REF_STORE_WRITE,2867"ref_transaction_prepare");2868size_t i;2869int ret =0;2870struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2871char*head_ref = NULL;2872int head_type;2873struct object_id head_oid;28742875assert(err);28762877if(!transaction->nr)2878goto cleanup;28792880/*2881 * Fail if a refname appears more than once in the2882 * transaction. (If we end up splitting up any updates using2883 * split_symref_update() or split_head_update(), those2884 * functions will check that the new updates don't have the2885 * same refname as any existing ones.)2886 */2887for(i =0; i < transaction->nr; i++) {2888struct ref_update *update = transaction->updates[i];2889struct string_list_item *item =2890string_list_append(&affected_refnames, update->refname);28912892/*2893 * We store a pointer to update in item->util, but at2894 * the moment we never use the value of this field2895 * except to check whether it is non-NULL.2896 */2897 item->util = update;2898}2899string_list_sort(&affected_refnames);2900if(ref_update_reject_duplicates(&affected_refnames, err)) {2901 ret = TRANSACTION_GENERIC_ERROR;2902goto cleanup;2903}29042905/*2906 * Special hack: If a branch is updated directly and HEAD2907 * points to it (may happen on the remote side of a push2908 * for example) then logically the HEAD reflog should be2909 * updated too.2910 *2911 * A generic solution would require reverse symref lookups,2912 * but finding all symrefs pointing to a given branch would be2913 * rather costly for this rare event (the direct update of a2914 * branch) to be worth it. So let's cheat and check with HEAD2915 * only, which should cover 99% of all usage scenarios (even2916 * 100% of the default ones).2917 *2918 * So if HEAD is a symbolic reference, then record the name of2919 * the reference that it points to. If we see an update of2920 * head_ref within the transaction, then split_head_update()2921 * arranges for the reflog of HEAD to be updated, too.2922 */2923 head_ref =refs_resolve_refdup(ref_store,"HEAD",2924 RESOLVE_REF_NO_RECURSE,2925 head_oid.hash, &head_type);29262927if(head_ref && !(head_type & REF_ISSYMREF)) {2928free(head_ref);2929 head_ref = NULL;2930}29312932/*2933 * Acquire all locks, verify old values if provided, check2934 * that new values are valid, and write new values to the2935 * lockfiles, ready to be activated. Only keep one lockfile2936 * open at a time to avoid running out of file descriptors.2937 * Note that lock_ref_for_update() might append more updates2938 * to the transaction.2939 */2940for(i =0; i < transaction->nr; i++) {2941struct ref_update *update = transaction->updates[i];29422943 ret =lock_ref_for_update(refs, update, transaction,2944 head_ref, &affected_refnames, err);2945if(ret)2946break;2947}29482949cleanup:2950free(head_ref);2951string_list_clear(&affected_refnames,0);29522953if(ret)2954files_transaction_cleanup(transaction);2955else2956 transaction->state = REF_TRANSACTION_PREPARED;29572958return ret;2959}29602961static intfiles_transaction_finish(struct ref_store *ref_store,2962struct ref_transaction *transaction,2963struct strbuf *err)2964{2965struct files_ref_store *refs =2966files_downcast(ref_store,0,"ref_transaction_finish");2967size_t i;2968int ret =0;2969struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2970struct string_list_item *ref_to_delete;2971struct strbuf sb = STRBUF_INIT;29722973assert(err);29742975if(!transaction->nr) {2976 transaction->state = REF_TRANSACTION_CLOSED;2977return0;2978}29792980/* Perform updates first so live commits remain referenced */2981for(i =0; i < transaction->nr; i++) {2982struct ref_update *update = transaction->updates[i];2983struct ref_lock *lock = update->backend_data;29842985if(update->flags & REF_NEEDS_COMMIT ||2986 update->flags & REF_LOG_ONLY) {2987if(files_log_ref_write(refs,2988 lock->ref_name,2989&lock->old_oid,2990&update->new_oid,2991 update->msg, update->flags,2992 err)) {2993char*old_msg =strbuf_detach(err, NULL);29942995strbuf_addf(err,"cannot update the ref '%s':%s",2996 lock->ref_name, old_msg);2997free(old_msg);2998unlock_ref(lock);2999 update->backend_data = NULL;3000 ret = TRANSACTION_GENERIC_ERROR;3001goto cleanup;3002}3003}3004if(update->flags & REF_NEEDS_COMMIT) {3005clear_loose_ref_cache(refs);3006if(commit_ref(lock)) {3007strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3008unlock_ref(lock);3009 update->backend_data = NULL;3010 ret = TRANSACTION_GENERIC_ERROR;3011goto cleanup;3012}3013}3014}3015/* Perform deletes now that updates are safely completed */3016for(i =0; i < transaction->nr; i++) {3017struct ref_update *update = transaction->updates[i];3018struct ref_lock *lock = update->backend_data;30193020if(update->flags & REF_DELETING &&3021!(update->flags & REF_LOG_ONLY)) {3022if(!(update->type & REF_ISPACKED) ||3023 update->type & REF_ISSYMREF) {3024/* It is a loose reference. */3025strbuf_reset(&sb);3026files_ref_path(refs, &sb, lock->ref_name);3027if(unlink_or_msg(sb.buf, err)) {3028 ret = TRANSACTION_GENERIC_ERROR;3029goto cleanup;3030}3031 update->flags |= REF_DELETED_LOOSE;3032}30333034if(!(update->flags & REF_ISPRUNING))3035string_list_append(&refs_to_delete,3036 lock->ref_name);3037}3038}30393040if(repack_without_refs(refs, &refs_to_delete, err)) {3041 ret = TRANSACTION_GENERIC_ERROR;3042goto cleanup;3043}30443045/* Delete the reflogs of any references that were deleted: */3046for_each_string_list_item(ref_to_delete, &refs_to_delete) {3047strbuf_reset(&sb);3048files_reflog_path(refs, &sb, ref_to_delete->string);3049if(!unlink_or_warn(sb.buf))3050try_remove_empty_parents(refs, ref_to_delete->string,3051 REMOVE_EMPTY_PARENTS_REFLOG);3052}30533054clear_loose_ref_cache(refs);30553056cleanup:3057files_transaction_cleanup(transaction);30583059for(i =0; i < transaction->nr; i++) {3060struct ref_update *update = transaction->updates[i];30613062if(update->flags & REF_DELETED_LOOSE) {3063/*3064 * The loose reference was deleted. Delete any3065 * empty parent directories. (Note that this3066 * can only work because we have already3067 * removed the lockfile.)3068 */3069try_remove_empty_parents(refs, update->refname,3070 REMOVE_EMPTY_PARENTS_REF);3071}3072}30733074strbuf_release(&sb);3075string_list_clear(&refs_to_delete,0);3076return ret;3077}30783079static intfiles_transaction_abort(struct ref_store *ref_store,3080struct ref_transaction *transaction,3081struct strbuf *err)3082{3083files_transaction_cleanup(transaction);3084return0;3085}30863087static intref_present(const char*refname,3088const struct object_id *oid,int flags,void*cb_data)3089{3090struct string_list *affected_refnames = cb_data;30913092returnstring_list_has_string(affected_refnames, refname);3093}30943095static intfiles_initial_transaction_commit(struct ref_store *ref_store,3096struct ref_transaction *transaction,3097struct strbuf *err)3098{3099struct files_ref_store *refs =3100files_downcast(ref_store, REF_STORE_WRITE,3101"initial_ref_transaction_commit");3102size_t i;3103int ret =0;3104struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31053106assert(err);31073108if(transaction->state != REF_TRANSACTION_OPEN)3109die("BUG: commit called for transaction that is not open");31103111/* Fail if a refname appears more than once in the transaction: */3112for(i =0; i < transaction->nr; i++)3113string_list_append(&affected_refnames,3114 transaction->updates[i]->refname);3115string_list_sort(&affected_refnames);3116if(ref_update_reject_duplicates(&affected_refnames, err)) {3117 ret = TRANSACTION_GENERIC_ERROR;3118goto cleanup;3119}31203121/*3122 * It's really undefined to call this function in an active3123 * repository or when there are existing references: we are3124 * only locking and changing packed-refs, so (1) any3125 * simultaneous processes might try to change a reference at3126 * the same time we do, and (2) any existing loose versions of3127 * the references that we are setting would have precedence3128 * over our values. But some remote helpers create the remote3129 * "HEAD" and "master" branches before calling this function,3130 * so here we really only check that none of the references3131 * that we are creating already exists.3132 */3133if(refs_for_each_rawref(&refs->base, ref_present,3134&affected_refnames))3135die("BUG: initial ref transaction called with existing refs");31363137for(i =0; i < transaction->nr; i++) {3138struct ref_update *update = transaction->updates[i];31393140if((update->flags & REF_HAVE_OLD) &&3141!is_null_oid(&update->old_oid))3142die("BUG: initial ref transaction with old_sha1 set");3143if(refs_verify_refname_available(&refs->base, update->refname,3144&affected_refnames, NULL,3145 err)) {3146 ret = TRANSACTION_NAME_CONFLICT;3147goto cleanup;3148}3149}31503151if(lock_packed_refs(refs,0)) {3152strbuf_addf(err,"unable to lock packed-refs file:%s",3153strerror(errno));3154 ret = TRANSACTION_GENERIC_ERROR;3155goto cleanup;3156}31573158for(i =0; i < transaction->nr; i++) {3159struct ref_update *update = transaction->updates[i];31603161if((update->flags & REF_HAVE_NEW) &&3162!is_null_oid(&update->new_oid))3163add_packed_ref(refs, update->refname,3164&update->new_oid);3165}31663167if(commit_packed_refs(refs)) {3168strbuf_addf(err,"unable to commit packed-refs file:%s",3169strerror(errno));3170 ret = TRANSACTION_GENERIC_ERROR;3171goto cleanup;3172}31733174cleanup:3175 transaction->state = REF_TRANSACTION_CLOSED;3176string_list_clear(&affected_refnames,0);3177return ret;3178}31793180struct expire_reflog_cb {3181unsigned int flags;3182 reflog_expiry_should_prune_fn *should_prune_fn;3183void*policy_cb;3184FILE*newlog;3185struct object_id last_kept_oid;3186};31873188static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3189const char*email, timestamp_t timestamp,int tz,3190const char*message,void*cb_data)3191{3192struct expire_reflog_cb *cb = cb_data;3193struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;31943195if(cb->flags & EXPIRE_REFLOGS_REWRITE)3196 ooid = &cb->last_kept_oid;31973198if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3199 message, policy_cb)) {3200if(!cb->newlog)3201printf("would prune%s", message);3202else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3203printf("prune%s", message);3204}else{3205if(cb->newlog) {3206fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3207oid_to_hex(ooid),oid_to_hex(noid),3208 email, timestamp, tz, message);3209oidcpy(&cb->last_kept_oid, noid);3210}3211if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3212printf("keep%s", message);3213}3214return0;3215}32163217static intfiles_reflog_expire(struct ref_store *ref_store,3218const char*refname,const unsigned char*sha1,3219unsigned int flags,3220 reflog_expiry_prepare_fn prepare_fn,3221 reflog_expiry_should_prune_fn should_prune_fn,3222 reflog_expiry_cleanup_fn cleanup_fn,3223void*policy_cb_data)3224{3225struct files_ref_store *refs =3226files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3227static struct lock_file reflog_lock;3228struct expire_reflog_cb cb;3229struct ref_lock *lock;3230struct strbuf log_file_sb = STRBUF_INIT;3231char*log_file;3232int status =0;3233int type;3234struct strbuf err = STRBUF_INIT;3235struct object_id oid;32363237memset(&cb,0,sizeof(cb));3238 cb.flags = flags;3239 cb.policy_cb = policy_cb_data;3240 cb.should_prune_fn = should_prune_fn;32413242/*3243 * The reflog file is locked by holding the lock on the3244 * reference itself, plus we might need to update the3245 * reference if --updateref was specified:3246 */3247 lock =lock_ref_sha1_basic(refs, refname, sha1,3248 NULL, NULL, REF_NODEREF,3249&type, &err);3250if(!lock) {3251error("cannot lock ref '%s':%s", refname, err.buf);3252strbuf_release(&err);3253return-1;3254}3255if(!refs_reflog_exists(ref_store, refname)) {3256unlock_ref(lock);3257return0;3258}32593260files_reflog_path(refs, &log_file_sb, refname);3261 log_file =strbuf_detach(&log_file_sb, NULL);3262if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3263/*3264 * Even though holding $GIT_DIR/logs/$reflog.lock has3265 * no locking implications, we use the lock_file3266 * machinery here anyway because it does a lot of the3267 * work we need, including cleaning up if the program3268 * exits unexpectedly.3269 */3270if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3271struct strbuf err = STRBUF_INIT;3272unable_to_lock_message(log_file, errno, &err);3273error("%s", err.buf);3274strbuf_release(&err);3275goto failure;3276}3277 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3278if(!cb.newlog) {3279error("cannot fdopen%s(%s)",3280get_lock_file_path(&reflog_lock),strerror(errno));3281goto failure;3282}3283}32843285hashcpy(oid.hash, sha1);32863287(*prepare_fn)(refname, &oid, cb.policy_cb);3288refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3289(*cleanup_fn)(cb.policy_cb);32903291if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3292/*3293 * It doesn't make sense to adjust a reference pointed3294 * to by a symbolic ref based on expiring entries in3295 * the symbolic reference's reflog. Nor can we update3296 * a reference if there are no remaining reflog3297 * entries.3298 */3299int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3300!(type & REF_ISSYMREF) &&3301!is_null_oid(&cb.last_kept_oid);33023303if(close_lock_file(&reflog_lock)) {3304 status |=error("couldn't write%s:%s", log_file,3305strerror(errno));3306}else if(update &&3307(write_in_full(get_lock_file_fd(lock->lk),3308oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3309write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3310close_ref(lock) <0)) {3311 status |=error("couldn't write%s",3312get_lock_file_path(lock->lk));3313rollback_lock_file(&reflog_lock);3314}else if(commit_lock_file(&reflog_lock)) {3315 status |=error("unable to write reflog '%s' (%s)",3316 log_file,strerror(errno));3317}else if(update &&commit_ref(lock)) {3318 status |=error("couldn't set%s", lock->ref_name);3319}3320}3321free(log_file);3322unlock_ref(lock);3323return status;33243325 failure:3326rollback_lock_file(&reflog_lock);3327free(log_file);3328unlock_ref(lock);3329return-1;3330}33313332static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3333{3334struct files_ref_store *refs =3335files_downcast(ref_store, REF_STORE_WRITE,"init_db");3336struct strbuf sb = STRBUF_INIT;33373338/*3339 * Create .git/refs/{heads,tags}3340 */3341files_ref_path(refs, &sb,"refs/heads");3342safe_create_dir(sb.buf,1);33433344strbuf_reset(&sb);3345files_ref_path(refs, &sb,"refs/tags");3346safe_create_dir(sb.buf,1);33473348strbuf_release(&sb);3349return0;3350}33513352struct ref_storage_be refs_be_files = {3353 NULL,3354"files",3355 files_ref_store_create,3356 files_init_db,3357 files_transaction_prepare,3358 files_transaction_finish,3359 files_transaction_abort,3360 files_initial_transaction_commit,33613362 files_pack_refs,3363 files_peel_ref,3364 files_create_symref,3365 files_delete_refs,3366 files_rename_ref,33673368 files_ref_iterator_begin,3369 files_read_raw_ref,33703371 files_reflog_iterator_begin,3372 files_for_each_reflog_ent,3373 files_for_each_reflog_ent_reverse,3374 files_reflog_exists,3375 files_create_reflog,3376 files_delete_reflog,3377 files_reflog_expire3378};