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 from `packed_refs_file` into a newly-allocated 213 * `packed_ref_cache` and return it. The return value will already 214 * have its reference count incremented. 215 * 216 * A comment line of the form "# pack-refs with: " may contain zero or 217 * more traits. We interpret the traits as follows: 218 * 219 * No traits: 220 * 221 * Probably no references are peeled. But if the file contains a 222 * peeled value for a reference, we will use it. 223 * 224 * peeled: 225 * 226 * References under "refs/tags/", if they *can* be peeled, *are* 227 * peeled in this file. References outside of "refs/tags/" are 228 * probably not peeled even if they could have been, but if we find 229 * a peeled value for such a reference we will use it. 230 * 231 * fully-peeled: 232 * 233 * All references in the file that can be peeled are peeled. 234 * Inversely (and this is more important), any references in the 235 * file for which no peeled value is recorded is not peelable. This 236 * trait should typically be written alongside "peeled" for 237 * compatibility with older clients, but we do not require it 238 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 239 */ 240static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 241{ 242FILE*f; 243struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 244struct ref_entry *last = NULL; 245struct strbuf line = STRBUF_INIT; 246enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 247struct ref_dir *dir; 248 249acquire_packed_ref_cache(packed_refs); 250 packed_refs->cache =create_ref_cache(NULL, NULL); 251 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 252 253 f =fopen(packed_refs_file,"r"); 254if(!f) 255return packed_refs; 256 257stat_validity_update(&packed_refs->validity,fileno(f)); 258 259 dir =get_ref_dir(packed_refs->cache->root); 260while(strbuf_getwholeline(&line, f,'\n') != EOF) { 261struct object_id oid; 262const char*refname; 263const char*traits; 264 265if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 266if(strstr(traits," fully-peeled ")) 267 peeled = PEELED_FULLY; 268else if(strstr(traits," peeled ")) 269 peeled = PEELED_TAGS; 270/* perhaps other traits later as well */ 271continue; 272} 273 274 refname =parse_ref_line(&line, &oid); 275if(refname) { 276int flag = REF_ISPACKED; 277 278if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 279if(!refname_is_safe(refname)) 280die("packed refname is dangerous:%s", refname); 281oidclr(&oid); 282 flag |= REF_BAD_NAME | REF_ISBROKEN; 283} 284 last =create_ref_entry(refname, &oid, flag,0); 285if(peeled == PEELED_FULLY || 286(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 287 last->flag |= REF_KNOWS_PEELED; 288add_ref_entry(dir, last); 289continue; 290} 291if(last && 292 line.buf[0] =='^'&& 293 line.len == PEELED_LINE_LENGTH && 294 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 295!get_oid_hex(line.buf +1, &oid)) { 296oidcpy(&last->u.value.peeled, &oid); 297/* 298 * Regardless of what the file header said, 299 * we definitely know the value of *this* 300 * reference: 301 */ 302 last->flag |= REF_KNOWS_PEELED; 303} 304} 305 306fclose(f); 307strbuf_release(&line); 308 309return packed_refs; 310} 311 312static const char*files_packed_refs_path(struct files_ref_store *refs) 313{ 314return refs->packed_refs_path; 315} 316 317static voidfiles_reflog_path(struct files_ref_store *refs, 318struct strbuf *sb, 319const char*refname) 320{ 321if(!refname) { 322/* 323 * FIXME: of course this is wrong in multi worktree 324 * setting. To be fixed real soon. 325 */ 326strbuf_addf(sb,"%s/logs", refs->gitcommondir); 327return; 328} 329 330switch(ref_type(refname)) { 331case REF_TYPE_PER_WORKTREE: 332case REF_TYPE_PSEUDOREF: 333strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 334break; 335case REF_TYPE_NORMAL: 336strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 337break; 338default: 339die("BUG: unknown ref type%dof ref%s", 340ref_type(refname), refname); 341} 342} 343 344static voidfiles_ref_path(struct files_ref_store *refs, 345struct strbuf *sb, 346const char*refname) 347{ 348switch(ref_type(refname)) { 349case REF_TYPE_PER_WORKTREE: 350case REF_TYPE_PSEUDOREF: 351strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 352break; 353case REF_TYPE_NORMAL: 354strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 355break; 356default: 357die("BUG: unknown ref type%dof ref%s", 358ref_type(refname), refname); 359} 360} 361 362/* 363 * Get the packed_ref_cache for the specified files_ref_store, 364 * creating and populating it if it hasn't been read before or if the 365 * file has been changed (according to its `validity` field) since it 366 * was last read. On the other hand, if we hold the lock, then assume 367 * that the file hasn't been changed out from under us, so skip the 368 * extra `stat()` call in `stat_validity_check()`. 369 */ 370static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 371{ 372const char*packed_refs_file =files_packed_refs_path(refs); 373 374if(refs->packed && 375!is_lock_file_locked(&refs->packed_refs_lock) && 376!stat_validity_check(&refs->packed->validity, packed_refs_file)) 377clear_packed_ref_cache(refs); 378 379if(!refs->packed) 380 refs->packed =read_packed_refs(packed_refs_file); 381 382return refs->packed; 383} 384 385static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 386{ 387returnget_ref_dir(packed_ref_cache->cache->root); 388} 389 390static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 391{ 392returnget_packed_ref_dir(get_packed_ref_cache(refs)); 393} 394 395/* 396 * Add a reference to the in-memory packed reference cache. This may 397 * only be called while the packed-refs file is locked (see 398 * lock_packed_refs()). To actually write the packed-refs file, call 399 * commit_packed_refs(). 400 */ 401static voidadd_packed_ref(struct files_ref_store *refs, 402const char*refname,const struct object_id *oid) 403{ 404struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 405 406if(!is_lock_file_locked(&refs->packed_refs_lock)) 407die("BUG: packed refs not locked"); 408add_ref_entry(get_packed_ref_dir(packed_ref_cache), 409create_ref_entry(refname, oid, REF_ISPACKED,1)); 410} 411 412/* 413 * Read the loose references from the namespace dirname into dir 414 * (without recursing). dirname must end with '/'. dir must be the 415 * directory entry corresponding to dirname. 416 */ 417static voidloose_fill_ref_dir(struct ref_store *ref_store, 418struct ref_dir *dir,const char*dirname) 419{ 420struct files_ref_store *refs = 421files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 422DIR*d; 423struct dirent *de; 424int dirnamelen =strlen(dirname); 425struct strbuf refname; 426struct strbuf path = STRBUF_INIT; 427size_t path_baselen; 428 429files_ref_path(refs, &path, dirname); 430 path_baselen = path.len; 431 432 d =opendir(path.buf); 433if(!d) { 434strbuf_release(&path); 435return; 436} 437 438strbuf_init(&refname, dirnamelen +257); 439strbuf_add(&refname, dirname, dirnamelen); 440 441while((de =readdir(d)) != NULL) { 442struct object_id oid; 443struct stat st; 444int flag; 445 446if(de->d_name[0] =='.') 447continue; 448if(ends_with(de->d_name,".lock")) 449continue; 450strbuf_addstr(&refname, de->d_name); 451strbuf_addstr(&path, de->d_name); 452if(stat(path.buf, &st) <0) { 453;/* silently ignore */ 454}else if(S_ISDIR(st.st_mode)) { 455strbuf_addch(&refname,'/'); 456add_entry_to_dir(dir, 457create_dir_entry(dir->cache, refname.buf, 458 refname.len,1)); 459}else{ 460if(!refs_resolve_ref_unsafe(&refs->base, 461 refname.buf, 462 RESOLVE_REF_READING, 463 oid.hash, &flag)) { 464oidclr(&oid); 465 flag |= REF_ISBROKEN; 466}else if(is_null_oid(&oid)) { 467/* 468 * It is so astronomically unlikely 469 * that NULL_SHA1 is the SHA-1 of an 470 * actual object that we consider its 471 * appearance in a loose reference 472 * file to be repo corruption 473 * (probably due to a software bug). 474 */ 475 flag |= REF_ISBROKEN; 476} 477 478if(check_refname_format(refname.buf, 479 REFNAME_ALLOW_ONELEVEL)) { 480if(!refname_is_safe(refname.buf)) 481die("loose refname is dangerous:%s", refname.buf); 482oidclr(&oid); 483 flag |= REF_BAD_NAME | REF_ISBROKEN; 484} 485add_entry_to_dir(dir, 486create_ref_entry(refname.buf, &oid, flag,0)); 487} 488strbuf_setlen(&refname, dirnamelen); 489strbuf_setlen(&path, path_baselen); 490} 491strbuf_release(&refname); 492strbuf_release(&path); 493closedir(d); 494 495/* 496 * Manually add refs/bisect, which, being per-worktree, might 497 * not appear in the directory listing for refs/ in the main 498 * repo. 499 */ 500if(!strcmp(dirname,"refs/")) { 501int pos =search_ref_dir(dir,"refs/bisect/",12); 502 503if(pos <0) { 504struct ref_entry *child_entry =create_dir_entry( 505 dir->cache,"refs/bisect/",12,1); 506add_entry_to_dir(dir, child_entry); 507} 508} 509} 510 511static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 512{ 513if(!refs->loose) { 514/* 515 * Mark the top-level directory complete because we 516 * are about to read the only subdirectory that can 517 * hold references: 518 */ 519 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 520 521/* We're going to fill the top level ourselves: */ 522 refs->loose->root->flag &= ~REF_INCOMPLETE; 523 524/* 525 * Add an incomplete entry for "refs/" (to be filled 526 * lazily): 527 */ 528add_entry_to_dir(get_ref_dir(refs->loose->root), 529create_dir_entry(refs->loose,"refs/",5,1)); 530} 531return refs->loose; 532} 533 534/* 535 * Return the ref_entry for the given refname from the packed 536 * references. If it does not exist, return NULL. 537 */ 538static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 539const char*refname) 540{ 541returnfind_ref_entry(get_packed_refs(refs), refname); 542} 543 544/* 545 * A loose ref file doesn't exist; check for a packed ref. 546 */ 547static intresolve_packed_ref(struct files_ref_store *refs, 548const char*refname, 549unsigned char*sha1,unsigned int*flags) 550{ 551struct ref_entry *entry; 552 553/* 554 * The loose reference file does not exist; check for a packed 555 * reference. 556 */ 557 entry =get_packed_ref(refs, refname); 558if(entry) { 559hashcpy(sha1, entry->u.value.oid.hash); 560*flags |= REF_ISPACKED; 561return0; 562} 563/* refname is not a packed reference. */ 564return-1; 565} 566 567static intfiles_read_raw_ref(struct ref_store *ref_store, 568const char*refname,unsigned char*sha1, 569struct strbuf *referent,unsigned int*type) 570{ 571struct files_ref_store *refs = 572files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 573struct strbuf sb_contents = STRBUF_INIT; 574struct strbuf sb_path = STRBUF_INIT; 575const char*path; 576const char*buf; 577struct stat st; 578int fd; 579int ret = -1; 580int save_errno; 581int remaining_retries =3; 582 583*type =0; 584strbuf_reset(&sb_path); 585 586files_ref_path(refs, &sb_path, refname); 587 588 path = sb_path.buf; 589 590stat_ref: 591/* 592 * We might have to loop back here to avoid a race 593 * condition: first we lstat() the file, then we try 594 * to read it as a link or as a file. But if somebody 595 * changes the type of the file (file <-> directory 596 * <-> symlink) between the lstat() and reading, then 597 * we don't want to report that as an error but rather 598 * try again starting with the lstat(). 599 * 600 * We'll keep a count of the retries, though, just to avoid 601 * any confusing situation sending us into an infinite loop. 602 */ 603 604if(remaining_retries-- <=0) 605goto out; 606 607if(lstat(path, &st) <0) { 608if(errno != ENOENT) 609goto out; 610if(resolve_packed_ref(refs, refname, sha1, type)) { 611 errno = ENOENT; 612goto out; 613} 614 ret =0; 615goto out; 616} 617 618/* Follow "normalized" - ie "refs/.." symlinks by hand */ 619if(S_ISLNK(st.st_mode)) { 620strbuf_reset(&sb_contents); 621if(strbuf_readlink(&sb_contents, path,0) <0) { 622if(errno == ENOENT || errno == EINVAL) 623/* inconsistent with lstat; retry */ 624goto stat_ref; 625else 626goto out; 627} 628if(starts_with(sb_contents.buf,"refs/") && 629!check_refname_format(sb_contents.buf,0)) { 630strbuf_swap(&sb_contents, referent); 631*type |= REF_ISSYMREF; 632 ret =0; 633goto out; 634} 635/* 636 * It doesn't look like a refname; fall through to just 637 * treating it like a non-symlink, and reading whatever it 638 * points to. 639 */ 640} 641 642/* Is it a directory? */ 643if(S_ISDIR(st.st_mode)) { 644/* 645 * Even though there is a directory where the loose 646 * ref is supposed to be, there could still be a 647 * packed ref: 648 */ 649if(resolve_packed_ref(refs, refname, sha1, type)) { 650 errno = EISDIR; 651goto out; 652} 653 ret =0; 654goto out; 655} 656 657/* 658 * Anything else, just open it and try to use it as 659 * a ref 660 */ 661 fd =open(path, O_RDONLY); 662if(fd <0) { 663if(errno == ENOENT && !S_ISLNK(st.st_mode)) 664/* inconsistent with lstat; retry */ 665goto stat_ref; 666else 667goto out; 668} 669strbuf_reset(&sb_contents); 670if(strbuf_read(&sb_contents, fd,256) <0) { 671int save_errno = errno; 672close(fd); 673 errno = save_errno; 674goto out; 675} 676close(fd); 677strbuf_rtrim(&sb_contents); 678 buf = sb_contents.buf; 679if(starts_with(buf,"ref:")) { 680 buf +=4; 681while(isspace(*buf)) 682 buf++; 683 684strbuf_reset(referent); 685strbuf_addstr(referent, buf); 686*type |= REF_ISSYMREF; 687 ret =0; 688goto out; 689} 690 691/* 692 * Please note that FETCH_HEAD has additional 693 * data after the sha. 694 */ 695if(get_sha1_hex(buf, sha1) || 696(buf[40] !='\0'&& !isspace(buf[40]))) { 697*type |= REF_ISBROKEN; 698 errno = EINVAL; 699goto out; 700} 701 702 ret =0; 703 704out: 705 save_errno = errno; 706strbuf_release(&sb_path); 707strbuf_release(&sb_contents); 708 errno = save_errno; 709return ret; 710} 711 712static voidunlock_ref(struct ref_lock *lock) 713{ 714/* Do not free lock->lk -- atexit() still looks at them */ 715if(lock->lk) 716rollback_lock_file(lock->lk); 717free(lock->ref_name); 718free(lock); 719} 720 721/* 722 * Lock refname, without following symrefs, and set *lock_p to point 723 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 724 * and type similarly to read_raw_ref(). 725 * 726 * The caller must verify that refname is a "safe" reference name (in 727 * the sense of refname_is_safe()) before calling this function. 728 * 729 * If the reference doesn't already exist, verify that refname doesn't 730 * have a D/F conflict with any existing references. extras and skip 731 * are passed to refs_verify_refname_available() for this check. 732 * 733 * If mustexist is not set and the reference is not found or is 734 * broken, lock the reference anyway but clear sha1. 735 * 736 * Return 0 on success. On failure, write an error message to err and 737 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 738 * 739 * Implementation note: This function is basically 740 * 741 * lock reference 742 * read_raw_ref() 743 * 744 * but it includes a lot more code to 745 * - Deal with possible races with other processes 746 * - Avoid calling refs_verify_refname_available() when it can be 747 * avoided, namely if we were successfully able to read the ref 748 * - Generate informative error messages in the case of failure 749 */ 750static intlock_raw_ref(struct files_ref_store *refs, 751const char*refname,int mustexist, 752const struct string_list *extras, 753const struct string_list *skip, 754struct ref_lock **lock_p, 755struct strbuf *referent, 756unsigned int*type, 757struct strbuf *err) 758{ 759struct ref_lock *lock; 760struct strbuf ref_file = STRBUF_INIT; 761int attempts_remaining =3; 762int ret = TRANSACTION_GENERIC_ERROR; 763 764assert(err); 765files_assert_main_repository(refs,"lock_raw_ref"); 766 767*type =0; 768 769/* First lock the file so it can't change out from under us. */ 770 771*lock_p = lock =xcalloc(1,sizeof(*lock)); 772 773 lock->ref_name =xstrdup(refname); 774files_ref_path(refs, &ref_file, refname); 775 776retry: 777switch(safe_create_leading_directories(ref_file.buf)) { 778case SCLD_OK: 779break;/* success */ 780case SCLD_EXISTS: 781/* 782 * Suppose refname is "refs/foo/bar". We just failed 783 * to create the containing directory, "refs/foo", 784 * because there was a non-directory in the way. This 785 * indicates a D/F conflict, probably because of 786 * another reference such as "refs/foo". There is no 787 * reason to expect this error to be transitory. 788 */ 789if(refs_verify_refname_available(&refs->base, refname, 790 extras, skip, err)) { 791if(mustexist) { 792/* 793 * To the user the relevant error is 794 * that the "mustexist" reference is 795 * missing: 796 */ 797strbuf_reset(err); 798strbuf_addf(err,"unable to resolve reference '%s'", 799 refname); 800}else{ 801/* 802 * The error message set by 803 * refs_verify_refname_available() is 804 * OK. 805 */ 806 ret = TRANSACTION_NAME_CONFLICT; 807} 808}else{ 809/* 810 * The file that is in the way isn't a loose 811 * reference. Report it as a low-level 812 * failure. 813 */ 814strbuf_addf(err,"unable to create lock file%s.lock; " 815"non-directory in the way", 816 ref_file.buf); 817} 818goto error_return; 819case SCLD_VANISHED: 820/* Maybe another process was tidying up. Try again. */ 821if(--attempts_remaining >0) 822goto retry; 823/* fall through */ 824default: 825strbuf_addf(err,"unable to create directory for%s", 826 ref_file.buf); 827goto error_return; 828} 829 830if(!lock->lk) 831 lock->lk =xcalloc(1,sizeof(struct lock_file)); 832 833if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 834if(errno == ENOENT && --attempts_remaining >0) { 835/* 836 * Maybe somebody just deleted one of the 837 * directories leading to ref_file. Try 838 * again: 839 */ 840goto retry; 841}else{ 842unable_to_lock_message(ref_file.buf, errno, err); 843goto error_return; 844} 845} 846 847/* 848 * Now we hold the lock and can read the reference without 849 * fear that its value will change. 850 */ 851 852if(files_read_raw_ref(&refs->base, refname, 853 lock->old_oid.hash, referent, type)) { 854if(errno == ENOENT) { 855if(mustexist) { 856/* Garden variety missing reference. */ 857strbuf_addf(err,"unable to resolve reference '%s'", 858 refname); 859goto error_return; 860}else{ 861/* 862 * Reference is missing, but that's OK. We 863 * know that there is not a conflict with 864 * another loose reference because 865 * (supposing that we are trying to lock 866 * reference "refs/foo/bar"): 867 * 868 * - We were successfully able to create 869 * the lockfile refs/foo/bar.lock, so we 870 * know there cannot be a loose reference 871 * named "refs/foo". 872 * 873 * - We got ENOENT and not EISDIR, so we 874 * know that there cannot be a loose 875 * reference named "refs/foo/bar/baz". 876 */ 877} 878}else if(errno == EISDIR) { 879/* 880 * There is a directory in the way. It might have 881 * contained references that have been deleted. If 882 * we don't require that the reference already 883 * exists, try to remove the directory so that it 884 * doesn't cause trouble when we want to rename the 885 * lockfile into place later. 886 */ 887if(mustexist) { 888/* Garden variety missing reference. */ 889strbuf_addf(err,"unable to resolve reference '%s'", 890 refname); 891goto error_return; 892}else if(remove_dir_recursively(&ref_file, 893 REMOVE_DIR_EMPTY_ONLY)) { 894if(refs_verify_refname_available( 895&refs->base, refname, 896 extras, skip, err)) { 897/* 898 * The error message set by 899 * verify_refname_available() is OK. 900 */ 901 ret = TRANSACTION_NAME_CONFLICT; 902goto error_return; 903}else{ 904/* 905 * We can't delete the directory, 906 * but we also don't know of any 907 * references that it should 908 * contain. 909 */ 910strbuf_addf(err,"there is a non-empty directory '%s' " 911"blocking reference '%s'", 912 ref_file.buf, refname); 913goto error_return; 914} 915} 916}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 917strbuf_addf(err,"unable to resolve reference '%s': " 918"reference broken", refname); 919goto error_return; 920}else{ 921strbuf_addf(err,"unable to resolve reference '%s':%s", 922 refname,strerror(errno)); 923goto error_return; 924} 925 926/* 927 * If the ref did not exist and we are creating it, 928 * make sure there is no existing ref that conflicts 929 * with refname: 930 */ 931if(refs_verify_refname_available( 932&refs->base, refname, 933 extras, skip, err)) 934goto error_return; 935} 936 937 ret =0; 938goto out; 939 940error_return: 941unlock_ref(lock); 942*lock_p = NULL; 943 944out: 945strbuf_release(&ref_file); 946return ret; 947} 948 949static intfiles_peel_ref(struct ref_store *ref_store, 950const char*refname,unsigned char*sha1) 951{ 952struct files_ref_store *refs = 953files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 954"peel_ref"); 955int flag; 956unsigned char base[20]; 957 958if(current_ref_iter && current_ref_iter->refname == refname) { 959struct object_id peeled; 960 961if(ref_iterator_peel(current_ref_iter, &peeled)) 962return-1; 963hashcpy(sha1, peeled.hash); 964return0; 965} 966 967if(refs_read_ref_full(ref_store, refname, 968 RESOLVE_REF_READING, base, &flag)) 969return-1; 970 971/* 972 * If the reference is packed, read its ref_entry from the 973 * cache in the hope that we already know its peeled value. 974 * We only try this optimization on packed references because 975 * (a) forcing the filling of the loose reference cache could 976 * be expensive and (b) loose references anyway usually do not 977 * have REF_KNOWS_PEELED. 978 */ 979if(flag & REF_ISPACKED) { 980struct ref_entry *r =get_packed_ref(refs, refname); 981if(r) { 982if(peel_entry(r,0)) 983return-1; 984hashcpy(sha1, r->u.value.peeled.hash); 985return0; 986} 987} 988 989returnpeel_object(base, sha1); 990} 991 992struct files_ref_iterator { 993struct ref_iterator base; 994 995struct packed_ref_cache *packed_ref_cache; 996struct ref_iterator *iter0; 997unsigned int flags; 998}; 9991000static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1001{1002struct files_ref_iterator *iter =1003(struct files_ref_iterator *)ref_iterator;1004int ok;10051006while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1007if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1008ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1009continue;10101011if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1012!ref_resolves_to_object(iter->iter0->refname,1013 iter->iter0->oid,1014 iter->iter0->flags))1015continue;10161017 iter->base.refname = iter->iter0->refname;1018 iter->base.oid = iter->iter0->oid;1019 iter->base.flags = iter->iter0->flags;1020return ITER_OK;1021}10221023 iter->iter0 = NULL;1024if(ref_iterator_abort(ref_iterator) != ITER_DONE)1025 ok = ITER_ERROR;10261027return ok;1028}10291030static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1031struct object_id *peeled)1032{1033struct files_ref_iterator *iter =1034(struct files_ref_iterator *)ref_iterator;10351036returnref_iterator_peel(iter->iter0, peeled);1037}10381039static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1040{1041struct files_ref_iterator *iter =1042(struct files_ref_iterator *)ref_iterator;1043int ok = ITER_DONE;10441045if(iter->iter0)1046 ok =ref_iterator_abort(iter->iter0);10471048release_packed_ref_cache(iter->packed_ref_cache);1049base_ref_iterator_free(ref_iterator);1050return ok;1051}10521053static struct ref_iterator_vtable files_ref_iterator_vtable = {1054 files_ref_iterator_advance,1055 files_ref_iterator_peel,1056 files_ref_iterator_abort1057};10581059static struct ref_iterator *files_ref_iterator_begin(1060struct ref_store *ref_store,1061const char*prefix,unsigned int flags)1062{1063struct files_ref_store *refs;1064struct ref_iterator *loose_iter, *packed_iter;1065struct files_ref_iterator *iter;1066struct ref_iterator *ref_iterator;10671068if(ref_paranoia <0)1069 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1070if(ref_paranoia)1071 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10721073 refs =files_downcast(ref_store,1074 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1075"ref_iterator_begin");10761077 iter =xcalloc(1,sizeof(*iter));1078 ref_iterator = &iter->base;1079base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10801081/*1082 * We must make sure that all loose refs are read before1083 * accessing the packed-refs file; this avoids a race1084 * condition if loose refs are migrated to the packed-refs1085 * file by a simultaneous process, but our in-memory view is1086 * from before the migration. We ensure this as follows:1087 * First, we call start the loose refs iteration with its1088 * `prime_ref` argument set to true. This causes the loose1089 * references in the subtree to be pre-read into the cache.1090 * (If they've already been read, that's OK; we only need to1091 * guarantee that they're read before the packed refs, not1092 * *how much* before.) After that, we call1093 * get_packed_ref_cache(), which internally checks whether the1094 * packed-ref cache is up to date with what is on disk, and1095 * re-reads it if not.1096 */10971098 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1099 prefix,1);11001101 iter->packed_ref_cache =get_packed_ref_cache(refs);1102acquire_packed_ref_cache(iter->packed_ref_cache);1103 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1104 prefix,0);11051106 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1107 iter->flags = flags;11081109return ref_iterator;1110}11111112/*1113 * Verify that the reference locked by lock has the value old_sha1.1114 * Fail if the reference doesn't exist and mustexist is set. Return 01115 * on success. On error, write an error message to err, set errno, and1116 * return a negative value.1117 */1118static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1119const unsigned char*old_sha1,int mustexist,1120struct strbuf *err)1121{1122assert(err);11231124if(refs_read_ref_full(ref_store, lock->ref_name,1125 mustexist ? RESOLVE_REF_READING :0,1126 lock->old_oid.hash, NULL)) {1127if(old_sha1) {1128int save_errno = errno;1129strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1130 errno = save_errno;1131return-1;1132}else{1133oidclr(&lock->old_oid);1134return0;1135}1136}1137if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1138strbuf_addf(err,"ref '%s' is at%sbut expected%s",1139 lock->ref_name,1140oid_to_hex(&lock->old_oid),1141sha1_to_hex(old_sha1));1142 errno = EBUSY;1143return-1;1144}1145return0;1146}11471148static intremove_empty_directories(struct strbuf *path)1149{1150/*1151 * we want to create a file but there is a directory there;1152 * if that is an empty directory (or a directory that contains1153 * only empty directories), remove them.1154 */1155returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1156}11571158static intcreate_reflock(const char*path,void*cb)1159{1160struct lock_file *lk = cb;11611162returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1163}11641165/*1166 * Locks a ref returning the lock on success and NULL on failure.1167 * On failure errno is set to something meaningful.1168 */1169static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1170const char*refname,1171const unsigned char*old_sha1,1172const struct string_list *extras,1173const struct string_list *skip,1174unsigned int flags,int*type,1175struct strbuf *err)1176{1177struct strbuf ref_file = STRBUF_INIT;1178struct ref_lock *lock;1179int last_errno =0;1180int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1181int resolve_flags = RESOLVE_REF_NO_RECURSE;1182int resolved;11831184files_assert_main_repository(refs,"lock_ref_sha1_basic");1185assert(err);11861187 lock =xcalloc(1,sizeof(struct ref_lock));11881189if(mustexist)1190 resolve_flags |= RESOLVE_REF_READING;1191if(flags & REF_DELETING)1192 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11931194files_ref_path(refs, &ref_file, refname);1195 resolved = !!refs_resolve_ref_unsafe(&refs->base,1196 refname, resolve_flags,1197 lock->old_oid.hash, type);1198if(!resolved && errno == EISDIR) {1199/*1200 * we are trying to lock foo but we used to1201 * have foo/bar which now does not exist;1202 * it is normal for the empty directory 'foo'1203 * to remain.1204 */1205if(remove_empty_directories(&ref_file)) {1206 last_errno = errno;1207if(!refs_verify_refname_available(1208&refs->base,1209 refname, extras, skip, err))1210strbuf_addf(err,"there are still refs under '%s'",1211 refname);1212goto error_return;1213}1214 resolved = !!refs_resolve_ref_unsafe(&refs->base,1215 refname, resolve_flags,1216 lock->old_oid.hash, type);1217}1218if(!resolved) {1219 last_errno = errno;1220if(last_errno != ENOTDIR ||1221!refs_verify_refname_available(&refs->base, refname,1222 extras, skip, err))1223strbuf_addf(err,"unable to resolve reference '%s':%s",1224 refname,strerror(last_errno));12251226goto error_return;1227}12281229/*1230 * If the ref did not exist and we are creating it, make sure1231 * there is no existing packed ref whose name begins with our1232 * refname, nor a packed ref whose name is a proper prefix of1233 * our refname.1234 */1235if(is_null_oid(&lock->old_oid) &&1236refs_verify_refname_available(&refs->base, refname,1237 extras, skip, err)) {1238 last_errno = ENOTDIR;1239goto error_return;1240}12411242 lock->lk =xcalloc(1,sizeof(struct lock_file));12431244 lock->ref_name =xstrdup(refname);12451246if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1247 last_errno = errno;1248unable_to_lock_message(ref_file.buf, errno, err);1249goto error_return;1250}12511252if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1253 last_errno = errno;1254goto error_return;1255}1256goto out;12571258 error_return:1259unlock_ref(lock);1260 lock = NULL;12611262 out:1263strbuf_release(&ref_file);1264 errno = last_errno;1265return lock;1266}12671268/*1269 * Write an entry to the packed-refs file for the specified refname.1270 * If peeled is non-NULL, write it as the entry's peeled value.1271 */1272static voidwrite_packed_entry(FILE*fh,const char*refname,1273const unsigned char*sha1,1274const unsigned char*peeled)1275{1276fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1277if(peeled)1278fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1279}12801281/*1282 * Lock the packed-refs file for writing. Flags is passed to1283 * hold_lock_file_for_update(). Return 0 on success. On errors, set1284 * errno appropriately and return a nonzero value.1285 */1286static intlock_packed_refs(struct files_ref_store *refs,int flags)1287{1288static int timeout_configured =0;1289static int timeout_value =1000;1290struct packed_ref_cache *packed_ref_cache;12911292files_assert_main_repository(refs,"lock_packed_refs");12931294if(!timeout_configured) {1295git_config_get_int("core.packedrefstimeout", &timeout_value);1296 timeout_configured =1;1297}12981299if(hold_lock_file_for_update_timeout(1300&refs->packed_refs_lock,files_packed_refs_path(refs),1301 flags, timeout_value) <0)1302return-1;1303/*1304 * Get the current packed-refs while holding the lock. It is1305 * important that we call `get_packed_ref_cache()` before1306 * setting `packed_ref_cache->lock`, because otherwise the1307 * former will see that the file is locked and assume that the1308 * cache can't be stale.1309 */1310 packed_ref_cache =get_packed_ref_cache(refs);1311/* Increment the reference count to prevent it from being freed: */1312acquire_packed_ref_cache(packed_ref_cache);1313return0;1314}13151316/*1317 * Write the current version of the packed refs cache from memory to1318 * disk. The packed-refs file must already be locked for writing (see1319 * lock_packed_refs()). Return zero on success. On errors, set errno1320 * and return a nonzero value1321 */1322static intcommit_packed_refs(struct files_ref_store *refs)1323{1324struct packed_ref_cache *packed_ref_cache =1325get_packed_ref_cache(refs);1326int ok, error =0;1327int save_errno =0;1328FILE*out;1329struct ref_iterator *iter;13301331files_assert_main_repository(refs,"commit_packed_refs");13321333if(!is_lock_file_locked(&refs->packed_refs_lock))1334die("BUG: packed-refs not locked");13351336 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1337if(!out)1338die_errno("unable to fdopen packed-refs descriptor");13391340fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13411342 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1343while((ok =ref_iterator_advance(iter)) == ITER_OK) {1344struct object_id peeled;1345int peel_error =ref_iterator_peel(iter, &peeled);13461347write_packed_entry(out, iter->refname, iter->oid->hash,1348 peel_error ? NULL : peeled.hash);1349}13501351if(ok != ITER_DONE)1352die("error while iterating over references");13531354if(commit_lock_file(&refs->packed_refs_lock)) {1355 save_errno = errno;1356 error = -1;1357}1358release_packed_ref_cache(packed_ref_cache);1359 errno = save_errno;1360return error;1361}13621363/*1364 * Rollback the lockfile for the packed-refs file, and discard the1365 * in-memory packed reference cache. (The packed-refs file will be1366 * read anew if it is needed again after this function is called.)1367 */1368static voidrollback_packed_refs(struct files_ref_store *refs)1369{1370struct packed_ref_cache *packed_ref_cache =1371get_packed_ref_cache(refs);13721373files_assert_main_repository(refs,"rollback_packed_refs");13741375if(!is_lock_file_locked(&refs->packed_refs_lock))1376die("BUG: packed-refs not locked");1377rollback_lock_file(&refs->packed_refs_lock);1378release_packed_ref_cache(packed_ref_cache);1379clear_packed_ref_cache(refs);1380}13811382struct ref_to_prune {1383struct ref_to_prune *next;1384unsigned char sha1[20];1385char name[FLEX_ARRAY];1386};13871388enum{1389 REMOVE_EMPTY_PARENTS_REF =0x01,1390 REMOVE_EMPTY_PARENTS_REFLOG =0x021391};13921393/*1394 * Remove empty parent directories associated with the specified1395 * reference and/or its reflog, but spare [logs/]refs/ and immediate1396 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1397 * REMOVE_EMPTY_PARENTS_REFLOG.1398 */1399static voidtry_remove_empty_parents(struct files_ref_store *refs,1400const char*refname,1401unsigned int flags)1402{1403struct strbuf buf = STRBUF_INIT;1404struct strbuf sb = STRBUF_INIT;1405char*p, *q;1406int i;14071408strbuf_addstr(&buf, refname);1409 p = buf.buf;1410for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1411while(*p && *p !='/')1412 p++;1413/* tolerate duplicate slashes; see check_refname_format() */1414while(*p =='/')1415 p++;1416}1417 q = buf.buf + buf.len;1418while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1419while(q > p && *q !='/')1420 q--;1421while(q > p && *(q-1) =='/')1422 q--;1423if(q == p)1424break;1425strbuf_setlen(&buf, q - buf.buf);14261427strbuf_reset(&sb);1428files_ref_path(refs, &sb, buf.buf);1429if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1430 flags &= ~REMOVE_EMPTY_PARENTS_REF;14311432strbuf_reset(&sb);1433files_reflog_path(refs, &sb, buf.buf);1434if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1435 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1436}1437strbuf_release(&buf);1438strbuf_release(&sb);1439}14401441/* make sure nobody touched the ref, and unlink */1442static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1443{1444struct ref_transaction *transaction;1445struct strbuf err = STRBUF_INIT;14461447if(check_refname_format(r->name,0))1448return;14491450 transaction =ref_store_transaction_begin(&refs->base, &err);1451if(!transaction ||1452ref_transaction_delete(transaction, r->name, r->sha1,1453 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1454ref_transaction_commit(transaction, &err)) {1455ref_transaction_free(transaction);1456error("%s", err.buf);1457strbuf_release(&err);1458return;1459}1460ref_transaction_free(transaction);1461strbuf_release(&err);1462}14631464static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1465{1466while(r) {1467prune_ref(refs, r);1468 r = r->next;1469}1470}14711472/*1473 * Return true if the specified reference should be packed.1474 */1475static intshould_pack_ref(const char*refname,1476const struct object_id *oid,unsigned int ref_flags,1477unsigned int pack_flags)1478{1479/* Do not pack per-worktree refs: */1480if(ref_type(refname) != REF_TYPE_NORMAL)1481return0;14821483/* Do not pack non-tags unless PACK_REFS_ALL is set: */1484if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1485return0;14861487/* Do not pack symbolic refs: */1488if(ref_flags & REF_ISSYMREF)1489return0;14901491/* Do not pack broken refs: */1492if(!ref_resolves_to_object(refname, oid, ref_flags))1493return0;14941495return1;1496}14971498static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1499{1500struct files_ref_store *refs =1501files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1502"pack_refs");1503struct ref_iterator *iter;1504struct ref_dir *packed_refs;1505int ok;1506struct ref_to_prune *refs_to_prune = NULL;15071508lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1509 packed_refs =get_packed_refs(refs);15101511 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1512while((ok =ref_iterator_advance(iter)) == ITER_OK) {1513/*1514 * If the loose reference can be packed, add an entry1515 * in the packed ref cache. If the reference should be1516 * pruned, also add it to refs_to_prune.1517 */1518struct ref_entry *packed_entry;15191520if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1521 flags))1522continue;15231524/*1525 * Create an entry in the packed-refs cache equivalent1526 * to the one from the loose ref cache, except that1527 * we don't copy the peeled status, because we want it1528 * to be re-peeled.1529 */1530 packed_entry =find_ref_entry(packed_refs, iter->refname);1531if(packed_entry) {1532/* Overwrite existing packed entry with info from loose entry */1533 packed_entry->flag = REF_ISPACKED;1534oidcpy(&packed_entry->u.value.oid, iter->oid);1535}else{1536 packed_entry =create_ref_entry(iter->refname, iter->oid,1537 REF_ISPACKED,0);1538add_ref_entry(packed_refs, packed_entry);1539}1540oidclr(&packed_entry->u.value.peeled);15411542/* Schedule the loose reference for pruning if requested. */1543if((flags & PACK_REFS_PRUNE)) {1544struct ref_to_prune *n;1545FLEX_ALLOC_STR(n, name, iter->refname);1546hashcpy(n->sha1, iter->oid->hash);1547 n->next = refs_to_prune;1548 refs_to_prune = n;1549}1550}1551if(ok != ITER_DONE)1552die("error while iterating over references");15531554if(commit_packed_refs(refs))1555die_errno("unable to overwrite old ref-pack file");15561557prune_refs(refs, refs_to_prune);1558return0;1559}15601561/*1562 * Rewrite the packed-refs file, omitting any refs listed in1563 * 'refnames'. On error, leave packed-refs unchanged, write an error1564 * message to 'err', and return a nonzero value.1565 *1566 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1567 */1568static intrepack_without_refs(struct files_ref_store *refs,1569struct string_list *refnames,struct strbuf *err)1570{1571struct ref_dir *packed;1572struct string_list_item *refname;1573int ret, needs_repacking =0, removed =0;15741575files_assert_main_repository(refs,"repack_without_refs");1576assert(err);15771578/* Look for a packed ref */1579for_each_string_list_item(refname, refnames) {1580if(get_packed_ref(refs, refname->string)) {1581 needs_repacking =1;1582break;1583}1584}15851586/* Avoid locking if we have nothing to do */1587if(!needs_repacking)1588return0;/* no refname exists in packed refs */15891590if(lock_packed_refs(refs,0)) {1591unable_to_lock_message(files_packed_refs_path(refs), errno, err);1592return-1;1593}1594 packed =get_packed_refs(refs);15951596/* Remove refnames from the cache */1597for_each_string_list_item(refname, refnames)1598if(remove_entry_from_dir(packed, refname->string) != -1)1599 removed =1;1600if(!removed) {1601/*1602 * All packed entries disappeared while we were1603 * acquiring the lock.1604 */1605rollback_packed_refs(refs);1606return0;1607}16081609/* Write what remains */1610 ret =commit_packed_refs(refs);1611if(ret)1612strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1613strerror(errno));1614return ret;1615}16161617static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1618struct string_list *refnames,unsigned int flags)1619{1620struct files_ref_store *refs =1621files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1622struct strbuf err = STRBUF_INIT;1623int i, result =0;16241625if(!refnames->nr)1626return0;16271628 result =repack_without_refs(refs, refnames, &err);1629if(result) {1630/*1631 * If we failed to rewrite the packed-refs file, then1632 * it is unsafe to try to remove loose refs, because1633 * doing so might expose an obsolete packed value for1634 * a reference that might even point at an object that1635 * has been garbage collected.1636 */1637if(refnames->nr ==1)1638error(_("could not delete reference%s:%s"),1639 refnames->items[0].string, err.buf);1640else1641error(_("could not delete references:%s"), err.buf);16421643goto out;1644}16451646for(i =0; i < refnames->nr; i++) {1647const char*refname = refnames->items[i].string;16481649if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1650 result |=error(_("could not remove reference%s"), refname);1651}16521653out:1654strbuf_release(&err);1655return result;1656}16571658/*1659 * People using contrib's git-new-workdir have .git/logs/refs ->1660 * /some/other/path/.git/logs/refs, and that may live on another device.1661 *1662 * IOW, to avoid cross device rename errors, the temporary renamed log must1663 * live into logs/refs.1664 */1665#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16661667struct rename_cb {1668const char*tmp_renamed_log;1669int true_errno;1670};16711672static intrename_tmp_log_callback(const char*path,void*cb_data)1673{1674struct rename_cb *cb = cb_data;16751676if(rename(cb->tmp_renamed_log, path)) {1677/*1678 * rename(a, b) when b is an existing directory ought1679 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1680 * Sheesh. Record the true errno for error reporting,1681 * but report EISDIR to raceproof_create_file() so1682 * that it knows to retry.1683 */1684 cb->true_errno = errno;1685if(errno == ENOTDIR)1686 errno = EISDIR;1687return-1;1688}else{1689return0;1690}1691}16921693static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1694{1695struct strbuf path = STRBUF_INIT;1696struct strbuf tmp = STRBUF_INIT;1697struct rename_cb cb;1698int ret;16991700files_reflog_path(refs, &path, newrefname);1701files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1702 cb.tmp_renamed_log = tmp.buf;1703 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1704if(ret) {1705if(errno == EISDIR)1706error("directory not empty:%s", path.buf);1707else1708error("unable to move logfile%sto%s:%s",1709 tmp.buf, path.buf,1710strerror(cb.true_errno));1711}17121713strbuf_release(&path);1714strbuf_release(&tmp);1715return ret;1716}17171718static intwrite_ref_to_lockfile(struct ref_lock *lock,1719const struct object_id *oid,struct strbuf *err);1720static intcommit_ref_update(struct files_ref_store *refs,1721struct ref_lock *lock,1722const struct object_id *oid,const char*logmsg,1723struct strbuf *err);17241725static intfiles_rename_ref(struct ref_store *ref_store,1726const char*oldrefname,const char*newrefname,1727const char*logmsg)1728{1729struct files_ref_store *refs =1730files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1731struct object_id oid, orig_oid;1732int flag =0, logmoved =0;1733struct ref_lock *lock;1734struct stat loginfo;1735struct strbuf sb_oldref = STRBUF_INIT;1736struct strbuf sb_newref = STRBUF_INIT;1737struct strbuf tmp_renamed_log = STRBUF_INIT;1738int log, ret;1739struct strbuf err = STRBUF_INIT;17401741files_reflog_path(refs, &sb_oldref, oldrefname);1742files_reflog_path(refs, &sb_newref, newrefname);1743files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17441745 log = !lstat(sb_oldref.buf, &loginfo);1746if(log &&S_ISLNK(loginfo.st_mode)) {1747 ret =error("reflog for%sis a symlink", oldrefname);1748goto out;1749}17501751if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1752 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1753 orig_oid.hash, &flag)) {1754 ret =error("refname%snot found", oldrefname);1755goto out;1756}17571758if(flag & REF_ISSYMREF) {1759 ret =error("refname%sis a symbolic ref, renaming it is not supported",1760 oldrefname);1761goto out;1762}1763if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1764 ret =1;1765goto out;1766}17671768if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1769 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1770 oldrefname,strerror(errno));1771goto out;1772}17731774if(refs_delete_ref(&refs->base, logmsg, oldrefname,1775 orig_oid.hash, REF_NODEREF)) {1776error("unable to delete old%s", oldrefname);1777goto rollback;1778}17791780/*1781 * Since we are doing a shallow lookup, oid is not the1782 * correct value to pass to delete_ref as old_oid. But that1783 * doesn't matter, because an old_oid check wouldn't add to1784 * the safety anyway; we want to delete the reference whatever1785 * its current value.1786 */1787if(!refs_read_ref_full(&refs->base, newrefname,1788 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1789 oid.hash, NULL) &&1790refs_delete_ref(&refs->base, NULL, newrefname,1791 NULL, REF_NODEREF)) {1792if(errno == EISDIR) {1793struct strbuf path = STRBUF_INIT;1794int result;17951796files_ref_path(refs, &path, newrefname);1797 result =remove_empty_directories(&path);1798strbuf_release(&path);17991800if(result) {1801error("Directory not empty:%s", newrefname);1802goto rollback;1803}1804}else{1805error("unable to delete existing%s", newrefname);1806goto rollback;1807}1808}18091810if(log &&rename_tmp_log(refs, newrefname))1811goto rollback;18121813 logmoved = log;18141815 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1816 REF_NODEREF, NULL, &err);1817if(!lock) {1818error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1819strbuf_release(&err);1820goto rollback;1821}1822oidcpy(&lock->old_oid, &orig_oid);18231824if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1825commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1826error("unable to write current sha1 into%s:%s", newrefname, err.buf);1827strbuf_release(&err);1828goto rollback;1829}18301831 ret =0;1832goto out;18331834 rollback:1835 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1836 REF_NODEREF, NULL, &err);1837if(!lock) {1838error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1839strbuf_release(&err);1840goto rollbacklog;1841}18421843 flag = log_all_ref_updates;1844 log_all_ref_updates = LOG_REFS_NONE;1845if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1846commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1847error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1848strbuf_release(&err);1849}1850 log_all_ref_updates = flag;18511852 rollbacklog:1853if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1854error("unable to restore logfile%sfrom%s:%s",1855 oldrefname, newrefname,strerror(errno));1856if(!logmoved && log &&1857rename(tmp_renamed_log.buf, sb_oldref.buf))1858error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1859 oldrefname,strerror(errno));1860 ret =1;1861 out:1862strbuf_release(&sb_newref);1863strbuf_release(&sb_oldref);1864strbuf_release(&tmp_renamed_log);18651866return ret;1867}18681869static intclose_ref(struct ref_lock *lock)1870{1871if(close_lock_file(lock->lk))1872return-1;1873return0;1874}18751876static intcommit_ref(struct ref_lock *lock)1877{1878char*path =get_locked_file_path(lock->lk);1879struct stat st;18801881if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1882/*1883 * There is a directory at the path we want to rename1884 * the lockfile to. Hopefully it is empty; try to1885 * delete it.1886 */1887size_t len =strlen(path);1888struct strbuf sb_path = STRBUF_INIT;18891890strbuf_attach(&sb_path, path, len, len);18911892/*1893 * If this fails, commit_lock_file() will also fail1894 * and will report the problem.1895 */1896remove_empty_directories(&sb_path);1897strbuf_release(&sb_path);1898}else{1899free(path);1900}19011902if(commit_lock_file(lock->lk))1903return-1;1904return0;1905}19061907static intopen_or_create_logfile(const char*path,void*cb)1908{1909int*fd = cb;19101911*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1912return(*fd <0) ? -1:0;1913}19141915/*1916 * Create a reflog for a ref. If force_create = 0, only create the1917 * reflog for certain refs (those for which should_autocreate_reflog1918 * returns non-zero). Otherwise, create it regardless of the reference1919 * name. If the logfile already existed or was created, return 0 and1920 * set *logfd to the file descriptor opened for appending to the file.1921 * If no logfile exists and we decided not to create one, return 0 and1922 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1923 * return -1.1924 */1925static intlog_ref_setup(struct files_ref_store *refs,1926const char*refname,int force_create,1927int*logfd,struct strbuf *err)1928{1929struct strbuf logfile_sb = STRBUF_INIT;1930char*logfile;19311932files_reflog_path(refs, &logfile_sb, refname);1933 logfile =strbuf_detach(&logfile_sb, NULL);19341935if(force_create ||should_autocreate_reflog(refname)) {1936if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1937if(errno == ENOENT)1938strbuf_addf(err,"unable to create directory for '%s': "1939"%s", logfile,strerror(errno));1940else if(errno == EISDIR)1941strbuf_addf(err,"there are still logs under '%s'",1942 logfile);1943else1944strbuf_addf(err,"unable to append to '%s':%s",1945 logfile,strerror(errno));19461947goto error;1948}1949}else{1950*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1951if(*logfd <0) {1952if(errno == ENOENT || errno == EISDIR) {1953/*1954 * The logfile doesn't already exist,1955 * but that is not an error; it only1956 * means that we won't write log1957 * entries to it.1958 */1959;1960}else{1961strbuf_addf(err,"unable to append to '%s':%s",1962 logfile,strerror(errno));1963goto error;1964}1965}1966}19671968if(*logfd >=0)1969adjust_shared_perm(logfile);19701971free(logfile);1972return0;19731974error:1975free(logfile);1976return-1;1977}19781979static intfiles_create_reflog(struct ref_store *ref_store,1980const char*refname,int force_create,1981struct strbuf *err)1982{1983struct files_ref_store *refs =1984files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1985int fd;19861987if(log_ref_setup(refs, refname, force_create, &fd, err))1988return-1;19891990if(fd >=0)1991close(fd);19921993return0;1994}19951996static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1997const struct object_id *new_oid,1998const char*committer,const char*msg)1999{2000int msglen, written;2001unsigned maxlen, len;2002char*logrec;20032004 msglen = msg ?strlen(msg) :0;2005 maxlen =strlen(committer) + msglen +100;2006 logrec =xmalloc(maxlen);2007 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2008oid_to_hex(old_oid),2009oid_to_hex(new_oid),2010 committer);2011if(msglen)2012 len +=copy_reflog_msg(logrec + len -1, msg) -1;20132014 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2015free(logrec);2016if(written != len)2017return-1;20182019return0;2020}20212022static intfiles_log_ref_write(struct files_ref_store *refs,2023const char*refname,const struct object_id *old_oid,2024const struct object_id *new_oid,const char*msg,2025int flags,struct strbuf *err)2026{2027int logfd, result;20282029if(log_all_ref_updates == LOG_REFS_UNSET)2030 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20312032 result =log_ref_setup(refs, refname,2033 flags & REF_FORCE_CREATE_REFLOG,2034&logfd, err);20352036if(result)2037return result;20382039if(logfd <0)2040return0;2041 result =log_ref_write_fd(logfd, old_oid, new_oid,2042git_committer_info(0), msg);2043if(result) {2044struct strbuf sb = STRBUF_INIT;2045int save_errno = errno;20462047files_reflog_path(refs, &sb, refname);2048strbuf_addf(err,"unable to append to '%s':%s",2049 sb.buf,strerror(save_errno));2050strbuf_release(&sb);2051close(logfd);2052return-1;2053}2054if(close(logfd)) {2055struct strbuf sb = STRBUF_INIT;2056int save_errno = errno;20572058files_reflog_path(refs, &sb, refname);2059strbuf_addf(err,"unable to append to '%s':%s",2060 sb.buf,strerror(save_errno));2061strbuf_release(&sb);2062return-1;2063}2064return0;2065}20662067/*2068 * Write sha1 into the open lockfile, then close the lockfile. On2069 * errors, rollback the lockfile, fill in *err and2070 * return -1.2071 */2072static intwrite_ref_to_lockfile(struct ref_lock *lock,2073const struct object_id *oid,struct strbuf *err)2074{2075static char term ='\n';2076struct object *o;2077int fd;20782079 o =parse_object(oid);2080if(!o) {2081strbuf_addf(err,2082"trying to write ref '%s' with nonexistent object%s",2083 lock->ref_name,oid_to_hex(oid));2084unlock_ref(lock);2085return-1;2086}2087if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2088strbuf_addf(err,2089"trying to write non-commit object%sto branch '%s'",2090oid_to_hex(oid), lock->ref_name);2091unlock_ref(lock);2092return-1;2093}2094 fd =get_lock_file_fd(lock->lk);2095if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2096write_in_full(fd, &term,1) !=1||2097close_ref(lock) <0) {2098strbuf_addf(err,2099"couldn't write '%s'",get_lock_file_path(lock->lk));2100unlock_ref(lock);2101return-1;2102}2103return0;2104}21052106/*2107 * Commit a change to a loose reference that has already been written2108 * to the loose reference lockfile. Also update the reflogs if2109 * necessary, using the specified lockmsg (which can be NULL).2110 */2111static intcommit_ref_update(struct files_ref_store *refs,2112struct ref_lock *lock,2113const struct object_id *oid,const char*logmsg,2114struct strbuf *err)2115{2116files_assert_main_repository(refs,"commit_ref_update");21172118clear_loose_ref_cache(refs);2119if(files_log_ref_write(refs, lock->ref_name,2120&lock->old_oid, oid,2121 logmsg,0, err)) {2122char*old_msg =strbuf_detach(err, NULL);2123strbuf_addf(err,"cannot update the ref '%s':%s",2124 lock->ref_name, old_msg);2125free(old_msg);2126unlock_ref(lock);2127return-1;2128}21292130if(strcmp(lock->ref_name,"HEAD") !=0) {2131/*2132 * Special hack: If a branch is updated directly and HEAD2133 * points to it (may happen on the remote side of a push2134 * for example) then logically the HEAD reflog should be2135 * updated too.2136 * A generic solution implies reverse symref information,2137 * but finding all symrefs pointing to the given branch2138 * would be rather costly for this rare event (the direct2139 * update of a branch) to be worth it. So let's cheat and2140 * check with HEAD only which should cover 99% of all usage2141 * scenarios (even 100% of the default ones).2142 */2143struct object_id head_oid;2144int head_flag;2145const char*head_ref;21462147 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2148 RESOLVE_REF_READING,2149 head_oid.hash, &head_flag);2150if(head_ref && (head_flag & REF_ISSYMREF) &&2151!strcmp(head_ref, lock->ref_name)) {2152struct strbuf log_err = STRBUF_INIT;2153if(files_log_ref_write(refs,"HEAD",2154&lock->old_oid, oid,2155 logmsg,0, &log_err)) {2156error("%s", log_err.buf);2157strbuf_release(&log_err);2158}2159}2160}21612162if(commit_ref(lock)) {2163strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2164unlock_ref(lock);2165return-1;2166}21672168unlock_ref(lock);2169return0;2170}21712172static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2173{2174int ret = -1;2175#ifndef NO_SYMLINK_HEAD2176char*ref_path =get_locked_file_path(lock->lk);2177unlink(ref_path);2178 ret =symlink(target, ref_path);2179free(ref_path);21802181if(ret)2182fprintf(stderr,"no symlink - falling back to symbolic ref\n");2183#endif2184return ret;2185}21862187static voidupdate_symref_reflog(struct files_ref_store *refs,2188struct ref_lock *lock,const char*refname,2189const char*target,const char*logmsg)2190{2191struct strbuf err = STRBUF_INIT;2192struct object_id new_oid;2193if(logmsg &&2194!refs_read_ref_full(&refs->base, target,2195 RESOLVE_REF_READING, new_oid.hash, NULL) &&2196files_log_ref_write(refs, refname, &lock->old_oid,2197&new_oid, logmsg,0, &err)) {2198error("%s", err.buf);2199strbuf_release(&err);2200}2201}22022203static intcreate_symref_locked(struct files_ref_store *refs,2204struct ref_lock *lock,const char*refname,2205const char*target,const char*logmsg)2206{2207if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2208update_symref_reflog(refs, lock, refname, target, logmsg);2209return0;2210}22112212if(!fdopen_lock_file(lock->lk,"w"))2213returnerror("unable to fdopen%s:%s",2214 lock->lk->tempfile.filename.buf,strerror(errno));22152216update_symref_reflog(refs, lock, refname, target, logmsg);22172218/* no error check; commit_ref will check ferror */2219fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2220if(commit_ref(lock) <0)2221returnerror("unable to write symref for%s:%s", refname,2222strerror(errno));2223return0;2224}22252226static intfiles_create_symref(struct ref_store *ref_store,2227const char*refname,const char*target,2228const char*logmsg)2229{2230struct files_ref_store *refs =2231files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2232struct strbuf err = STRBUF_INIT;2233struct ref_lock *lock;2234int ret;22352236 lock =lock_ref_sha1_basic(refs, refname, NULL,2237 NULL, NULL, REF_NODEREF, NULL,2238&err);2239if(!lock) {2240error("%s", err.buf);2241strbuf_release(&err);2242return-1;2243}22442245 ret =create_symref_locked(refs, lock, refname, target, logmsg);2246unlock_ref(lock);2247return ret;2248}22492250static intfiles_reflog_exists(struct ref_store *ref_store,2251const char*refname)2252{2253struct files_ref_store *refs =2254files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2255struct strbuf sb = STRBUF_INIT;2256struct stat st;2257int ret;22582259files_reflog_path(refs, &sb, refname);2260 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2261strbuf_release(&sb);2262return ret;2263}22642265static intfiles_delete_reflog(struct ref_store *ref_store,2266const char*refname)2267{2268struct files_ref_store *refs =2269files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2270struct strbuf sb = STRBUF_INIT;2271int ret;22722273files_reflog_path(refs, &sb, refname);2274 ret =remove_path(sb.buf);2275strbuf_release(&sb);2276return ret;2277}22782279static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2280{2281struct object_id ooid, noid;2282char*email_end, *message;2283 timestamp_t timestamp;2284int tz;2285const char*p = sb->buf;22862287/* old SP new SP name <email> SP time TAB msg LF */2288if(!sb->len || sb->buf[sb->len -1] !='\n'||2289parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2290parse_oid_hex(p, &noid, &p) || *p++ !=' '||2291!(email_end =strchr(p,'>')) ||2292 email_end[1] !=' '||2293!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2294!message || message[0] !=' '||2295(message[1] !='+'&& message[1] !='-') ||2296!isdigit(message[2]) || !isdigit(message[3]) ||2297!isdigit(message[4]) || !isdigit(message[5]))2298return0;/* corrupt? */2299 email_end[1] ='\0';2300 tz =strtol(message +1, NULL,10);2301if(message[6] !='\t')2302 message +=6;2303else2304 message +=7;2305returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2306}23072308static char*find_beginning_of_line(char*bob,char*scan)2309{2310while(bob < scan && *(--scan) !='\n')2311;/* keep scanning backwards */2312/*2313 * Return either beginning of the buffer, or LF at the end of2314 * the previous line.2315 */2316return scan;2317}23182319static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2320const char*refname,2321 each_reflog_ent_fn fn,2322void*cb_data)2323{2324struct files_ref_store *refs =2325files_downcast(ref_store, REF_STORE_READ,2326"for_each_reflog_ent_reverse");2327struct strbuf sb = STRBUF_INIT;2328FILE*logfp;2329long pos;2330int ret =0, at_tail =1;23312332files_reflog_path(refs, &sb, refname);2333 logfp =fopen(sb.buf,"r");2334strbuf_release(&sb);2335if(!logfp)2336return-1;23372338/* Jump to the end */2339if(fseek(logfp,0, SEEK_END) <0)2340 ret =error("cannot seek back reflog for%s:%s",2341 refname,strerror(errno));2342 pos =ftell(logfp);2343while(!ret &&0< pos) {2344int cnt;2345size_t nread;2346char buf[BUFSIZ];2347char*endp, *scanp;23482349/* Fill next block from the end */2350 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2351if(fseek(logfp, pos - cnt, SEEK_SET)) {2352 ret =error("cannot seek back reflog for%s:%s",2353 refname,strerror(errno));2354break;2355}2356 nread =fread(buf, cnt,1, logfp);2357if(nread !=1) {2358 ret =error("cannot read%dbytes from reflog for%s:%s",2359 cnt, refname,strerror(errno));2360break;2361}2362 pos -= cnt;23632364 scanp = endp = buf + cnt;2365if(at_tail && scanp[-1] =='\n')2366/* Looking at the final LF at the end of the file */2367 scanp--;2368 at_tail =0;23692370while(buf < scanp) {2371/*2372 * terminating LF of the previous line, or the beginning2373 * of the buffer.2374 */2375char*bp;23762377 bp =find_beginning_of_line(buf, scanp);23782379if(*bp =='\n') {2380/*2381 * The newline is the end of the previous line,2382 * so we know we have complete line starting2383 * at (bp + 1). Prefix it onto any prior data2384 * we collected for the line and process it.2385 */2386strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2387 scanp = bp;2388 endp = bp +1;2389 ret =show_one_reflog_ent(&sb, fn, cb_data);2390strbuf_reset(&sb);2391if(ret)2392break;2393}else if(!pos) {2394/*2395 * We are at the start of the buffer, and the2396 * start of the file; there is no previous2397 * line, and we have everything for this one.2398 * Process it, and we can end the loop.2399 */2400strbuf_splice(&sb,0,0, buf, endp - buf);2401 ret =show_one_reflog_ent(&sb, fn, cb_data);2402strbuf_reset(&sb);2403break;2404}24052406if(bp == buf) {2407/*2408 * We are at the start of the buffer, and there2409 * is more file to read backwards. Which means2410 * we are in the middle of a line. Note that we2411 * may get here even if *bp was a newline; that2412 * just means we are at the exact end of the2413 * previous line, rather than some spot in the2414 * middle.2415 *2416 * Save away what we have to be combined with2417 * the data from the next read.2418 */2419strbuf_splice(&sb,0,0, buf, endp - buf);2420break;2421}2422}24232424}2425if(!ret && sb.len)2426die("BUG: reverse reflog parser had leftover data");24272428fclose(logfp);2429strbuf_release(&sb);2430return ret;2431}24322433static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2434const char*refname,2435 each_reflog_ent_fn fn,void*cb_data)2436{2437struct files_ref_store *refs =2438files_downcast(ref_store, REF_STORE_READ,2439"for_each_reflog_ent");2440FILE*logfp;2441struct strbuf sb = STRBUF_INIT;2442int ret =0;24432444files_reflog_path(refs, &sb, refname);2445 logfp =fopen(sb.buf,"r");2446strbuf_release(&sb);2447if(!logfp)2448return-1;24492450while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2451 ret =show_one_reflog_ent(&sb, fn, cb_data);2452fclose(logfp);2453strbuf_release(&sb);2454return ret;2455}24562457struct files_reflog_iterator {2458struct ref_iterator base;24592460struct ref_store *ref_store;2461struct dir_iterator *dir_iterator;2462struct object_id oid;2463};24642465static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2466{2467struct files_reflog_iterator *iter =2468(struct files_reflog_iterator *)ref_iterator;2469struct dir_iterator *diter = iter->dir_iterator;2470int ok;24712472while((ok =dir_iterator_advance(diter)) == ITER_OK) {2473int flags;24742475if(!S_ISREG(diter->st.st_mode))2476continue;2477if(diter->basename[0] =='.')2478continue;2479if(ends_with(diter->basename,".lock"))2480continue;24812482if(refs_read_ref_full(iter->ref_store,2483 diter->relative_path,0,2484 iter->oid.hash, &flags)) {2485error("bad ref for%s", diter->path.buf);2486continue;2487}24882489 iter->base.refname = diter->relative_path;2490 iter->base.oid = &iter->oid;2491 iter->base.flags = flags;2492return ITER_OK;2493}24942495 iter->dir_iterator = NULL;2496if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2497 ok = ITER_ERROR;2498return ok;2499}25002501static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2502struct object_id *peeled)2503{2504die("BUG: ref_iterator_peel() called for reflog_iterator");2505}25062507static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2508{2509struct files_reflog_iterator *iter =2510(struct files_reflog_iterator *)ref_iterator;2511int ok = ITER_DONE;25122513if(iter->dir_iterator)2514 ok =dir_iterator_abort(iter->dir_iterator);25152516base_ref_iterator_free(ref_iterator);2517return ok;2518}25192520static struct ref_iterator_vtable files_reflog_iterator_vtable = {2521 files_reflog_iterator_advance,2522 files_reflog_iterator_peel,2523 files_reflog_iterator_abort2524};25252526static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2527{2528struct files_ref_store *refs =2529files_downcast(ref_store, REF_STORE_READ,2530"reflog_iterator_begin");2531struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2532struct ref_iterator *ref_iterator = &iter->base;2533struct strbuf sb = STRBUF_INIT;25342535base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2536files_reflog_path(refs, &sb, NULL);2537 iter->dir_iterator =dir_iterator_begin(sb.buf);2538 iter->ref_store = ref_store;2539strbuf_release(&sb);2540return ref_iterator;2541}25422543/*2544 * If update is a direct update of head_ref (the reference pointed to2545 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2546 */2547static intsplit_head_update(struct ref_update *update,2548struct ref_transaction *transaction,2549const char*head_ref,2550struct string_list *affected_refnames,2551struct strbuf *err)2552{2553struct string_list_item *item;2554struct ref_update *new_update;25552556if((update->flags & REF_LOG_ONLY) ||2557(update->flags & REF_ISPRUNING) ||2558(update->flags & REF_UPDATE_VIA_HEAD))2559return0;25602561if(strcmp(update->refname, head_ref))2562return0;25632564/*2565 * First make sure that HEAD is not already in the2566 * transaction. This insertion is O(N) in the transaction2567 * size, but it happens at most once per transaction.2568 */2569 item =string_list_insert(affected_refnames,"HEAD");2570if(item->util) {2571/* An entry already existed */2572strbuf_addf(err,2573"multiple updates for 'HEAD' (including one "2574"via its referent '%s') are not allowed",2575 update->refname);2576return TRANSACTION_NAME_CONFLICT;2577}25782579 new_update =ref_transaction_add_update(2580 transaction,"HEAD",2581 update->flags | REF_LOG_ONLY | REF_NODEREF,2582 update->new_oid.hash, update->old_oid.hash,2583 update->msg);25842585 item->util = new_update;25862587return0;2588}25892590/*2591 * update is for a symref that points at referent and doesn't have2592 * REF_NODEREF set. Split it into two updates:2593 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2594 * - A new, separate update for the referent reference2595 * Note that the new update will itself be subject to splitting when2596 * the iteration gets to it.2597 */2598static intsplit_symref_update(struct files_ref_store *refs,2599struct ref_update *update,2600const char*referent,2601struct ref_transaction *transaction,2602struct string_list *affected_refnames,2603struct strbuf *err)2604{2605struct string_list_item *item;2606struct ref_update *new_update;2607unsigned int new_flags;26082609/*2610 * First make sure that referent is not already in the2611 * transaction. This insertion is O(N) in the transaction2612 * size, but it happens at most once per symref in a2613 * transaction.2614 */2615 item =string_list_insert(affected_refnames, referent);2616if(item->util) {2617/* An entry already existed */2618strbuf_addf(err,2619"multiple updates for '%s' (including one "2620"via symref '%s') are not allowed",2621 referent, update->refname);2622return TRANSACTION_NAME_CONFLICT;2623}26242625 new_flags = update->flags;2626if(!strcmp(update->refname,"HEAD")) {2627/*2628 * Record that the new update came via HEAD, so that2629 * when we process it, split_head_update() doesn't try2630 * to add another reflog update for HEAD. Note that2631 * this bit will be propagated if the new_update2632 * itself needs to be split.2633 */2634 new_flags |= REF_UPDATE_VIA_HEAD;2635}26362637 new_update =ref_transaction_add_update(2638 transaction, referent, new_flags,2639 update->new_oid.hash, update->old_oid.hash,2640 update->msg);26412642 new_update->parent_update = update;26432644/*2645 * Change the symbolic ref update to log only. Also, it2646 * doesn't need to check its old SHA-1 value, as that will be2647 * done when new_update is processed.2648 */2649 update->flags |= REF_LOG_ONLY | REF_NODEREF;2650 update->flags &= ~REF_HAVE_OLD;26512652 item->util = new_update;26532654return0;2655}26562657/*2658 * Return the refname under which update was originally requested.2659 */2660static const char*original_update_refname(struct ref_update *update)2661{2662while(update->parent_update)2663 update = update->parent_update;26642665return update->refname;2666}26672668/*2669 * Check whether the REF_HAVE_OLD and old_oid values stored in update2670 * are consistent with oid, which is the reference's current value. If2671 * everything is OK, return 0; otherwise, write an error message to2672 * err and return -1.2673 */2674static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2675struct strbuf *err)2676{2677if(!(update->flags & REF_HAVE_OLD) ||2678!oidcmp(oid, &update->old_oid))2679return0;26802681if(is_null_oid(&update->old_oid))2682strbuf_addf(err,"cannot lock ref '%s': "2683"reference already exists",2684original_update_refname(update));2685else if(is_null_oid(oid))2686strbuf_addf(err,"cannot lock ref '%s': "2687"reference is missing but expected%s",2688original_update_refname(update),2689oid_to_hex(&update->old_oid));2690else2691strbuf_addf(err,"cannot lock ref '%s': "2692"is at%sbut expected%s",2693original_update_refname(update),2694oid_to_hex(oid),2695oid_to_hex(&update->old_oid));26962697return-1;2698}26992700/*2701 * Prepare for carrying out update:2702 * - Lock the reference referred to by update.2703 * - Read the reference under lock.2704 * - Check that its old SHA-1 value (if specified) is correct, and in2705 * any case record it in update->lock->old_oid for later use when2706 * writing the reflog.2707 * - If it is a symref update without REF_NODEREF, split it up into a2708 * REF_LOG_ONLY update of the symref and add a separate update for2709 * the referent to transaction.2710 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2711 * update of HEAD.2712 */2713static intlock_ref_for_update(struct files_ref_store *refs,2714struct ref_update *update,2715struct ref_transaction *transaction,2716const char*head_ref,2717struct string_list *affected_refnames,2718struct strbuf *err)2719{2720struct strbuf referent = STRBUF_INIT;2721int mustexist = (update->flags & REF_HAVE_OLD) &&2722!is_null_oid(&update->old_oid);2723int ret;2724struct ref_lock *lock;27252726files_assert_main_repository(refs,"lock_ref_for_update");27272728if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2729 update->flags |= REF_DELETING;27302731if(head_ref) {2732 ret =split_head_update(update, transaction, head_ref,2733 affected_refnames, err);2734if(ret)2735return ret;2736}27372738 ret =lock_raw_ref(refs, update->refname, mustexist,2739 affected_refnames, NULL,2740&lock, &referent,2741&update->type, err);2742if(ret) {2743char*reason;27442745 reason =strbuf_detach(err, NULL);2746strbuf_addf(err,"cannot lock ref '%s':%s",2747original_update_refname(update), reason);2748free(reason);2749return ret;2750}27512752 update->backend_data = lock;27532754if(update->type & REF_ISSYMREF) {2755if(update->flags & REF_NODEREF) {2756/*2757 * We won't be reading the referent as part of2758 * the transaction, so we have to read it here2759 * to record and possibly check old_sha1:2760 */2761if(refs_read_ref_full(&refs->base,2762 referent.buf,0,2763 lock->old_oid.hash, NULL)) {2764if(update->flags & REF_HAVE_OLD) {2765strbuf_addf(err,"cannot lock ref '%s': "2766"error reading reference",2767original_update_refname(update));2768return-1;2769}2770}else if(check_old_oid(update, &lock->old_oid, err)) {2771return TRANSACTION_GENERIC_ERROR;2772}2773}else{2774/*2775 * Create a new update for the reference this2776 * symref is pointing at. Also, we will record2777 * and verify old_sha1 for this update as part2778 * of processing the split-off update, so we2779 * don't have to do it here.2780 */2781 ret =split_symref_update(refs, update,2782 referent.buf, transaction,2783 affected_refnames, err);2784if(ret)2785return ret;2786}2787}else{2788struct ref_update *parent_update;27892790if(check_old_oid(update, &lock->old_oid, err))2791return TRANSACTION_GENERIC_ERROR;27922793/*2794 * If this update is happening indirectly because of a2795 * symref update, record the old SHA-1 in the parent2796 * update:2797 */2798for(parent_update = update->parent_update;2799 parent_update;2800 parent_update = parent_update->parent_update) {2801struct ref_lock *parent_lock = parent_update->backend_data;2802oidcpy(&parent_lock->old_oid, &lock->old_oid);2803}2804}28052806if((update->flags & REF_HAVE_NEW) &&2807!(update->flags & REF_DELETING) &&2808!(update->flags & REF_LOG_ONLY)) {2809if(!(update->type & REF_ISSYMREF) &&2810!oidcmp(&lock->old_oid, &update->new_oid)) {2811/*2812 * The reference already has the desired2813 * value, so we don't need to write it.2814 */2815}else if(write_ref_to_lockfile(lock, &update->new_oid,2816 err)) {2817char*write_err =strbuf_detach(err, NULL);28182819/*2820 * The lock was freed upon failure of2821 * write_ref_to_lockfile():2822 */2823 update->backend_data = NULL;2824strbuf_addf(err,2825"cannot update ref '%s':%s",2826 update->refname, write_err);2827free(write_err);2828return TRANSACTION_GENERIC_ERROR;2829}else{2830 update->flags |= REF_NEEDS_COMMIT;2831}2832}2833if(!(update->flags & REF_NEEDS_COMMIT)) {2834/*2835 * We didn't call write_ref_to_lockfile(), so2836 * the lockfile is still open. Close it to2837 * free up the file descriptor:2838 */2839if(close_ref(lock)) {2840strbuf_addf(err,"couldn't close '%s.lock'",2841 update->refname);2842return TRANSACTION_GENERIC_ERROR;2843}2844}2845return0;2846}28472848/*2849 * Unlock any references in `transaction` that are still locked, and2850 * mark the transaction closed.2851 */2852static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2853{2854size_t i;28552856for(i =0; i < transaction->nr; i++) {2857struct ref_update *update = transaction->updates[i];2858struct ref_lock *lock = update->backend_data;28592860if(lock) {2861unlock_ref(lock);2862 update->backend_data = NULL;2863}2864}28652866 transaction->state = REF_TRANSACTION_CLOSED;2867}28682869static intfiles_transaction_prepare(struct ref_store *ref_store,2870struct ref_transaction *transaction,2871struct strbuf *err)2872{2873struct files_ref_store *refs =2874files_downcast(ref_store, REF_STORE_WRITE,2875"ref_transaction_prepare");2876size_t i;2877int ret =0;2878struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2879char*head_ref = NULL;2880int head_type;2881struct object_id head_oid;28822883assert(err);28842885if(!transaction->nr)2886goto cleanup;28872888/*2889 * Fail if a refname appears more than once in the2890 * transaction. (If we end up splitting up any updates using2891 * split_symref_update() or split_head_update(), those2892 * functions will check that the new updates don't have the2893 * same refname as any existing ones.)2894 */2895for(i =0; i < transaction->nr; i++) {2896struct ref_update *update = transaction->updates[i];2897struct string_list_item *item =2898string_list_append(&affected_refnames, update->refname);28992900/*2901 * We store a pointer to update in item->util, but at2902 * the moment we never use the value of this field2903 * except to check whether it is non-NULL.2904 */2905 item->util = update;2906}2907string_list_sort(&affected_refnames);2908if(ref_update_reject_duplicates(&affected_refnames, err)) {2909 ret = TRANSACTION_GENERIC_ERROR;2910goto cleanup;2911}29122913/*2914 * Special hack: If a branch is updated directly and HEAD2915 * points to it (may happen on the remote side of a push2916 * for example) then logically the HEAD reflog should be2917 * updated too.2918 *2919 * A generic solution would require reverse symref lookups,2920 * but finding all symrefs pointing to a given branch would be2921 * rather costly for this rare event (the direct update of a2922 * branch) to be worth it. So let's cheat and check with HEAD2923 * only, which should cover 99% of all usage scenarios (even2924 * 100% of the default ones).2925 *2926 * So if HEAD is a symbolic reference, then record the name of2927 * the reference that it points to. If we see an update of2928 * head_ref within the transaction, then split_head_update()2929 * arranges for the reflog of HEAD to be updated, too.2930 */2931 head_ref =refs_resolve_refdup(ref_store,"HEAD",2932 RESOLVE_REF_NO_RECURSE,2933 head_oid.hash, &head_type);29342935if(head_ref && !(head_type & REF_ISSYMREF)) {2936free(head_ref);2937 head_ref = NULL;2938}29392940/*2941 * Acquire all locks, verify old values if provided, check2942 * that new values are valid, and write new values to the2943 * lockfiles, ready to be activated. Only keep one lockfile2944 * open at a time to avoid running out of file descriptors.2945 * Note that lock_ref_for_update() might append more updates2946 * to the transaction.2947 */2948for(i =0; i < transaction->nr; i++) {2949struct ref_update *update = transaction->updates[i];29502951 ret =lock_ref_for_update(refs, update, transaction,2952 head_ref, &affected_refnames, err);2953if(ret)2954break;2955}29562957cleanup:2958free(head_ref);2959string_list_clear(&affected_refnames,0);29602961if(ret)2962files_transaction_cleanup(transaction);2963else2964 transaction->state = REF_TRANSACTION_PREPARED;29652966return ret;2967}29682969static intfiles_transaction_finish(struct ref_store *ref_store,2970struct ref_transaction *transaction,2971struct strbuf *err)2972{2973struct files_ref_store *refs =2974files_downcast(ref_store,0,"ref_transaction_finish");2975size_t i;2976int ret =0;2977struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2978struct string_list_item *ref_to_delete;2979struct strbuf sb = STRBUF_INIT;29802981assert(err);29822983if(!transaction->nr) {2984 transaction->state = REF_TRANSACTION_CLOSED;2985return0;2986}29872988/* Perform updates first so live commits remain referenced */2989for(i =0; i < transaction->nr; i++) {2990struct ref_update *update = transaction->updates[i];2991struct ref_lock *lock = update->backend_data;29922993if(update->flags & REF_NEEDS_COMMIT ||2994 update->flags & REF_LOG_ONLY) {2995if(files_log_ref_write(refs,2996 lock->ref_name,2997&lock->old_oid,2998&update->new_oid,2999 update->msg, update->flags,3000 err)) {3001char*old_msg =strbuf_detach(err, NULL);30023003strbuf_addf(err,"cannot update the ref '%s':%s",3004 lock->ref_name, old_msg);3005free(old_msg);3006unlock_ref(lock);3007 update->backend_data = NULL;3008 ret = TRANSACTION_GENERIC_ERROR;3009goto cleanup;3010}3011}3012if(update->flags & REF_NEEDS_COMMIT) {3013clear_loose_ref_cache(refs);3014if(commit_ref(lock)) {3015strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3016unlock_ref(lock);3017 update->backend_data = NULL;3018 ret = TRANSACTION_GENERIC_ERROR;3019goto cleanup;3020}3021}3022}3023/* Perform deletes now that updates are safely completed */3024for(i =0; i < transaction->nr; i++) {3025struct ref_update *update = transaction->updates[i];3026struct ref_lock *lock = update->backend_data;30273028if(update->flags & REF_DELETING &&3029!(update->flags & REF_LOG_ONLY)) {3030if(!(update->type & REF_ISPACKED) ||3031 update->type & REF_ISSYMREF) {3032/* It is a loose reference. */3033strbuf_reset(&sb);3034files_ref_path(refs, &sb, lock->ref_name);3035if(unlink_or_msg(sb.buf, err)) {3036 ret = TRANSACTION_GENERIC_ERROR;3037goto cleanup;3038}3039 update->flags |= REF_DELETED_LOOSE;3040}30413042if(!(update->flags & REF_ISPRUNING))3043string_list_append(&refs_to_delete,3044 lock->ref_name);3045}3046}30473048if(repack_without_refs(refs, &refs_to_delete, err)) {3049 ret = TRANSACTION_GENERIC_ERROR;3050goto cleanup;3051}30523053/* Delete the reflogs of any references that were deleted: */3054for_each_string_list_item(ref_to_delete, &refs_to_delete) {3055strbuf_reset(&sb);3056files_reflog_path(refs, &sb, ref_to_delete->string);3057if(!unlink_or_warn(sb.buf))3058try_remove_empty_parents(refs, ref_to_delete->string,3059 REMOVE_EMPTY_PARENTS_REFLOG);3060}30613062clear_loose_ref_cache(refs);30633064cleanup:3065files_transaction_cleanup(transaction);30663067for(i =0; i < transaction->nr; i++) {3068struct ref_update *update = transaction->updates[i];30693070if(update->flags & REF_DELETED_LOOSE) {3071/*3072 * The loose reference was deleted. Delete any3073 * empty parent directories. (Note that this3074 * can only work because we have already3075 * removed the lockfile.)3076 */3077try_remove_empty_parents(refs, update->refname,3078 REMOVE_EMPTY_PARENTS_REF);3079}3080}30813082strbuf_release(&sb);3083string_list_clear(&refs_to_delete,0);3084return ret;3085}30863087static intfiles_transaction_abort(struct ref_store *ref_store,3088struct ref_transaction *transaction,3089struct strbuf *err)3090{3091files_transaction_cleanup(transaction);3092return0;3093}30943095static intref_present(const char*refname,3096const struct object_id *oid,int flags,void*cb_data)3097{3098struct string_list *affected_refnames = cb_data;30993100returnstring_list_has_string(affected_refnames, refname);3101}31023103static intfiles_initial_transaction_commit(struct ref_store *ref_store,3104struct ref_transaction *transaction,3105struct strbuf *err)3106{3107struct files_ref_store *refs =3108files_downcast(ref_store, REF_STORE_WRITE,3109"initial_ref_transaction_commit");3110size_t i;3111int ret =0;3112struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31133114assert(err);31153116if(transaction->state != REF_TRANSACTION_OPEN)3117die("BUG: commit called for transaction that is not open");31183119/* Fail if a refname appears more than once in the transaction: */3120for(i =0; i < transaction->nr; i++)3121string_list_append(&affected_refnames,3122 transaction->updates[i]->refname);3123string_list_sort(&affected_refnames);3124if(ref_update_reject_duplicates(&affected_refnames, err)) {3125 ret = TRANSACTION_GENERIC_ERROR;3126goto cleanup;3127}31283129/*3130 * It's really undefined to call this function in an active3131 * repository or when there are existing references: we are3132 * only locking and changing packed-refs, so (1) any3133 * simultaneous processes might try to change a reference at3134 * the same time we do, and (2) any existing loose versions of3135 * the references that we are setting would have precedence3136 * over our values. But some remote helpers create the remote3137 * "HEAD" and "master" branches before calling this function,3138 * so here we really only check that none of the references3139 * that we are creating already exists.3140 */3141if(refs_for_each_rawref(&refs->base, ref_present,3142&affected_refnames))3143die("BUG: initial ref transaction called with existing refs");31443145for(i =0; i < transaction->nr; i++) {3146struct ref_update *update = transaction->updates[i];31473148if((update->flags & REF_HAVE_OLD) &&3149!is_null_oid(&update->old_oid))3150die("BUG: initial ref transaction with old_sha1 set");3151if(refs_verify_refname_available(&refs->base, update->refname,3152&affected_refnames, NULL,3153 err)) {3154 ret = TRANSACTION_NAME_CONFLICT;3155goto cleanup;3156}3157}31583159if(lock_packed_refs(refs,0)) {3160strbuf_addf(err,"unable to lock packed-refs file:%s",3161strerror(errno));3162 ret = TRANSACTION_GENERIC_ERROR;3163goto cleanup;3164}31653166for(i =0; i < transaction->nr; i++) {3167struct ref_update *update = transaction->updates[i];31683169if((update->flags & REF_HAVE_NEW) &&3170!is_null_oid(&update->new_oid))3171add_packed_ref(refs, update->refname,3172&update->new_oid);3173}31743175if(commit_packed_refs(refs)) {3176strbuf_addf(err,"unable to commit packed-refs file:%s",3177strerror(errno));3178 ret = TRANSACTION_GENERIC_ERROR;3179goto cleanup;3180}31813182cleanup:3183 transaction->state = REF_TRANSACTION_CLOSED;3184string_list_clear(&affected_refnames,0);3185return ret;3186}31873188struct expire_reflog_cb {3189unsigned int flags;3190 reflog_expiry_should_prune_fn *should_prune_fn;3191void*policy_cb;3192FILE*newlog;3193struct object_id last_kept_oid;3194};31953196static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3197const char*email, timestamp_t timestamp,int tz,3198const char*message,void*cb_data)3199{3200struct expire_reflog_cb *cb = cb_data;3201struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32023203if(cb->flags & EXPIRE_REFLOGS_REWRITE)3204 ooid = &cb->last_kept_oid;32053206if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3207 message, policy_cb)) {3208if(!cb->newlog)3209printf("would prune%s", message);3210else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3211printf("prune%s", message);3212}else{3213if(cb->newlog) {3214fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3215oid_to_hex(ooid),oid_to_hex(noid),3216 email, timestamp, tz, message);3217oidcpy(&cb->last_kept_oid, noid);3218}3219if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3220printf("keep%s", message);3221}3222return0;3223}32243225static intfiles_reflog_expire(struct ref_store *ref_store,3226const char*refname,const unsigned char*sha1,3227unsigned int flags,3228 reflog_expiry_prepare_fn prepare_fn,3229 reflog_expiry_should_prune_fn should_prune_fn,3230 reflog_expiry_cleanup_fn cleanup_fn,3231void*policy_cb_data)3232{3233struct files_ref_store *refs =3234files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3235static struct lock_file reflog_lock;3236struct expire_reflog_cb cb;3237struct ref_lock *lock;3238struct strbuf log_file_sb = STRBUF_INIT;3239char*log_file;3240int status =0;3241int type;3242struct strbuf err = STRBUF_INIT;3243struct object_id oid;32443245memset(&cb,0,sizeof(cb));3246 cb.flags = flags;3247 cb.policy_cb = policy_cb_data;3248 cb.should_prune_fn = should_prune_fn;32493250/*3251 * The reflog file is locked by holding the lock on the3252 * reference itself, plus we might need to update the3253 * reference if --updateref was specified:3254 */3255 lock =lock_ref_sha1_basic(refs, refname, sha1,3256 NULL, NULL, REF_NODEREF,3257&type, &err);3258if(!lock) {3259error("cannot lock ref '%s':%s", refname, err.buf);3260strbuf_release(&err);3261return-1;3262}3263if(!refs_reflog_exists(ref_store, refname)) {3264unlock_ref(lock);3265return0;3266}32673268files_reflog_path(refs, &log_file_sb, refname);3269 log_file =strbuf_detach(&log_file_sb, NULL);3270if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3271/*3272 * Even though holding $GIT_DIR/logs/$reflog.lock has3273 * no locking implications, we use the lock_file3274 * machinery here anyway because it does a lot of the3275 * work we need, including cleaning up if the program3276 * exits unexpectedly.3277 */3278if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3279struct strbuf err = STRBUF_INIT;3280unable_to_lock_message(log_file, errno, &err);3281error("%s", err.buf);3282strbuf_release(&err);3283goto failure;3284}3285 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3286if(!cb.newlog) {3287error("cannot fdopen%s(%s)",3288get_lock_file_path(&reflog_lock),strerror(errno));3289goto failure;3290}3291}32923293hashcpy(oid.hash, sha1);32943295(*prepare_fn)(refname, &oid, cb.policy_cb);3296refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3297(*cleanup_fn)(cb.policy_cb);32983299if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3300/*3301 * It doesn't make sense to adjust a reference pointed3302 * to by a symbolic ref based on expiring entries in3303 * the symbolic reference's reflog. Nor can we update3304 * a reference if there are no remaining reflog3305 * entries.3306 */3307int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3308!(type & REF_ISSYMREF) &&3309!is_null_oid(&cb.last_kept_oid);33103311if(close_lock_file(&reflog_lock)) {3312 status |=error("couldn't write%s:%s", log_file,3313strerror(errno));3314}else if(update &&3315(write_in_full(get_lock_file_fd(lock->lk),3316oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3317write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3318close_ref(lock) <0)) {3319 status |=error("couldn't write%s",3320get_lock_file_path(lock->lk));3321rollback_lock_file(&reflog_lock);3322}else if(commit_lock_file(&reflog_lock)) {3323 status |=error("unable to write reflog '%s' (%s)",3324 log_file,strerror(errno));3325}else if(update &&commit_ref(lock)) {3326 status |=error("couldn't set%s", lock->ref_name);3327}3328}3329free(log_file);3330unlock_ref(lock);3331return status;33323333 failure:3334rollback_lock_file(&reflog_lock);3335free(log_file);3336unlock_ref(lock);3337return-1;3338}33393340static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3341{3342struct files_ref_store *refs =3343files_downcast(ref_store, REF_STORE_WRITE,"init_db");3344struct strbuf sb = STRBUF_INIT;33453346/*3347 * Create .git/refs/{heads,tags}3348 */3349files_ref_path(refs, &sb,"refs/heads");3350safe_create_dir(sb.buf,1);33513352strbuf_reset(&sb);3353files_ref_path(refs, &sb,"refs/tags");3354safe_create_dir(sb.buf,1);33553356strbuf_release(&sb);3357return0;3358}33593360struct ref_storage_be refs_be_files = {3361 NULL,3362"files",3363 files_ref_store_create,3364 files_init_db,3365 files_transaction_prepare,3366 files_transaction_finish,3367 files_transaction_abort,3368 files_initial_transaction_commit,33693370 files_pack_refs,3371 files_peel_ref,3372 files_create_symref,3373 files_delete_refs,3374 files_rename_ref,33753376 files_ref_iterator_begin,3377 files_read_raw_ref,33783379 files_reflog_iterator_begin,3380 files_for_each_reflog_ent,3381 files_for_each_reflog_ent_reverse,3382 files_reflog_exists,3383 files_create_reflog,3384 files_delete_reflog,3385 files_reflog_expire3386};