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/* 47 * Iff the packed-refs file associated with this instance is 48 * currently locked for writing, this points at the associated 49 * lock (which is owned by somebody else). The referrer count 50 * is also incremented when the file is locked and decremented 51 * when it is unlocked. 52 */ 53struct lock_file *lock; 54 55/* The metadata from when this packed-refs cache was read */ 56struct stat_validity validity; 57}; 58 59/* 60 * Future: need to be in "struct repository" 61 * when doing a full libification. 62 */ 63struct files_ref_store { 64struct ref_store base; 65unsigned int store_flags; 66 67char*gitdir; 68char*gitcommondir; 69char*packed_refs_path; 70 71struct ref_cache *loose; 72struct packed_ref_cache *packed; 73}; 74 75/* Lock used for the main packed-refs file: */ 76static struct lock_file packlock; 77 78/* 79 * Increment the reference count of *packed_refs. 80 */ 81static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 82{ 83 packed_refs->referrers++; 84} 85 86/* 87 * Decrease the reference count of *packed_refs. If it goes to zero, 88 * free *packed_refs and return true; otherwise return false. 89 */ 90static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 91{ 92if(!--packed_refs->referrers) { 93free_ref_cache(packed_refs->cache); 94stat_validity_clear(&packed_refs->validity); 95free(packed_refs); 96return1; 97}else{ 98return0; 99} 100} 101 102static voidclear_packed_ref_cache(struct files_ref_store *refs) 103{ 104if(refs->packed) { 105struct packed_ref_cache *packed_refs = refs->packed; 106 107if(packed_refs->lock) 108die("internal error: packed-ref cache cleared while locked"); 109 refs->packed = NULL; 110release_packed_ref_cache(packed_refs); 111} 112} 113 114static voidclear_loose_ref_cache(struct files_ref_store *refs) 115{ 116if(refs->loose) { 117free_ref_cache(refs->loose); 118 refs->loose = NULL; 119} 120} 121 122/* 123 * Create a new submodule ref cache and add it to the internal 124 * set of caches. 125 */ 126static struct ref_store *files_ref_store_create(const char*gitdir, 127unsigned int flags) 128{ 129struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 130struct ref_store *ref_store = (struct ref_store *)refs; 131struct strbuf sb = STRBUF_INIT; 132 133base_ref_store_init(ref_store, &refs_be_files); 134 refs->store_flags = flags; 135 136 refs->gitdir =xstrdup(gitdir); 137get_common_dir_noenv(&sb, gitdir); 138 refs->gitcommondir =strbuf_detach(&sb, NULL); 139strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 140 refs->packed_refs_path =strbuf_detach(&sb, NULL); 141 142return ref_store; 143} 144 145/* 146 * Die if refs is not the main ref store. caller is used in any 147 * necessary error messages. 148 */ 149static voidfiles_assert_main_repository(struct files_ref_store *refs, 150const char*caller) 151{ 152if(refs->store_flags & REF_STORE_MAIN) 153return; 154 155die("BUG: operation%sonly allowed for main ref store", caller); 156} 157 158/* 159 * Downcast ref_store to files_ref_store. Die if ref_store is not a 160 * files_ref_store. required_flags is compared with ref_store's 161 * store_flags to ensure the ref_store has all required capabilities. 162 * "caller" is used in any necessary error messages. 163 */ 164static struct files_ref_store *files_downcast(struct ref_store *ref_store, 165unsigned int required_flags, 166const char*caller) 167{ 168struct files_ref_store *refs; 169 170if(ref_store->be != &refs_be_files) 171die("BUG: ref_store is type\"%s\"not\"files\"in%s", 172 ref_store->be->name, caller); 173 174 refs = (struct files_ref_store *)ref_store; 175 176if((refs->store_flags & required_flags) != required_flags) 177die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 178 caller, required_flags, refs->store_flags); 179 180return refs; 181} 182 183/* The length of a peeled reference line in packed-refs, including EOL: */ 184#define PEELED_LINE_LENGTH 42 185 186/* 187 * The packed-refs header line that we write out. Perhaps other 188 * traits will be added later. The trailing space is required. 189 */ 190static const char PACKED_REFS_HEADER[] = 191"# pack-refs with: peeled fully-peeled\n"; 192 193/* 194 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 195 * Return a pointer to the refname within the line (null-terminated), 196 * or NULL if there was a problem. 197 */ 198static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 199{ 200const char*ref; 201 202if(parse_oid_hex(line->buf, oid, &ref) <0) 203return NULL; 204if(!isspace(*ref++)) 205return NULL; 206 207if(isspace(*ref)) 208return NULL; 209 210if(line->buf[line->len -1] !='\n') 211return NULL; 212 line->buf[--line->len] =0; 213 214return ref; 215} 216 217/* 218 * Read f, which is a packed-refs file, into dir. 219 * 220 * A comment line of the form "# pack-refs with: " may contain zero or 221 * more traits. We interpret the traits as follows: 222 * 223 * No traits: 224 * 225 * Probably no references are peeled. But if the file contains a 226 * peeled value for a reference, we will use it. 227 * 228 * peeled: 229 * 230 * References under "refs/tags/", if they *can* be peeled, *are* 231 * peeled in this file. References outside of "refs/tags/" are 232 * probably not peeled even if they could have been, but if we find 233 * a peeled value for such a reference we will use it. 234 * 235 * fully-peeled: 236 * 237 * All references in the file that can be peeled are peeled. 238 * Inversely (and this is more important), any references in the 239 * file for which no peeled value is recorded is not peelable. This 240 * trait should typically be written alongside "peeled" for 241 * compatibility with older clients, but we do not require it 242 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 243 */ 244static voidread_packed_refs(FILE*f,struct ref_dir *dir) 245{ 246struct ref_entry *last = NULL; 247struct strbuf line = STRBUF_INIT; 248enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 249 250while(strbuf_getwholeline(&line, f,'\n') != EOF) { 251struct object_id oid; 252const char*refname; 253const char*traits; 254 255if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 256if(strstr(traits," fully-peeled ")) 257 peeled = PEELED_FULLY; 258else if(strstr(traits," peeled ")) 259 peeled = PEELED_TAGS; 260/* perhaps other traits later as well */ 261continue; 262} 263 264 refname =parse_ref_line(&line, &oid); 265if(refname) { 266int flag = REF_ISPACKED; 267 268if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 269if(!refname_is_safe(refname)) 270die("packed refname is dangerous:%s", refname); 271oidclr(&oid); 272 flag |= REF_BAD_NAME | REF_ISBROKEN; 273} 274 last =create_ref_entry(refname, &oid, flag,0); 275if(peeled == PEELED_FULLY || 276(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 277 last->flag |= REF_KNOWS_PEELED; 278add_ref_entry(dir, last); 279continue; 280} 281if(last && 282 line.buf[0] =='^'&& 283 line.len == PEELED_LINE_LENGTH && 284 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 285!get_oid_hex(line.buf +1, &oid)) { 286oidcpy(&last->u.value.peeled, &oid); 287/* 288 * Regardless of what the file header said, 289 * we definitely know the value of *this* 290 * reference: 291 */ 292 last->flag |= REF_KNOWS_PEELED; 293} 294} 295 296strbuf_release(&line); 297} 298 299static const char*files_packed_refs_path(struct files_ref_store *refs) 300{ 301return refs->packed_refs_path; 302} 303 304static voidfiles_reflog_path(struct files_ref_store *refs, 305struct strbuf *sb, 306const char*refname) 307{ 308if(!refname) { 309/* 310 * FIXME: of course this is wrong in multi worktree 311 * setting. To be fixed real soon. 312 */ 313strbuf_addf(sb,"%s/logs", refs->gitcommondir); 314return; 315} 316 317switch(ref_type(refname)) { 318case REF_TYPE_PER_WORKTREE: 319case REF_TYPE_PSEUDOREF: 320strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 321break; 322case REF_TYPE_NORMAL: 323strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 324break; 325default: 326die("BUG: unknown ref type%dof ref%s", 327ref_type(refname), refname); 328} 329} 330 331static voidfiles_ref_path(struct files_ref_store *refs, 332struct strbuf *sb, 333const char*refname) 334{ 335switch(ref_type(refname)) { 336case REF_TYPE_PER_WORKTREE: 337case REF_TYPE_PSEUDOREF: 338strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 339break; 340case REF_TYPE_NORMAL: 341strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 342break; 343default: 344die("BUG: unknown ref type%dof ref%s", 345ref_type(refname), refname); 346} 347} 348 349/* 350 * Get the packed_ref_cache for the specified files_ref_store, 351 * creating it if necessary. 352 */ 353static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 354{ 355const char*packed_refs_file =files_packed_refs_path(refs); 356 357if(refs->packed && 358!stat_validity_check(&refs->packed->validity, packed_refs_file)) 359clear_packed_ref_cache(refs); 360 361if(!refs->packed) { 362FILE*f; 363 364 refs->packed =xcalloc(1,sizeof(*refs->packed)); 365acquire_packed_ref_cache(refs->packed); 366 refs->packed->cache =create_ref_cache(&refs->base, NULL); 367 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 368 f =fopen(packed_refs_file,"r"); 369if(f) { 370stat_validity_update(&refs->packed->validity,fileno(f)); 371read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 372fclose(f); 373} 374} 375return refs->packed; 376} 377 378static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 379{ 380returnget_ref_dir(packed_ref_cache->cache->root); 381} 382 383static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 384{ 385returnget_packed_ref_dir(get_packed_ref_cache(refs)); 386} 387 388/* 389 * Add a reference to the in-memory packed reference cache. This may 390 * only be called while the packed-refs file is locked (see 391 * lock_packed_refs()). To actually write the packed-refs file, call 392 * commit_packed_refs(). 393 */ 394static voidadd_packed_ref(struct files_ref_store *refs, 395const char*refname,const struct object_id *oid) 396{ 397struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 398 399if(!packed_ref_cache->lock) 400die("internal error: packed refs not locked"); 401add_ref_entry(get_packed_ref_dir(packed_ref_cache), 402create_ref_entry(refname, oid, REF_ISPACKED,1)); 403} 404 405/* 406 * Read the loose references from the namespace dirname into dir 407 * (without recursing). dirname must end with '/'. dir must be the 408 * directory entry corresponding to dirname. 409 */ 410static voidloose_fill_ref_dir(struct ref_store *ref_store, 411struct ref_dir *dir,const char*dirname) 412{ 413struct files_ref_store *refs = 414files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 415DIR*d; 416struct dirent *de; 417int dirnamelen =strlen(dirname); 418struct strbuf refname; 419struct strbuf path = STRBUF_INIT; 420size_t path_baselen; 421 422files_ref_path(refs, &path, dirname); 423 path_baselen = path.len; 424 425 d =opendir(path.buf); 426if(!d) { 427strbuf_release(&path); 428return; 429} 430 431strbuf_init(&refname, dirnamelen +257); 432strbuf_add(&refname, dirname, dirnamelen); 433 434while((de =readdir(d)) != NULL) { 435struct object_id oid; 436struct stat st; 437int flag; 438 439if(de->d_name[0] =='.') 440continue; 441if(ends_with(de->d_name,".lock")) 442continue; 443strbuf_addstr(&refname, de->d_name); 444strbuf_addstr(&path, de->d_name); 445if(stat(path.buf, &st) <0) { 446;/* silently ignore */ 447}else if(S_ISDIR(st.st_mode)) { 448strbuf_addch(&refname,'/'); 449add_entry_to_dir(dir, 450create_dir_entry(dir->cache, refname.buf, 451 refname.len,1)); 452}else{ 453if(!refs_resolve_ref_unsafe(&refs->base, 454 refname.buf, 455 RESOLVE_REF_READING, 456 oid.hash, &flag)) { 457oidclr(&oid); 458 flag |= REF_ISBROKEN; 459}else if(is_null_oid(&oid)) { 460/* 461 * It is so astronomically unlikely 462 * that NULL_SHA1 is the SHA-1 of an 463 * actual object that we consider its 464 * appearance in a loose reference 465 * file to be repo corruption 466 * (probably due to a software bug). 467 */ 468 flag |= REF_ISBROKEN; 469} 470 471if(check_refname_format(refname.buf, 472 REFNAME_ALLOW_ONELEVEL)) { 473if(!refname_is_safe(refname.buf)) 474die("loose refname is dangerous:%s", refname.buf); 475oidclr(&oid); 476 flag |= REF_BAD_NAME | REF_ISBROKEN; 477} 478add_entry_to_dir(dir, 479create_ref_entry(refname.buf, &oid, flag,0)); 480} 481strbuf_setlen(&refname, dirnamelen); 482strbuf_setlen(&path, path_baselen); 483} 484strbuf_release(&refname); 485strbuf_release(&path); 486closedir(d); 487 488/* 489 * Manually add refs/bisect, which, being per-worktree, might 490 * not appear in the directory listing for refs/ in the main 491 * repo. 492 */ 493if(!strcmp(dirname,"refs/")) { 494int pos =search_ref_dir(dir,"refs/bisect/",12); 495 496if(pos <0) { 497struct ref_entry *child_entry =create_dir_entry( 498 dir->cache,"refs/bisect/",12,1); 499add_entry_to_dir(dir, child_entry); 500} 501} 502} 503 504static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 505{ 506if(!refs->loose) { 507/* 508 * Mark the top-level directory complete because we 509 * are about to read the only subdirectory that can 510 * hold references: 511 */ 512 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 513 514/* We're going to fill the top level ourselves: */ 515 refs->loose->root->flag &= ~REF_INCOMPLETE; 516 517/* 518 * Add an incomplete entry for "refs/" (to be filled 519 * lazily): 520 */ 521add_entry_to_dir(get_ref_dir(refs->loose->root), 522create_dir_entry(refs->loose,"refs/",5,1)); 523} 524return refs->loose; 525} 526 527/* 528 * Return the ref_entry for the given refname from the packed 529 * references. If it does not exist, return NULL. 530 */ 531static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 532const char*refname) 533{ 534returnfind_ref_entry(get_packed_refs(refs), refname); 535} 536 537/* 538 * A loose ref file doesn't exist; check for a packed ref. 539 */ 540static intresolve_packed_ref(struct files_ref_store *refs, 541const char*refname, 542unsigned char*sha1,unsigned int*flags) 543{ 544struct ref_entry *entry; 545 546/* 547 * The loose reference file does not exist; check for a packed 548 * reference. 549 */ 550 entry =get_packed_ref(refs, refname); 551if(entry) { 552hashcpy(sha1, entry->u.value.oid.hash); 553*flags |= REF_ISPACKED; 554return0; 555} 556/* refname is not a packed reference. */ 557return-1; 558} 559 560static intfiles_read_raw_ref(struct ref_store *ref_store, 561const char*refname,unsigned char*sha1, 562struct strbuf *referent,unsigned int*type) 563{ 564struct files_ref_store *refs = 565files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 566struct strbuf sb_contents = STRBUF_INIT; 567struct strbuf sb_path = STRBUF_INIT; 568const char*path; 569const char*buf; 570struct stat st; 571int fd; 572int ret = -1; 573int save_errno; 574int remaining_retries =3; 575 576*type =0; 577strbuf_reset(&sb_path); 578 579files_ref_path(refs, &sb_path, refname); 580 581 path = sb_path.buf; 582 583stat_ref: 584/* 585 * We might have to loop back here to avoid a race 586 * condition: first we lstat() the file, then we try 587 * to read it as a link or as a file. But if somebody 588 * changes the type of the file (file <-> directory 589 * <-> symlink) between the lstat() and reading, then 590 * we don't want to report that as an error but rather 591 * try again starting with the lstat(). 592 * 593 * We'll keep a count of the retries, though, just to avoid 594 * any confusing situation sending us into an infinite loop. 595 */ 596 597if(remaining_retries-- <=0) 598goto out; 599 600if(lstat(path, &st) <0) { 601if(errno != ENOENT) 602goto out; 603if(resolve_packed_ref(refs, refname, sha1, type)) { 604 errno = ENOENT; 605goto out; 606} 607 ret =0; 608goto out; 609} 610 611/* Follow "normalized" - ie "refs/.." symlinks by hand */ 612if(S_ISLNK(st.st_mode)) { 613strbuf_reset(&sb_contents); 614if(strbuf_readlink(&sb_contents, path,0) <0) { 615if(errno == ENOENT || errno == EINVAL) 616/* inconsistent with lstat; retry */ 617goto stat_ref; 618else 619goto out; 620} 621if(starts_with(sb_contents.buf,"refs/") && 622!check_refname_format(sb_contents.buf,0)) { 623strbuf_swap(&sb_contents, referent); 624*type |= REF_ISSYMREF; 625 ret =0; 626goto out; 627} 628/* 629 * It doesn't look like a refname; fall through to just 630 * treating it like a non-symlink, and reading whatever it 631 * points to. 632 */ 633} 634 635/* Is it a directory? */ 636if(S_ISDIR(st.st_mode)) { 637/* 638 * Even though there is a directory where the loose 639 * ref is supposed to be, there could still be a 640 * packed ref: 641 */ 642if(resolve_packed_ref(refs, refname, sha1, type)) { 643 errno = EISDIR; 644goto out; 645} 646 ret =0; 647goto out; 648} 649 650/* 651 * Anything else, just open it and try to use it as 652 * a ref 653 */ 654 fd =open(path, O_RDONLY); 655if(fd <0) { 656if(errno == ENOENT && !S_ISLNK(st.st_mode)) 657/* inconsistent with lstat; retry */ 658goto stat_ref; 659else 660goto out; 661} 662strbuf_reset(&sb_contents); 663if(strbuf_read(&sb_contents, fd,256) <0) { 664int save_errno = errno; 665close(fd); 666 errno = save_errno; 667goto out; 668} 669close(fd); 670strbuf_rtrim(&sb_contents); 671 buf = sb_contents.buf; 672if(starts_with(buf,"ref:")) { 673 buf +=4; 674while(isspace(*buf)) 675 buf++; 676 677strbuf_reset(referent); 678strbuf_addstr(referent, buf); 679*type |= REF_ISSYMREF; 680 ret =0; 681goto out; 682} 683 684/* 685 * Please note that FETCH_HEAD has additional 686 * data after the sha. 687 */ 688if(get_sha1_hex(buf, sha1) || 689(buf[40] !='\0'&& !isspace(buf[40]))) { 690*type |= REF_ISBROKEN; 691 errno = EINVAL; 692goto out; 693} 694 695 ret =0; 696 697out: 698 save_errno = errno; 699strbuf_release(&sb_path); 700strbuf_release(&sb_contents); 701 errno = save_errno; 702return ret; 703} 704 705static voidunlock_ref(struct ref_lock *lock) 706{ 707/* Do not free lock->lk -- atexit() still looks at them */ 708if(lock->lk) 709rollback_lock_file(lock->lk); 710free(lock->ref_name); 711free(lock); 712} 713 714/* 715 * Lock refname, without following symrefs, and set *lock_p to point 716 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 717 * and type similarly to read_raw_ref(). 718 * 719 * The caller must verify that refname is a "safe" reference name (in 720 * the sense of refname_is_safe()) before calling this function. 721 * 722 * If the reference doesn't already exist, verify that refname doesn't 723 * have a D/F conflict with any existing references. extras and skip 724 * are passed to refs_verify_refname_available() for this check. 725 * 726 * If mustexist is not set and the reference is not found or is 727 * broken, lock the reference anyway but clear sha1. 728 * 729 * Return 0 on success. On failure, write an error message to err and 730 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 731 * 732 * Implementation note: This function is basically 733 * 734 * lock reference 735 * read_raw_ref() 736 * 737 * but it includes a lot more code to 738 * - Deal with possible races with other processes 739 * - Avoid calling refs_verify_refname_available() when it can be 740 * avoided, namely if we were successfully able to read the ref 741 * - Generate informative error messages in the case of failure 742 */ 743static intlock_raw_ref(struct files_ref_store *refs, 744const char*refname,int mustexist, 745const struct string_list *extras, 746const struct string_list *skip, 747struct ref_lock **lock_p, 748struct strbuf *referent, 749unsigned int*type, 750struct strbuf *err) 751{ 752struct ref_lock *lock; 753struct strbuf ref_file = STRBUF_INIT; 754int attempts_remaining =3; 755int ret = TRANSACTION_GENERIC_ERROR; 756 757assert(err); 758files_assert_main_repository(refs,"lock_raw_ref"); 759 760*type =0; 761 762/* First lock the file so it can't change out from under us. */ 763 764*lock_p = lock =xcalloc(1,sizeof(*lock)); 765 766 lock->ref_name =xstrdup(refname); 767files_ref_path(refs, &ref_file, refname); 768 769retry: 770switch(safe_create_leading_directories(ref_file.buf)) { 771case SCLD_OK: 772break;/* success */ 773case SCLD_EXISTS: 774/* 775 * Suppose refname is "refs/foo/bar". We just failed 776 * to create the containing directory, "refs/foo", 777 * because there was a non-directory in the way. This 778 * indicates a D/F conflict, probably because of 779 * another reference such as "refs/foo". There is no 780 * reason to expect this error to be transitory. 781 */ 782if(refs_verify_refname_available(&refs->base, refname, 783 extras, skip, err)) { 784if(mustexist) { 785/* 786 * To the user the relevant error is 787 * that the "mustexist" reference is 788 * missing: 789 */ 790strbuf_reset(err); 791strbuf_addf(err,"unable to resolve reference '%s'", 792 refname); 793}else{ 794/* 795 * The error message set by 796 * refs_verify_refname_available() is 797 * OK. 798 */ 799 ret = TRANSACTION_NAME_CONFLICT; 800} 801}else{ 802/* 803 * The file that is in the way isn't a loose 804 * reference. Report it as a low-level 805 * failure. 806 */ 807strbuf_addf(err,"unable to create lock file%s.lock; " 808"non-directory in the way", 809 ref_file.buf); 810} 811goto error_return; 812case SCLD_VANISHED: 813/* Maybe another process was tidying up. Try again. */ 814if(--attempts_remaining >0) 815goto retry; 816/* fall through */ 817default: 818strbuf_addf(err,"unable to create directory for%s", 819 ref_file.buf); 820goto error_return; 821} 822 823if(!lock->lk) 824 lock->lk =xcalloc(1,sizeof(struct lock_file)); 825 826if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 827if(errno == ENOENT && --attempts_remaining >0) { 828/* 829 * Maybe somebody just deleted one of the 830 * directories leading to ref_file. Try 831 * again: 832 */ 833goto retry; 834}else{ 835unable_to_lock_message(ref_file.buf, errno, err); 836goto error_return; 837} 838} 839 840/* 841 * Now we hold the lock and can read the reference without 842 * fear that its value will change. 843 */ 844 845if(files_read_raw_ref(&refs->base, refname, 846 lock->old_oid.hash, referent, type)) { 847if(errno == ENOENT) { 848if(mustexist) { 849/* Garden variety missing reference. */ 850strbuf_addf(err,"unable to resolve reference '%s'", 851 refname); 852goto error_return; 853}else{ 854/* 855 * Reference is missing, but that's OK. We 856 * know that there is not a conflict with 857 * another loose reference because 858 * (supposing that we are trying to lock 859 * reference "refs/foo/bar"): 860 * 861 * - We were successfully able to create 862 * the lockfile refs/foo/bar.lock, so we 863 * know there cannot be a loose reference 864 * named "refs/foo". 865 * 866 * - We got ENOENT and not EISDIR, so we 867 * know that there cannot be a loose 868 * reference named "refs/foo/bar/baz". 869 */ 870} 871}else if(errno == EISDIR) { 872/* 873 * There is a directory in the way. It might have 874 * contained references that have been deleted. If 875 * we don't require that the reference already 876 * exists, try to remove the directory so that it 877 * doesn't cause trouble when we want to rename the 878 * lockfile into place later. 879 */ 880if(mustexist) { 881/* Garden variety missing reference. */ 882strbuf_addf(err,"unable to resolve reference '%s'", 883 refname); 884goto error_return; 885}else if(remove_dir_recursively(&ref_file, 886 REMOVE_DIR_EMPTY_ONLY)) { 887if(refs_verify_refname_available( 888&refs->base, refname, 889 extras, skip, err)) { 890/* 891 * The error message set by 892 * verify_refname_available() is OK. 893 */ 894 ret = TRANSACTION_NAME_CONFLICT; 895goto error_return; 896}else{ 897/* 898 * We can't delete the directory, 899 * but we also don't know of any 900 * references that it should 901 * contain. 902 */ 903strbuf_addf(err,"there is a non-empty directory '%s' " 904"blocking reference '%s'", 905 ref_file.buf, refname); 906goto error_return; 907} 908} 909}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 910strbuf_addf(err,"unable to resolve reference '%s': " 911"reference broken", refname); 912goto error_return; 913}else{ 914strbuf_addf(err,"unable to resolve reference '%s':%s", 915 refname,strerror(errno)); 916goto error_return; 917} 918 919/* 920 * If the ref did not exist and we are creating it, 921 * make sure there is no existing ref that conflicts 922 * with refname: 923 */ 924if(refs_verify_refname_available( 925&refs->base, refname, 926 extras, skip, err)) 927goto error_return; 928} 929 930 ret =0; 931goto out; 932 933error_return: 934unlock_ref(lock); 935*lock_p = NULL; 936 937out: 938strbuf_release(&ref_file); 939return ret; 940} 941 942static intfiles_peel_ref(struct ref_store *ref_store, 943const char*refname,unsigned char*sha1) 944{ 945struct files_ref_store *refs = 946files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 947"peel_ref"); 948int flag; 949unsigned char base[20]; 950 951if(current_ref_iter && current_ref_iter->refname == refname) { 952struct object_id peeled; 953 954if(ref_iterator_peel(current_ref_iter, &peeled)) 955return-1; 956hashcpy(sha1, peeled.hash); 957return0; 958} 959 960if(refs_read_ref_full(ref_store, refname, 961 RESOLVE_REF_READING, base, &flag)) 962return-1; 963 964/* 965 * If the reference is packed, read its ref_entry from the 966 * cache in the hope that we already know its peeled value. 967 * We only try this optimization on packed references because 968 * (a) forcing the filling of the loose reference cache could 969 * be expensive and (b) loose references anyway usually do not 970 * have REF_KNOWS_PEELED. 971 */ 972if(flag & REF_ISPACKED) { 973struct ref_entry *r =get_packed_ref(refs, refname); 974if(r) { 975if(peel_entry(r,0)) 976return-1; 977hashcpy(sha1, r->u.value.peeled.hash); 978return0; 979} 980} 981 982returnpeel_object(base, sha1); 983} 984 985struct files_ref_iterator { 986struct ref_iterator base; 987 988struct packed_ref_cache *packed_ref_cache; 989struct ref_iterator *iter0; 990unsigned int flags; 991}; 992 993static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 994{ 995struct files_ref_iterator *iter = 996(struct files_ref_iterator *)ref_iterator; 997int ok; 998 999while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1000if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1001ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1002continue;10031004if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1005!ref_resolves_to_object(iter->iter0->refname,1006 iter->iter0->oid,1007 iter->iter0->flags))1008continue;10091010 iter->base.refname = iter->iter0->refname;1011 iter->base.oid = iter->iter0->oid;1012 iter->base.flags = iter->iter0->flags;1013return ITER_OK;1014}10151016 iter->iter0 = NULL;1017if(ref_iterator_abort(ref_iterator) != ITER_DONE)1018 ok = ITER_ERROR;10191020return ok;1021}10221023static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1024struct object_id *peeled)1025{1026struct files_ref_iterator *iter =1027(struct files_ref_iterator *)ref_iterator;10281029returnref_iterator_peel(iter->iter0, peeled);1030}10311032static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1033{1034struct files_ref_iterator *iter =1035(struct files_ref_iterator *)ref_iterator;1036int ok = ITER_DONE;10371038if(iter->iter0)1039 ok =ref_iterator_abort(iter->iter0);10401041release_packed_ref_cache(iter->packed_ref_cache);1042base_ref_iterator_free(ref_iterator);1043return ok;1044}10451046static struct ref_iterator_vtable files_ref_iterator_vtable = {1047 files_ref_iterator_advance,1048 files_ref_iterator_peel,1049 files_ref_iterator_abort1050};10511052static struct ref_iterator *files_ref_iterator_begin(1053struct ref_store *ref_store,1054const char*prefix,unsigned int flags)1055{1056struct files_ref_store *refs;1057struct ref_iterator *loose_iter, *packed_iter;1058struct files_ref_iterator *iter;1059struct ref_iterator *ref_iterator;10601061if(ref_paranoia <0)1062 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1063if(ref_paranoia)1064 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10651066 refs =files_downcast(ref_store,1067 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1068"ref_iterator_begin");10691070 iter =xcalloc(1,sizeof(*iter));1071 ref_iterator = &iter->base;1072base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10731074/*1075 * We must make sure that all loose refs are read before1076 * accessing the packed-refs file; this avoids a race1077 * condition if loose refs are migrated to the packed-refs1078 * file by a simultaneous process, but our in-memory view is1079 * from before the migration. We ensure this as follows:1080 * First, we call start the loose refs iteration with its1081 * `prime_ref` argument set to true. This causes the loose1082 * references in the subtree to be pre-read into the cache.1083 * (If they've already been read, that's OK; we only need to1084 * guarantee that they're read before the packed refs, not1085 * *how much* before.) After that, we call1086 * get_packed_ref_cache(), which internally checks whether the1087 * packed-ref cache is up to date with what is on disk, and1088 * re-reads it if not.1089 */10901091 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1092 prefix,1);10931094 iter->packed_ref_cache =get_packed_ref_cache(refs);1095acquire_packed_ref_cache(iter->packed_ref_cache);1096 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1097 prefix,0);10981099 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1100 iter->flags = flags;11011102return ref_iterator;1103}11041105/*1106 * Verify that the reference locked by lock has the value old_sha1.1107 * Fail if the reference doesn't exist and mustexist is set. Return 01108 * on success. On error, write an error message to err, set errno, and1109 * return a negative value.1110 */1111static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1112const unsigned char*old_sha1,int mustexist,1113struct strbuf *err)1114{1115assert(err);11161117if(refs_read_ref_full(ref_store, lock->ref_name,1118 mustexist ? RESOLVE_REF_READING :0,1119 lock->old_oid.hash, NULL)) {1120if(old_sha1) {1121int save_errno = errno;1122strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1123 errno = save_errno;1124return-1;1125}else{1126oidclr(&lock->old_oid);1127return0;1128}1129}1130if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1131strbuf_addf(err,"ref '%s' is at%sbut expected%s",1132 lock->ref_name,1133oid_to_hex(&lock->old_oid),1134sha1_to_hex(old_sha1));1135 errno = EBUSY;1136return-1;1137}1138return0;1139}11401141static intremove_empty_directories(struct strbuf *path)1142{1143/*1144 * we want to create a file but there is a directory there;1145 * if that is an empty directory (or a directory that contains1146 * only empty directories), remove them.1147 */1148returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1149}11501151static intcreate_reflock(const char*path,void*cb)1152{1153struct lock_file *lk = cb;11541155returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1156}11571158/*1159 * Locks a ref returning the lock on success and NULL on failure.1160 * On failure errno is set to something meaningful.1161 */1162static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1163const char*refname,1164const unsigned char*old_sha1,1165const struct string_list *extras,1166const struct string_list *skip,1167unsigned int flags,int*type,1168struct strbuf *err)1169{1170struct strbuf ref_file = STRBUF_INIT;1171struct ref_lock *lock;1172int last_errno =0;1173int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1174int resolve_flags = RESOLVE_REF_NO_RECURSE;1175int resolved;11761177files_assert_main_repository(refs,"lock_ref_sha1_basic");1178assert(err);11791180 lock =xcalloc(1,sizeof(struct ref_lock));11811182if(mustexist)1183 resolve_flags |= RESOLVE_REF_READING;1184if(flags & REF_DELETING)1185 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11861187files_ref_path(refs, &ref_file, refname);1188 resolved = !!refs_resolve_ref_unsafe(&refs->base,1189 refname, resolve_flags,1190 lock->old_oid.hash, type);1191if(!resolved && errno == EISDIR) {1192/*1193 * we are trying to lock foo but we used to1194 * have foo/bar which now does not exist;1195 * it is normal for the empty directory 'foo'1196 * to remain.1197 */1198if(remove_empty_directories(&ref_file)) {1199 last_errno = errno;1200if(!refs_verify_refname_available(1201&refs->base,1202 refname, extras, skip, err))1203strbuf_addf(err,"there are still refs under '%s'",1204 refname);1205goto error_return;1206}1207 resolved = !!refs_resolve_ref_unsafe(&refs->base,1208 refname, resolve_flags,1209 lock->old_oid.hash, type);1210}1211if(!resolved) {1212 last_errno = errno;1213if(last_errno != ENOTDIR ||1214!refs_verify_refname_available(&refs->base, refname,1215 extras, skip, err))1216strbuf_addf(err,"unable to resolve reference '%s':%s",1217 refname,strerror(last_errno));12181219goto error_return;1220}12211222/*1223 * If the ref did not exist and we are creating it, make sure1224 * there is no existing packed ref whose name begins with our1225 * refname, nor a packed ref whose name is a proper prefix of1226 * our refname.1227 */1228if(is_null_oid(&lock->old_oid) &&1229refs_verify_refname_available(&refs->base, refname,1230 extras, skip, err)) {1231 last_errno = ENOTDIR;1232goto error_return;1233}12341235 lock->lk =xcalloc(1,sizeof(struct lock_file));12361237 lock->ref_name =xstrdup(refname);12381239if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1240 last_errno = errno;1241unable_to_lock_message(ref_file.buf, errno, err);1242goto error_return;1243}12441245if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1246 last_errno = errno;1247goto error_return;1248}1249goto out;12501251 error_return:1252unlock_ref(lock);1253 lock = NULL;12541255 out:1256strbuf_release(&ref_file);1257 errno = last_errno;1258return lock;1259}12601261/*1262 * Write an entry to the packed-refs file for the specified refname.1263 * If peeled is non-NULL, write it as the entry's peeled value.1264 */1265static voidwrite_packed_entry(FILE*fh,const char*refname,1266const unsigned char*sha1,1267const unsigned char*peeled)1268{1269fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1270if(peeled)1271fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1272}12731274/*1275 * Lock the packed-refs file for writing. Flags is passed to1276 * hold_lock_file_for_update(). Return 0 on success. On errors, set1277 * errno appropriately and return a nonzero value.1278 */1279static intlock_packed_refs(struct files_ref_store *refs,int flags)1280{1281static int timeout_configured =0;1282static int timeout_value =1000;1283struct packed_ref_cache *packed_ref_cache;12841285files_assert_main_repository(refs,"lock_packed_refs");12861287if(!timeout_configured) {1288git_config_get_int("core.packedrefstimeout", &timeout_value);1289 timeout_configured =1;1290}12911292if(hold_lock_file_for_update_timeout(1293&packlock,files_packed_refs_path(refs),1294 flags, timeout_value) <0)1295return-1;1296/*1297 * Get the current packed-refs while holding the lock. If the1298 * packed-refs file has been modified since we last read it,1299 * this will automatically invalidate the cache and re-read1300 * the packed-refs file.1301 */1302 packed_ref_cache =get_packed_ref_cache(refs);1303 packed_ref_cache->lock = &packlock;1304/* Increment the reference count to prevent it from being freed: */1305acquire_packed_ref_cache(packed_ref_cache);1306return0;1307}13081309/*1310 * Write the current version of the packed refs cache from memory to1311 * disk. The packed-refs file must already be locked for writing (see1312 * lock_packed_refs()). Return zero on success. On errors, set errno1313 * and return a nonzero value1314 */1315static intcommit_packed_refs(struct files_ref_store *refs)1316{1317struct packed_ref_cache *packed_ref_cache =1318get_packed_ref_cache(refs);1319int ok, error =0;1320int save_errno =0;1321FILE*out;1322struct ref_iterator *iter;13231324files_assert_main_repository(refs,"commit_packed_refs");13251326if(!packed_ref_cache->lock)1327die("internal error: packed-refs not locked");13281329 out =fdopen_lock_file(packed_ref_cache->lock,"w");1330if(!out)1331die_errno("unable to fdopen packed-refs descriptor");13321333fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13341335 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1336while((ok =ref_iterator_advance(iter)) == ITER_OK) {1337struct object_id peeled;1338int peel_error =ref_iterator_peel(iter, &peeled);13391340write_packed_entry(out, iter->refname, iter->oid->hash,1341 peel_error ? NULL : peeled.hash);1342}13431344if(ok != ITER_DONE)1345die("error while iterating over references");13461347if(commit_lock_file(packed_ref_cache->lock)) {1348 save_errno = errno;1349 error = -1;1350}1351 packed_ref_cache->lock = NULL;1352release_packed_ref_cache(packed_ref_cache);1353 errno = save_errno;1354return error;1355}13561357/*1358 * Rollback the lockfile for the packed-refs file, and discard the1359 * in-memory packed reference cache. (The packed-refs file will be1360 * read anew if it is needed again after this function is called.)1361 */1362static voidrollback_packed_refs(struct files_ref_store *refs)1363{1364struct packed_ref_cache *packed_ref_cache =1365get_packed_ref_cache(refs);13661367files_assert_main_repository(refs,"rollback_packed_refs");13681369if(!packed_ref_cache->lock)1370die("internal error: packed-refs not locked");1371rollback_lock_file(packed_ref_cache->lock);1372 packed_ref_cache->lock = NULL;1373release_packed_ref_cache(packed_ref_cache);1374clear_packed_ref_cache(refs);1375}13761377struct ref_to_prune {1378struct ref_to_prune *next;1379unsigned char sha1[20];1380char name[FLEX_ARRAY];1381};13821383enum{1384 REMOVE_EMPTY_PARENTS_REF =0x01,1385 REMOVE_EMPTY_PARENTS_REFLOG =0x021386};13871388/*1389 * Remove empty parent directories associated with the specified1390 * reference and/or its reflog, but spare [logs/]refs/ and immediate1391 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1392 * REMOVE_EMPTY_PARENTS_REFLOG.1393 */1394static voidtry_remove_empty_parents(struct files_ref_store *refs,1395const char*refname,1396unsigned int flags)1397{1398struct strbuf buf = STRBUF_INIT;1399struct strbuf sb = STRBUF_INIT;1400char*p, *q;1401int i;14021403strbuf_addstr(&buf, refname);1404 p = buf.buf;1405for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1406while(*p && *p !='/')1407 p++;1408/* tolerate duplicate slashes; see check_refname_format() */1409while(*p =='/')1410 p++;1411}1412 q = buf.buf + buf.len;1413while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1414while(q > p && *q !='/')1415 q--;1416while(q > p && *(q-1) =='/')1417 q--;1418if(q == p)1419break;1420strbuf_setlen(&buf, q - buf.buf);14211422strbuf_reset(&sb);1423files_ref_path(refs, &sb, buf.buf);1424if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1425 flags &= ~REMOVE_EMPTY_PARENTS_REF;14261427strbuf_reset(&sb);1428files_reflog_path(refs, &sb, buf.buf);1429if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1430 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1431}1432strbuf_release(&buf);1433strbuf_release(&sb);1434}14351436/* make sure nobody touched the ref, and unlink */1437static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1438{1439struct ref_transaction *transaction;1440struct strbuf err = STRBUF_INIT;14411442if(check_refname_format(r->name,0))1443return;14441445 transaction =ref_store_transaction_begin(&refs->base, &err);1446if(!transaction ||1447ref_transaction_delete(transaction, r->name, r->sha1,1448 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1449ref_transaction_commit(transaction, &err)) {1450ref_transaction_free(transaction);1451error("%s", err.buf);1452strbuf_release(&err);1453return;1454}1455ref_transaction_free(transaction);1456strbuf_release(&err);1457}14581459static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1460{1461while(r) {1462prune_ref(refs, r);1463 r = r->next;1464}1465}14661467static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1468{1469struct files_ref_store *refs =1470files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1471"pack_refs");1472struct ref_iterator *iter;1473struct ref_dir *packed_refs;1474int ok;1475struct ref_to_prune *refs_to_prune = NULL;14761477lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1478 packed_refs =get_packed_refs(refs);14791480 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1481while((ok =ref_iterator_advance(iter)) == ITER_OK) {1482/*1483 * If the loose reference can be packed, add an entry1484 * in the packed ref cache. If the reference should be1485 * pruned, also add it to refs_to_prune.1486 */1487struct ref_entry *packed_entry;1488int is_tag_ref =starts_with(iter->refname,"refs/tags/");14891490/* Do not pack per-worktree refs: */1491if(ref_type(iter->refname) != REF_TYPE_NORMAL)1492continue;14931494/* ALWAYS pack tags */1495if(!(flags & PACK_REFS_ALL) && !is_tag_ref)1496continue;14971498/* Do not pack symbolic or broken refs: */1499if(iter->flags & REF_ISSYMREF)1500continue;15011502if(!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))1503continue;15041505/*1506 * Create an entry in the packed-refs cache equivalent1507 * to the one from the loose ref cache, except that1508 * we don't copy the peeled status, because we want it1509 * to be re-peeled.1510 */1511 packed_entry =find_ref_entry(packed_refs, iter->refname);1512if(packed_entry) {1513/* Overwrite existing packed entry with info from loose entry */1514 packed_entry->flag = REF_ISPACKED;1515oidcpy(&packed_entry->u.value.oid, iter->oid);1516}else{1517 packed_entry =create_ref_entry(iter->refname, iter->oid,1518 REF_ISPACKED,0);1519add_ref_entry(packed_refs, packed_entry);1520}1521oidclr(&packed_entry->u.value.peeled);15221523/* Schedule the loose reference for pruning if requested. */1524if((flags & PACK_REFS_PRUNE)) {1525struct ref_to_prune *n;1526FLEX_ALLOC_STR(n, name, iter->refname);1527hashcpy(n->sha1, iter->oid->hash);1528 n->next = refs_to_prune;1529 refs_to_prune = n;1530}1531}1532if(ok != ITER_DONE)1533die("error while iterating over references");15341535if(commit_packed_refs(refs))1536die_errno("unable to overwrite old ref-pack file");15371538prune_refs(refs, refs_to_prune);1539return0;1540}15411542/*1543 * Rewrite the packed-refs file, omitting any refs listed in1544 * 'refnames'. On error, leave packed-refs unchanged, write an error1545 * message to 'err', and return a nonzero value.1546 *1547 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1548 */1549static intrepack_without_refs(struct files_ref_store *refs,1550struct string_list *refnames,struct strbuf *err)1551{1552struct ref_dir *packed;1553struct string_list_item *refname;1554int ret, needs_repacking =0, removed =0;15551556files_assert_main_repository(refs,"repack_without_refs");1557assert(err);15581559/* Look for a packed ref */1560for_each_string_list_item(refname, refnames) {1561if(get_packed_ref(refs, refname->string)) {1562 needs_repacking =1;1563break;1564}1565}15661567/* Avoid locking if we have nothing to do */1568if(!needs_repacking)1569return0;/* no refname exists in packed refs */15701571if(lock_packed_refs(refs,0)) {1572unable_to_lock_message(files_packed_refs_path(refs), errno, err);1573return-1;1574}1575 packed =get_packed_refs(refs);15761577/* Remove refnames from the cache */1578for_each_string_list_item(refname, refnames)1579if(remove_entry_from_dir(packed, refname->string) != -1)1580 removed =1;1581if(!removed) {1582/*1583 * All packed entries disappeared while we were1584 * acquiring the lock.1585 */1586rollback_packed_refs(refs);1587return0;1588}15891590/* Write what remains */1591 ret =commit_packed_refs(refs);1592if(ret)1593strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1594strerror(errno));1595return ret;1596}15971598static intfiles_delete_refs(struct ref_store *ref_store,1599struct string_list *refnames,unsigned int flags)1600{1601struct files_ref_store *refs =1602files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1603struct strbuf err = STRBUF_INIT;1604int i, result =0;16051606if(!refnames->nr)1607return0;16081609 result =repack_without_refs(refs, refnames, &err);1610if(result) {1611/*1612 * If we failed to rewrite the packed-refs file, then1613 * it is unsafe to try to remove loose refs, because1614 * doing so might expose an obsolete packed value for1615 * a reference that might even point at an object that1616 * has been garbage collected.1617 */1618if(refnames->nr ==1)1619error(_("could not delete reference%s:%s"),1620 refnames->items[0].string, err.buf);1621else1622error(_("could not delete references:%s"), err.buf);16231624goto out;1625}16261627for(i =0; i < refnames->nr; i++) {1628const char*refname = refnames->items[i].string;16291630if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))1631 result |=error(_("could not remove reference%s"), refname);1632}16331634out:1635strbuf_release(&err);1636return result;1637}16381639/*1640 * People using contrib's git-new-workdir have .git/logs/refs ->1641 * /some/other/path/.git/logs/refs, and that may live on another device.1642 *1643 * IOW, to avoid cross device rename errors, the temporary renamed log must1644 * live into logs/refs.1645 */1646#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16471648struct rename_cb {1649const char*tmp_renamed_log;1650int true_errno;1651};16521653static intrename_tmp_log_callback(const char*path,void*cb_data)1654{1655struct rename_cb *cb = cb_data;16561657if(rename(cb->tmp_renamed_log, path)) {1658/*1659 * rename(a, b) when b is an existing directory ought1660 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1661 * Sheesh. Record the true errno for error reporting,1662 * but report EISDIR to raceproof_create_file() so1663 * that it knows to retry.1664 */1665 cb->true_errno = errno;1666if(errno == ENOTDIR)1667 errno = EISDIR;1668return-1;1669}else{1670return0;1671}1672}16731674static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1675{1676struct strbuf path = STRBUF_INIT;1677struct strbuf tmp = STRBUF_INIT;1678struct rename_cb cb;1679int ret;16801681files_reflog_path(refs, &path, newrefname);1682files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1683 cb.tmp_renamed_log = tmp.buf;1684 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1685if(ret) {1686if(errno == EISDIR)1687error("directory not empty:%s", path.buf);1688else1689error("unable to move logfile%sto%s:%s",1690 tmp.buf, path.buf,1691strerror(cb.true_errno));1692}16931694strbuf_release(&path);1695strbuf_release(&tmp);1696return ret;1697}16981699static intwrite_ref_to_lockfile(struct ref_lock *lock,1700const struct object_id *oid,struct strbuf *err);1701static intcommit_ref_update(struct files_ref_store *refs,1702struct ref_lock *lock,1703const struct object_id *oid,const char*logmsg,1704struct strbuf *err);17051706static intfiles_rename_ref(struct ref_store *ref_store,1707const char*oldrefname,const char*newrefname,1708const char*logmsg)1709{1710struct files_ref_store *refs =1711files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1712struct object_id oid, orig_oid;1713int flag =0, logmoved =0;1714struct ref_lock *lock;1715struct stat loginfo;1716struct strbuf sb_oldref = STRBUF_INIT;1717struct strbuf sb_newref = STRBUF_INIT;1718struct strbuf tmp_renamed_log = STRBUF_INIT;1719int log, ret;1720struct strbuf err = STRBUF_INIT;17211722files_reflog_path(refs, &sb_oldref, oldrefname);1723files_reflog_path(refs, &sb_newref, newrefname);1724files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17251726 log = !lstat(sb_oldref.buf, &loginfo);1727if(log &&S_ISLNK(loginfo.st_mode)) {1728 ret =error("reflog for%sis a symlink", oldrefname);1729goto out;1730}17311732if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1733 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1734 orig_oid.hash, &flag)) {1735 ret =error("refname%snot found", oldrefname);1736goto out;1737}17381739if(flag & REF_ISSYMREF) {1740 ret =error("refname%sis a symbolic ref, renaming it is not supported",1741 oldrefname);1742goto out;1743}1744if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1745 ret =1;1746goto out;1747}17481749if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1750 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1751 oldrefname,strerror(errno));1752goto out;1753}17541755if(refs_delete_ref(&refs->base, logmsg, oldrefname,1756 orig_oid.hash, REF_NODEREF)) {1757error("unable to delete old%s", oldrefname);1758goto rollback;1759}17601761/*1762 * Since we are doing a shallow lookup, oid is not the1763 * correct value to pass to delete_ref as old_oid. But that1764 * doesn't matter, because an old_oid check wouldn't add to1765 * the safety anyway; we want to delete the reference whatever1766 * its current value.1767 */1768if(!refs_read_ref_full(&refs->base, newrefname,1769 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1770 oid.hash, NULL) &&1771refs_delete_ref(&refs->base, NULL, newrefname,1772 NULL, REF_NODEREF)) {1773if(errno == EISDIR) {1774struct strbuf path = STRBUF_INIT;1775int result;17761777files_ref_path(refs, &path, newrefname);1778 result =remove_empty_directories(&path);1779strbuf_release(&path);17801781if(result) {1782error("Directory not empty:%s", newrefname);1783goto rollback;1784}1785}else{1786error("unable to delete existing%s", newrefname);1787goto rollback;1788}1789}17901791if(log &&rename_tmp_log(refs, newrefname))1792goto rollback;17931794 logmoved = log;17951796 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1797 REF_NODEREF, NULL, &err);1798if(!lock) {1799error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1800strbuf_release(&err);1801goto rollback;1802}1803oidcpy(&lock->old_oid, &orig_oid);18041805if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1806commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1807error("unable to write current sha1 into%s:%s", newrefname, err.buf);1808strbuf_release(&err);1809goto rollback;1810}18111812 ret =0;1813goto out;18141815 rollback:1816 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1817 REF_NODEREF, NULL, &err);1818if(!lock) {1819error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1820strbuf_release(&err);1821goto rollbacklog;1822}18231824 flag = log_all_ref_updates;1825 log_all_ref_updates = LOG_REFS_NONE;1826if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1827commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1828error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1829strbuf_release(&err);1830}1831 log_all_ref_updates = flag;18321833 rollbacklog:1834if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1835error("unable to restore logfile%sfrom%s:%s",1836 oldrefname, newrefname,strerror(errno));1837if(!logmoved && log &&1838rename(tmp_renamed_log.buf, sb_oldref.buf))1839error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1840 oldrefname,strerror(errno));1841 ret =1;1842 out:1843strbuf_release(&sb_newref);1844strbuf_release(&sb_oldref);1845strbuf_release(&tmp_renamed_log);18461847return ret;1848}18491850static intclose_ref(struct ref_lock *lock)1851{1852if(close_lock_file(lock->lk))1853return-1;1854return0;1855}18561857static intcommit_ref(struct ref_lock *lock)1858{1859char*path =get_locked_file_path(lock->lk);1860struct stat st;18611862if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1863/*1864 * There is a directory at the path we want to rename1865 * the lockfile to. Hopefully it is empty; try to1866 * delete it.1867 */1868size_t len =strlen(path);1869struct strbuf sb_path = STRBUF_INIT;18701871strbuf_attach(&sb_path, path, len, len);18721873/*1874 * If this fails, commit_lock_file() will also fail1875 * and will report the problem.1876 */1877remove_empty_directories(&sb_path);1878strbuf_release(&sb_path);1879}else{1880free(path);1881}18821883if(commit_lock_file(lock->lk))1884return-1;1885return0;1886}18871888static intopen_or_create_logfile(const char*path,void*cb)1889{1890int*fd = cb;18911892*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1893return(*fd <0) ? -1:0;1894}18951896/*1897 * Create a reflog for a ref. If force_create = 0, only create the1898 * reflog for certain refs (those for which should_autocreate_reflog1899 * returns non-zero). Otherwise, create it regardless of the reference1900 * name. If the logfile already existed or was created, return 0 and1901 * set *logfd to the file descriptor opened for appending to the file.1902 * If no logfile exists and we decided not to create one, return 0 and1903 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1904 * return -1.1905 */1906static intlog_ref_setup(struct files_ref_store *refs,1907const char*refname,int force_create,1908int*logfd,struct strbuf *err)1909{1910struct strbuf logfile_sb = STRBUF_INIT;1911char*logfile;19121913files_reflog_path(refs, &logfile_sb, refname);1914 logfile =strbuf_detach(&logfile_sb, NULL);19151916if(force_create ||should_autocreate_reflog(refname)) {1917if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1918if(errno == ENOENT)1919strbuf_addf(err,"unable to create directory for '%s': "1920"%s", logfile,strerror(errno));1921else if(errno == EISDIR)1922strbuf_addf(err,"there are still logs under '%s'",1923 logfile);1924else1925strbuf_addf(err,"unable to append to '%s':%s",1926 logfile,strerror(errno));19271928goto error;1929}1930}else{1931*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1932if(*logfd <0) {1933if(errno == ENOENT || errno == EISDIR) {1934/*1935 * The logfile doesn't already exist,1936 * but that is not an error; it only1937 * means that we won't write log1938 * entries to it.1939 */1940;1941}else{1942strbuf_addf(err,"unable to append to '%s':%s",1943 logfile,strerror(errno));1944goto error;1945}1946}1947}19481949if(*logfd >=0)1950adjust_shared_perm(logfile);19511952free(logfile);1953return0;19541955error:1956free(logfile);1957return-1;1958}19591960static intfiles_create_reflog(struct ref_store *ref_store,1961const char*refname,int force_create,1962struct strbuf *err)1963{1964struct files_ref_store *refs =1965files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1966int fd;19671968if(log_ref_setup(refs, refname, force_create, &fd, err))1969return-1;19701971if(fd >=0)1972close(fd);19731974return0;1975}19761977static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1978const struct object_id *new_oid,1979const char*committer,const char*msg)1980{1981int msglen, written;1982unsigned maxlen, len;1983char*logrec;19841985 msglen = msg ?strlen(msg) :0;1986 maxlen =strlen(committer) + msglen +100;1987 logrec =xmalloc(maxlen);1988 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1989oid_to_hex(old_oid),1990oid_to_hex(new_oid),1991 committer);1992if(msglen)1993 len +=copy_reflog_msg(logrec + len -1, msg) -1;19941995 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1996free(logrec);1997if(written != len)1998return-1;19992000return0;2001}20022003static intfiles_log_ref_write(struct files_ref_store *refs,2004const char*refname,const struct object_id *old_oid,2005const struct object_id *new_oid,const char*msg,2006int flags,struct strbuf *err)2007{2008int logfd, result;20092010if(log_all_ref_updates == LOG_REFS_UNSET)2011 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20122013 result =log_ref_setup(refs, refname,2014 flags & REF_FORCE_CREATE_REFLOG,2015&logfd, err);20162017if(result)2018return result;20192020if(logfd <0)2021return0;2022 result =log_ref_write_fd(logfd, old_oid, new_oid,2023git_committer_info(0), msg);2024if(result) {2025struct strbuf sb = STRBUF_INIT;2026int save_errno = errno;20272028files_reflog_path(refs, &sb, refname);2029strbuf_addf(err,"unable to append to '%s':%s",2030 sb.buf,strerror(save_errno));2031strbuf_release(&sb);2032close(logfd);2033return-1;2034}2035if(close(logfd)) {2036struct strbuf sb = STRBUF_INIT;2037int save_errno = errno;20382039files_reflog_path(refs, &sb, refname);2040strbuf_addf(err,"unable to append to '%s':%s",2041 sb.buf,strerror(save_errno));2042strbuf_release(&sb);2043return-1;2044}2045return0;2046}20472048/*2049 * Write sha1 into the open lockfile, then close the lockfile. On2050 * errors, rollback the lockfile, fill in *err and2051 * return -1.2052 */2053static intwrite_ref_to_lockfile(struct ref_lock *lock,2054const struct object_id *oid,struct strbuf *err)2055{2056static char term ='\n';2057struct object *o;2058int fd;20592060 o =parse_object(oid);2061if(!o) {2062strbuf_addf(err,2063"trying to write ref '%s' with nonexistent object%s",2064 lock->ref_name,oid_to_hex(oid));2065unlock_ref(lock);2066return-1;2067}2068if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2069strbuf_addf(err,2070"trying to write non-commit object%sto branch '%s'",2071oid_to_hex(oid), lock->ref_name);2072unlock_ref(lock);2073return-1;2074}2075 fd =get_lock_file_fd(lock->lk);2076if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2077write_in_full(fd, &term,1) !=1||2078close_ref(lock) <0) {2079strbuf_addf(err,2080"couldn't write '%s'",get_lock_file_path(lock->lk));2081unlock_ref(lock);2082return-1;2083}2084return0;2085}20862087/*2088 * Commit a change to a loose reference that has already been written2089 * to the loose reference lockfile. Also update the reflogs if2090 * necessary, using the specified lockmsg (which can be NULL).2091 */2092static intcommit_ref_update(struct files_ref_store *refs,2093struct ref_lock *lock,2094const struct object_id *oid,const char*logmsg,2095struct strbuf *err)2096{2097files_assert_main_repository(refs,"commit_ref_update");20982099clear_loose_ref_cache(refs);2100if(files_log_ref_write(refs, lock->ref_name,2101&lock->old_oid, oid,2102 logmsg,0, err)) {2103char*old_msg =strbuf_detach(err, NULL);2104strbuf_addf(err,"cannot update the ref '%s':%s",2105 lock->ref_name, old_msg);2106free(old_msg);2107unlock_ref(lock);2108return-1;2109}21102111if(strcmp(lock->ref_name,"HEAD") !=0) {2112/*2113 * Special hack: If a branch is updated directly and HEAD2114 * points to it (may happen on the remote side of a push2115 * for example) then logically the HEAD reflog should be2116 * updated too.2117 * A generic solution implies reverse symref information,2118 * but finding all symrefs pointing to the given branch2119 * would be rather costly for this rare event (the direct2120 * update of a branch) to be worth it. So let's cheat and2121 * check with HEAD only which should cover 99% of all usage2122 * scenarios (even 100% of the default ones).2123 */2124struct object_id head_oid;2125int head_flag;2126const char*head_ref;21272128 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2129 RESOLVE_REF_READING,2130 head_oid.hash, &head_flag);2131if(head_ref && (head_flag & REF_ISSYMREF) &&2132!strcmp(head_ref, lock->ref_name)) {2133struct strbuf log_err = STRBUF_INIT;2134if(files_log_ref_write(refs,"HEAD",2135&lock->old_oid, oid,2136 logmsg,0, &log_err)) {2137error("%s", log_err.buf);2138strbuf_release(&log_err);2139}2140}2141}21422143if(commit_ref(lock)) {2144strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2145unlock_ref(lock);2146return-1;2147}21482149unlock_ref(lock);2150return0;2151}21522153static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2154{2155int ret = -1;2156#ifndef NO_SYMLINK_HEAD2157char*ref_path =get_locked_file_path(lock->lk);2158unlink(ref_path);2159 ret =symlink(target, ref_path);2160free(ref_path);21612162if(ret)2163fprintf(stderr,"no symlink - falling back to symbolic ref\n");2164#endif2165return ret;2166}21672168static voidupdate_symref_reflog(struct files_ref_store *refs,2169struct ref_lock *lock,const char*refname,2170const char*target,const char*logmsg)2171{2172struct strbuf err = STRBUF_INIT;2173struct object_id new_oid;2174if(logmsg &&2175!refs_read_ref_full(&refs->base, target,2176 RESOLVE_REF_READING, new_oid.hash, NULL) &&2177files_log_ref_write(refs, refname, &lock->old_oid,2178&new_oid, logmsg,0, &err)) {2179error("%s", err.buf);2180strbuf_release(&err);2181}2182}21832184static intcreate_symref_locked(struct files_ref_store *refs,2185struct ref_lock *lock,const char*refname,2186const char*target,const char*logmsg)2187{2188if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2189update_symref_reflog(refs, lock, refname, target, logmsg);2190return0;2191}21922193if(!fdopen_lock_file(lock->lk,"w"))2194returnerror("unable to fdopen%s:%s",2195 lock->lk->tempfile.filename.buf,strerror(errno));21962197update_symref_reflog(refs, lock, refname, target, logmsg);21982199/* no error check; commit_ref will check ferror */2200fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2201if(commit_ref(lock) <0)2202returnerror("unable to write symref for%s:%s", refname,2203strerror(errno));2204return0;2205}22062207static intfiles_create_symref(struct ref_store *ref_store,2208const char*refname,const char*target,2209const char*logmsg)2210{2211struct files_ref_store *refs =2212files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2213struct strbuf err = STRBUF_INIT;2214struct ref_lock *lock;2215int ret;22162217 lock =lock_ref_sha1_basic(refs, refname, NULL,2218 NULL, NULL, REF_NODEREF, NULL,2219&err);2220if(!lock) {2221error("%s", err.buf);2222strbuf_release(&err);2223return-1;2224}22252226 ret =create_symref_locked(refs, lock, refname, target, logmsg);2227unlock_ref(lock);2228return ret;2229}22302231static intfiles_reflog_exists(struct ref_store *ref_store,2232const char*refname)2233{2234struct files_ref_store *refs =2235files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2236struct strbuf sb = STRBUF_INIT;2237struct stat st;2238int ret;22392240files_reflog_path(refs, &sb, refname);2241 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2242strbuf_release(&sb);2243return ret;2244}22452246static intfiles_delete_reflog(struct ref_store *ref_store,2247const char*refname)2248{2249struct files_ref_store *refs =2250files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2251struct strbuf sb = STRBUF_INIT;2252int ret;22532254files_reflog_path(refs, &sb, refname);2255 ret =remove_path(sb.buf);2256strbuf_release(&sb);2257return ret;2258}22592260static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2261{2262struct object_id ooid, noid;2263char*email_end, *message;2264 timestamp_t timestamp;2265int tz;2266const char*p = sb->buf;22672268/* old SP new SP name <email> SP time TAB msg LF */2269if(!sb->len || sb->buf[sb->len -1] !='\n'||2270parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2271parse_oid_hex(p, &noid, &p) || *p++ !=' '||2272!(email_end =strchr(p,'>')) ||2273 email_end[1] !=' '||2274!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2275!message || message[0] !=' '||2276(message[1] !='+'&& message[1] !='-') ||2277!isdigit(message[2]) || !isdigit(message[3]) ||2278!isdigit(message[4]) || !isdigit(message[5]))2279return0;/* corrupt? */2280 email_end[1] ='\0';2281 tz =strtol(message +1, NULL,10);2282if(message[6] !='\t')2283 message +=6;2284else2285 message +=7;2286returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2287}22882289static char*find_beginning_of_line(char*bob,char*scan)2290{2291while(bob < scan && *(--scan) !='\n')2292;/* keep scanning backwards */2293/*2294 * Return either beginning of the buffer, or LF at the end of2295 * the previous line.2296 */2297return scan;2298}22992300static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2301const char*refname,2302 each_reflog_ent_fn fn,2303void*cb_data)2304{2305struct files_ref_store *refs =2306files_downcast(ref_store, REF_STORE_READ,2307"for_each_reflog_ent_reverse");2308struct strbuf sb = STRBUF_INIT;2309FILE*logfp;2310long pos;2311int ret =0, at_tail =1;23122313files_reflog_path(refs, &sb, refname);2314 logfp =fopen(sb.buf,"r");2315strbuf_release(&sb);2316if(!logfp)2317return-1;23182319/* Jump to the end */2320if(fseek(logfp,0, SEEK_END) <0)2321 ret =error("cannot seek back reflog for%s:%s",2322 refname,strerror(errno));2323 pos =ftell(logfp);2324while(!ret &&0< pos) {2325int cnt;2326size_t nread;2327char buf[BUFSIZ];2328char*endp, *scanp;23292330/* Fill next block from the end */2331 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2332if(fseek(logfp, pos - cnt, SEEK_SET)) {2333 ret =error("cannot seek back reflog for%s:%s",2334 refname,strerror(errno));2335break;2336}2337 nread =fread(buf, cnt,1, logfp);2338if(nread !=1) {2339 ret =error("cannot read%dbytes from reflog for%s:%s",2340 cnt, refname,strerror(errno));2341break;2342}2343 pos -= cnt;23442345 scanp = endp = buf + cnt;2346if(at_tail && scanp[-1] =='\n')2347/* Looking at the final LF at the end of the file */2348 scanp--;2349 at_tail =0;23502351while(buf < scanp) {2352/*2353 * terminating LF of the previous line, or the beginning2354 * of the buffer.2355 */2356char*bp;23572358 bp =find_beginning_of_line(buf, scanp);23592360if(*bp =='\n') {2361/*2362 * The newline is the end of the previous line,2363 * so we know we have complete line starting2364 * at (bp + 1). Prefix it onto any prior data2365 * we collected for the line and process it.2366 */2367strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2368 scanp = bp;2369 endp = bp +1;2370 ret =show_one_reflog_ent(&sb, fn, cb_data);2371strbuf_reset(&sb);2372if(ret)2373break;2374}else if(!pos) {2375/*2376 * We are at the start of the buffer, and the2377 * start of the file; there is no previous2378 * line, and we have everything for this one.2379 * Process it, and we can end the loop.2380 */2381strbuf_splice(&sb,0,0, buf, endp - buf);2382 ret =show_one_reflog_ent(&sb, fn, cb_data);2383strbuf_reset(&sb);2384break;2385}23862387if(bp == buf) {2388/*2389 * We are at the start of the buffer, and there2390 * is more file to read backwards. Which means2391 * we are in the middle of a line. Note that we2392 * may get here even if *bp was a newline; that2393 * just means we are at the exact end of the2394 * previous line, rather than some spot in the2395 * middle.2396 *2397 * Save away what we have to be combined with2398 * the data from the next read.2399 */2400strbuf_splice(&sb,0,0, buf, endp - buf);2401break;2402}2403}24042405}2406if(!ret && sb.len)2407die("BUG: reverse reflog parser had leftover data");24082409fclose(logfp);2410strbuf_release(&sb);2411return ret;2412}24132414static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2415const char*refname,2416 each_reflog_ent_fn fn,void*cb_data)2417{2418struct files_ref_store *refs =2419files_downcast(ref_store, REF_STORE_READ,2420"for_each_reflog_ent");2421FILE*logfp;2422struct strbuf sb = STRBUF_INIT;2423int ret =0;24242425files_reflog_path(refs, &sb, refname);2426 logfp =fopen(sb.buf,"r");2427strbuf_release(&sb);2428if(!logfp)2429return-1;24302431while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2432 ret =show_one_reflog_ent(&sb, fn, cb_data);2433fclose(logfp);2434strbuf_release(&sb);2435return ret;2436}24372438struct files_reflog_iterator {2439struct ref_iterator base;24402441struct ref_store *ref_store;2442struct dir_iterator *dir_iterator;2443struct object_id oid;2444};24452446static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2447{2448struct files_reflog_iterator *iter =2449(struct files_reflog_iterator *)ref_iterator;2450struct dir_iterator *diter = iter->dir_iterator;2451int ok;24522453while((ok =dir_iterator_advance(diter)) == ITER_OK) {2454int flags;24552456if(!S_ISREG(diter->st.st_mode))2457continue;2458if(diter->basename[0] =='.')2459continue;2460if(ends_with(diter->basename,".lock"))2461continue;24622463if(refs_read_ref_full(iter->ref_store,2464 diter->relative_path,0,2465 iter->oid.hash, &flags)) {2466error("bad ref for%s", diter->path.buf);2467continue;2468}24692470 iter->base.refname = diter->relative_path;2471 iter->base.oid = &iter->oid;2472 iter->base.flags = flags;2473return ITER_OK;2474}24752476 iter->dir_iterator = NULL;2477if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2478 ok = ITER_ERROR;2479return ok;2480}24812482static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2483struct object_id *peeled)2484{2485die("BUG: ref_iterator_peel() called for reflog_iterator");2486}24872488static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2489{2490struct files_reflog_iterator *iter =2491(struct files_reflog_iterator *)ref_iterator;2492int ok = ITER_DONE;24932494if(iter->dir_iterator)2495 ok =dir_iterator_abort(iter->dir_iterator);24962497base_ref_iterator_free(ref_iterator);2498return ok;2499}25002501static struct ref_iterator_vtable files_reflog_iterator_vtable = {2502 files_reflog_iterator_advance,2503 files_reflog_iterator_peel,2504 files_reflog_iterator_abort2505};25062507static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2508{2509struct files_ref_store *refs =2510files_downcast(ref_store, REF_STORE_READ,2511"reflog_iterator_begin");2512struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2513struct ref_iterator *ref_iterator = &iter->base;2514struct strbuf sb = STRBUF_INIT;25152516base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2517files_reflog_path(refs, &sb, NULL);2518 iter->dir_iterator =dir_iterator_begin(sb.buf);2519 iter->ref_store = ref_store;2520strbuf_release(&sb);2521return ref_iterator;2522}25232524static intref_update_reject_duplicates(struct string_list *refnames,2525struct strbuf *err)2526{2527int i, n = refnames->nr;25282529assert(err);25302531for(i =1; i < n; i++)2532if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2533strbuf_addf(err,2534"multiple updates for ref '%s' not allowed.",2535 refnames->items[i].string);2536return1;2537}2538return0;2539}25402541/*2542 * If update is a direct update of head_ref (the reference pointed to2543 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2544 */2545static intsplit_head_update(struct ref_update *update,2546struct ref_transaction *transaction,2547const char*head_ref,2548struct string_list *affected_refnames,2549struct strbuf *err)2550{2551struct string_list_item *item;2552struct ref_update *new_update;25532554if((update->flags & REF_LOG_ONLY) ||2555(update->flags & REF_ISPRUNING) ||2556(update->flags & REF_UPDATE_VIA_HEAD))2557return0;25582559if(strcmp(update->refname, head_ref))2560return0;25612562/*2563 * First make sure that HEAD is not already in the2564 * transaction. This insertion is O(N) in the transaction2565 * size, but it happens at most once per transaction.2566 */2567 item =string_list_insert(affected_refnames,"HEAD");2568if(item->util) {2569/* An entry already existed */2570strbuf_addf(err,2571"multiple updates for 'HEAD' (including one "2572"via its referent '%s') are not allowed",2573 update->refname);2574return TRANSACTION_NAME_CONFLICT;2575}25762577 new_update =ref_transaction_add_update(2578 transaction,"HEAD",2579 update->flags | REF_LOG_ONLY | REF_NODEREF,2580 update->new_oid.hash, update->old_oid.hash,2581 update->msg);25822583 item->util = new_update;25842585return0;2586}25872588/*2589 * update is for a symref that points at referent and doesn't have2590 * REF_NODEREF set. Split it into two updates:2591 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2592 * - A new, separate update for the referent reference2593 * Note that the new update will itself be subject to splitting when2594 * the iteration gets to it.2595 */2596static intsplit_symref_update(struct files_ref_store *refs,2597struct ref_update *update,2598const char*referent,2599struct ref_transaction *transaction,2600struct string_list *affected_refnames,2601struct strbuf *err)2602{2603struct string_list_item *item;2604struct ref_update *new_update;2605unsigned int new_flags;26062607/*2608 * First make sure that referent is not already in the2609 * transaction. This insertion is O(N) in the transaction2610 * size, but it happens at most once per symref in a2611 * transaction.2612 */2613 item =string_list_insert(affected_refnames, referent);2614if(item->util) {2615/* An entry already existed */2616strbuf_addf(err,2617"multiple updates for '%s' (including one "2618"via symref '%s') are not allowed",2619 referent, update->refname);2620return TRANSACTION_NAME_CONFLICT;2621}26222623 new_flags = update->flags;2624if(!strcmp(update->refname,"HEAD")) {2625/*2626 * Record that the new update came via HEAD, so that2627 * when we process it, split_head_update() doesn't try2628 * to add another reflog update for HEAD. Note that2629 * this bit will be propagated if the new_update2630 * itself needs to be split.2631 */2632 new_flags |= REF_UPDATE_VIA_HEAD;2633}26342635 new_update =ref_transaction_add_update(2636 transaction, referent, new_flags,2637 update->new_oid.hash, update->old_oid.hash,2638 update->msg);26392640 new_update->parent_update = update;26412642/*2643 * Change the symbolic ref update to log only. Also, it2644 * doesn't need to check its old SHA-1 value, as that will be2645 * done when new_update is processed.2646 */2647 update->flags |= REF_LOG_ONLY | REF_NODEREF;2648 update->flags &= ~REF_HAVE_OLD;26492650 item->util = new_update;26512652return0;2653}26542655/*2656 * Return the refname under which update was originally requested.2657 */2658static const char*original_update_refname(struct ref_update *update)2659{2660while(update->parent_update)2661 update = update->parent_update;26622663return update->refname;2664}26652666/*2667 * Check whether the REF_HAVE_OLD and old_oid values stored in update2668 * are consistent with oid, which is the reference's current value. If2669 * everything is OK, return 0; otherwise, write an error message to2670 * err and return -1.2671 */2672static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2673struct strbuf *err)2674{2675if(!(update->flags & REF_HAVE_OLD) ||2676!oidcmp(oid, &update->old_oid))2677return0;26782679if(is_null_oid(&update->old_oid))2680strbuf_addf(err,"cannot lock ref '%s': "2681"reference already exists",2682original_update_refname(update));2683else if(is_null_oid(oid))2684strbuf_addf(err,"cannot lock ref '%s': "2685"reference is missing but expected%s",2686original_update_refname(update),2687oid_to_hex(&update->old_oid));2688else2689strbuf_addf(err,"cannot lock ref '%s': "2690"is at%sbut expected%s",2691original_update_refname(update),2692oid_to_hex(oid),2693oid_to_hex(&update->old_oid));26942695return-1;2696}26972698/*2699 * Prepare for carrying out update:2700 * - Lock the reference referred to by update.2701 * - Read the reference under lock.2702 * - Check that its old SHA-1 value (if specified) is correct, and in2703 * any case record it in update->lock->old_oid for later use when2704 * writing the reflog.2705 * - If it is a symref update without REF_NODEREF, split it up into a2706 * REF_LOG_ONLY update of the symref and add a separate update for2707 * the referent to transaction.2708 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2709 * update of HEAD.2710 */2711static intlock_ref_for_update(struct files_ref_store *refs,2712struct ref_update *update,2713struct ref_transaction *transaction,2714const char*head_ref,2715struct string_list *affected_refnames,2716struct strbuf *err)2717{2718struct strbuf referent = STRBUF_INIT;2719int mustexist = (update->flags & REF_HAVE_OLD) &&2720!is_null_oid(&update->old_oid);2721int ret;2722struct ref_lock *lock;27232724files_assert_main_repository(refs,"lock_ref_for_update");27252726if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2727 update->flags |= REF_DELETING;27282729if(head_ref) {2730 ret =split_head_update(update, transaction, head_ref,2731 affected_refnames, err);2732if(ret)2733return ret;2734}27352736 ret =lock_raw_ref(refs, update->refname, mustexist,2737 affected_refnames, NULL,2738&lock, &referent,2739&update->type, err);2740if(ret) {2741char*reason;27422743 reason =strbuf_detach(err, NULL);2744strbuf_addf(err,"cannot lock ref '%s':%s",2745original_update_refname(update), reason);2746free(reason);2747return ret;2748}27492750 update->backend_data = lock;27512752if(update->type & REF_ISSYMREF) {2753if(update->flags & REF_NODEREF) {2754/*2755 * We won't be reading the referent as part of2756 * the transaction, so we have to read it here2757 * to record and possibly check old_sha1:2758 */2759if(refs_read_ref_full(&refs->base,2760 referent.buf,0,2761 lock->old_oid.hash, NULL)) {2762if(update->flags & REF_HAVE_OLD) {2763strbuf_addf(err,"cannot lock ref '%s': "2764"error reading reference",2765original_update_refname(update));2766return-1;2767}2768}else if(check_old_oid(update, &lock->old_oid, err)) {2769return TRANSACTION_GENERIC_ERROR;2770}2771}else{2772/*2773 * Create a new update for the reference this2774 * symref is pointing at. Also, we will record2775 * and verify old_sha1 for this update as part2776 * of processing the split-off update, so we2777 * don't have to do it here.2778 */2779 ret =split_symref_update(refs, update,2780 referent.buf, transaction,2781 affected_refnames, err);2782if(ret)2783return ret;2784}2785}else{2786struct ref_update *parent_update;27872788if(check_old_oid(update, &lock->old_oid, err))2789return TRANSACTION_GENERIC_ERROR;27902791/*2792 * If this update is happening indirectly because of a2793 * symref update, record the old SHA-1 in the parent2794 * update:2795 */2796for(parent_update = update->parent_update;2797 parent_update;2798 parent_update = parent_update->parent_update) {2799struct ref_lock *parent_lock = parent_update->backend_data;2800oidcpy(&parent_lock->old_oid, &lock->old_oid);2801}2802}28032804if((update->flags & REF_HAVE_NEW) &&2805!(update->flags & REF_DELETING) &&2806!(update->flags & REF_LOG_ONLY)) {2807if(!(update->type & REF_ISSYMREF) &&2808!oidcmp(&lock->old_oid, &update->new_oid)) {2809/*2810 * The reference already has the desired2811 * value, so we don't need to write it.2812 */2813}else if(write_ref_to_lockfile(lock, &update->new_oid,2814 err)) {2815char*write_err =strbuf_detach(err, NULL);28162817/*2818 * The lock was freed upon failure of2819 * write_ref_to_lockfile():2820 */2821 update->backend_data = NULL;2822strbuf_addf(err,2823"cannot update ref '%s':%s",2824 update->refname, write_err);2825free(write_err);2826return TRANSACTION_GENERIC_ERROR;2827}else{2828 update->flags |= REF_NEEDS_COMMIT;2829}2830}2831if(!(update->flags & REF_NEEDS_COMMIT)) {2832/*2833 * We didn't call write_ref_to_lockfile(), so2834 * the lockfile is still open. Close it to2835 * free up the file descriptor:2836 */2837if(close_ref(lock)) {2838strbuf_addf(err,"couldn't close '%s.lock'",2839 update->refname);2840return TRANSACTION_GENERIC_ERROR;2841}2842}2843return0;2844}28452846static intfiles_transaction_commit(struct ref_store *ref_store,2847struct ref_transaction *transaction,2848struct strbuf *err)2849{2850struct files_ref_store *refs =2851files_downcast(ref_store, REF_STORE_WRITE,2852"ref_transaction_commit");2853int ret =0, i;2854struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2855struct string_list_item *ref_to_delete;2856struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2857char*head_ref = NULL;2858int head_type;2859struct object_id head_oid;2860struct strbuf sb = STRBUF_INIT;28612862assert(err);28632864if(transaction->state != REF_TRANSACTION_OPEN)2865die("BUG: commit called for transaction that is not open");28662867if(!transaction->nr) {2868 transaction->state = REF_TRANSACTION_CLOSED;2869return0;2870}28712872/*2873 * Fail if a refname appears more than once in the2874 * transaction. (If we end up splitting up any updates using2875 * split_symref_update() or split_head_update(), those2876 * functions will check that the new updates don't have the2877 * same refname as any existing ones.)2878 */2879for(i =0; i < transaction->nr; i++) {2880struct ref_update *update = transaction->updates[i];2881struct string_list_item *item =2882string_list_append(&affected_refnames, update->refname);28832884/*2885 * We store a pointer to update in item->util, but at2886 * the moment we never use the value of this field2887 * except to check whether it is non-NULL.2888 */2889 item->util = update;2890}2891string_list_sort(&affected_refnames);2892if(ref_update_reject_duplicates(&affected_refnames, err)) {2893 ret = TRANSACTION_GENERIC_ERROR;2894goto cleanup;2895}28962897/*2898 * Special hack: If a branch is updated directly and HEAD2899 * points to it (may happen on the remote side of a push2900 * for example) then logically the HEAD reflog should be2901 * updated too.2902 *2903 * A generic solution would require reverse symref lookups,2904 * but finding all symrefs pointing to a given branch would be2905 * rather costly for this rare event (the direct update of a2906 * branch) to be worth it. So let's cheat and check with HEAD2907 * only, which should cover 99% of all usage scenarios (even2908 * 100% of the default ones).2909 *2910 * So if HEAD is a symbolic reference, then record the name of2911 * the reference that it points to. If we see an update of2912 * head_ref within the transaction, then split_head_update()2913 * arranges for the reflog of HEAD to be updated, too.2914 */2915 head_ref =refs_resolve_refdup(ref_store,"HEAD",2916 RESOLVE_REF_NO_RECURSE,2917 head_oid.hash, &head_type);29182919if(head_ref && !(head_type & REF_ISSYMREF)) {2920free(head_ref);2921 head_ref = NULL;2922}29232924/*2925 * Acquire all locks, verify old values if provided, check2926 * that new values are valid, and write new values to the2927 * lockfiles, ready to be activated. Only keep one lockfile2928 * open at a time to avoid running out of file descriptors.2929 */2930for(i =0; i < transaction->nr; i++) {2931struct ref_update *update = transaction->updates[i];29322933 ret =lock_ref_for_update(refs, update, transaction,2934 head_ref, &affected_refnames, err);2935if(ret)2936goto cleanup;2937}29382939/* Perform updates first so live commits remain referenced */2940for(i =0; i < transaction->nr; i++) {2941struct ref_update *update = transaction->updates[i];2942struct ref_lock *lock = update->backend_data;29432944if(update->flags & REF_NEEDS_COMMIT ||2945 update->flags & REF_LOG_ONLY) {2946if(files_log_ref_write(refs,2947 lock->ref_name,2948&lock->old_oid,2949&update->new_oid,2950 update->msg, update->flags,2951 err)) {2952char*old_msg =strbuf_detach(err, NULL);29532954strbuf_addf(err,"cannot update the ref '%s':%s",2955 lock->ref_name, old_msg);2956free(old_msg);2957unlock_ref(lock);2958 update->backend_data = NULL;2959 ret = TRANSACTION_GENERIC_ERROR;2960goto cleanup;2961}2962}2963if(update->flags & REF_NEEDS_COMMIT) {2964clear_loose_ref_cache(refs);2965if(commit_ref(lock)) {2966strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2967unlock_ref(lock);2968 update->backend_data = NULL;2969 ret = TRANSACTION_GENERIC_ERROR;2970goto cleanup;2971}2972}2973}2974/* Perform deletes now that updates are safely completed */2975for(i =0; i < transaction->nr; i++) {2976struct ref_update *update = transaction->updates[i];2977struct ref_lock *lock = update->backend_data;29782979if(update->flags & REF_DELETING &&2980!(update->flags & REF_LOG_ONLY)) {2981if(!(update->type & REF_ISPACKED) ||2982 update->type & REF_ISSYMREF) {2983/* It is a loose reference. */2984strbuf_reset(&sb);2985files_ref_path(refs, &sb, lock->ref_name);2986if(unlink_or_msg(sb.buf, err)) {2987 ret = TRANSACTION_GENERIC_ERROR;2988goto cleanup;2989}2990 update->flags |= REF_DELETED_LOOSE;2991}29922993if(!(update->flags & REF_ISPRUNING))2994string_list_append(&refs_to_delete,2995 lock->ref_name);2996}2997}29982999if(repack_without_refs(refs, &refs_to_delete, err)) {3000 ret = TRANSACTION_GENERIC_ERROR;3001goto cleanup;3002}30033004/* Delete the reflogs of any references that were deleted: */3005for_each_string_list_item(ref_to_delete, &refs_to_delete) {3006strbuf_reset(&sb);3007files_reflog_path(refs, &sb, ref_to_delete->string);3008if(!unlink_or_warn(sb.buf))3009try_remove_empty_parents(refs, ref_to_delete->string,3010 REMOVE_EMPTY_PARENTS_REFLOG);3011}30123013clear_loose_ref_cache(refs);30143015cleanup:3016strbuf_release(&sb);3017 transaction->state = REF_TRANSACTION_CLOSED;30183019for(i =0; i < transaction->nr; i++) {3020struct ref_update *update = transaction->updates[i];3021struct ref_lock *lock = update->backend_data;30223023if(lock)3024unlock_ref(lock);30253026if(update->flags & REF_DELETED_LOOSE) {3027/*3028 * The loose reference was deleted. Delete any3029 * empty parent directories. (Note that this3030 * can only work because we have already3031 * removed the lockfile.)3032 */3033try_remove_empty_parents(refs, update->refname,3034 REMOVE_EMPTY_PARENTS_REF);3035}3036}30373038string_list_clear(&refs_to_delete,0);3039free(head_ref);3040string_list_clear(&affected_refnames,0);30413042return ret;3043}30443045static intref_present(const char*refname,3046const struct object_id *oid,int flags,void*cb_data)3047{3048struct string_list *affected_refnames = cb_data;30493050returnstring_list_has_string(affected_refnames, refname);3051}30523053static intfiles_initial_transaction_commit(struct ref_store *ref_store,3054struct ref_transaction *transaction,3055struct strbuf *err)3056{3057struct files_ref_store *refs =3058files_downcast(ref_store, REF_STORE_WRITE,3059"initial_ref_transaction_commit");3060int ret =0, i;3061struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30623063assert(err);30643065if(transaction->state != REF_TRANSACTION_OPEN)3066die("BUG: commit called for transaction that is not open");30673068/* Fail if a refname appears more than once in the transaction: */3069for(i =0; i < transaction->nr; i++)3070string_list_append(&affected_refnames,3071 transaction->updates[i]->refname);3072string_list_sort(&affected_refnames);3073if(ref_update_reject_duplicates(&affected_refnames, err)) {3074 ret = TRANSACTION_GENERIC_ERROR;3075goto cleanup;3076}30773078/*3079 * It's really undefined to call this function in an active3080 * repository or when there are existing references: we are3081 * only locking and changing packed-refs, so (1) any3082 * simultaneous processes might try to change a reference at3083 * the same time we do, and (2) any existing loose versions of3084 * the references that we are setting would have precedence3085 * over our values. But some remote helpers create the remote3086 * "HEAD" and "master" branches before calling this function,3087 * so here we really only check that none of the references3088 * that we are creating already exists.3089 */3090if(refs_for_each_rawref(&refs->base, ref_present,3091&affected_refnames))3092die("BUG: initial ref transaction called with existing refs");30933094for(i =0; i < transaction->nr; i++) {3095struct ref_update *update = transaction->updates[i];30963097if((update->flags & REF_HAVE_OLD) &&3098!is_null_oid(&update->old_oid))3099die("BUG: initial ref transaction with old_sha1 set");3100if(refs_verify_refname_available(&refs->base, update->refname,3101&affected_refnames, NULL,3102 err)) {3103 ret = TRANSACTION_NAME_CONFLICT;3104goto cleanup;3105}3106}31073108if(lock_packed_refs(refs,0)) {3109strbuf_addf(err,"unable to lock packed-refs file:%s",3110strerror(errno));3111 ret = TRANSACTION_GENERIC_ERROR;3112goto cleanup;3113}31143115for(i =0; i < transaction->nr; i++) {3116struct ref_update *update = transaction->updates[i];31173118if((update->flags & REF_HAVE_NEW) &&3119!is_null_oid(&update->new_oid))3120add_packed_ref(refs, update->refname,3121&update->new_oid);3122}31233124if(commit_packed_refs(refs)) {3125strbuf_addf(err,"unable to commit packed-refs file:%s",3126strerror(errno));3127 ret = TRANSACTION_GENERIC_ERROR;3128goto cleanup;3129}31303131cleanup:3132 transaction->state = REF_TRANSACTION_CLOSED;3133string_list_clear(&affected_refnames,0);3134return ret;3135}31363137struct expire_reflog_cb {3138unsigned int flags;3139 reflog_expiry_should_prune_fn *should_prune_fn;3140void*policy_cb;3141FILE*newlog;3142struct object_id last_kept_oid;3143};31443145static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3146const char*email, timestamp_t timestamp,int tz,3147const char*message,void*cb_data)3148{3149struct expire_reflog_cb *cb = cb_data;3150struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;31513152if(cb->flags & EXPIRE_REFLOGS_REWRITE)3153 ooid = &cb->last_kept_oid;31543155if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3156 message, policy_cb)) {3157if(!cb->newlog)3158printf("would prune%s", message);3159else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3160printf("prune%s", message);3161}else{3162if(cb->newlog) {3163fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3164oid_to_hex(ooid),oid_to_hex(noid),3165 email, timestamp, tz, message);3166oidcpy(&cb->last_kept_oid, noid);3167}3168if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3169printf("keep%s", message);3170}3171return0;3172}31733174static intfiles_reflog_expire(struct ref_store *ref_store,3175const char*refname,const unsigned char*sha1,3176unsigned int flags,3177 reflog_expiry_prepare_fn prepare_fn,3178 reflog_expiry_should_prune_fn should_prune_fn,3179 reflog_expiry_cleanup_fn cleanup_fn,3180void*policy_cb_data)3181{3182struct files_ref_store *refs =3183files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3184static struct lock_file reflog_lock;3185struct expire_reflog_cb cb;3186struct ref_lock *lock;3187struct strbuf log_file_sb = STRBUF_INIT;3188char*log_file;3189int status =0;3190int type;3191struct strbuf err = STRBUF_INIT;3192struct object_id oid;31933194memset(&cb,0,sizeof(cb));3195 cb.flags = flags;3196 cb.policy_cb = policy_cb_data;3197 cb.should_prune_fn = should_prune_fn;31983199/*3200 * The reflog file is locked by holding the lock on the3201 * reference itself, plus we might need to update the3202 * reference if --updateref was specified:3203 */3204 lock =lock_ref_sha1_basic(refs, refname, sha1,3205 NULL, NULL, REF_NODEREF,3206&type, &err);3207if(!lock) {3208error("cannot lock ref '%s':%s", refname, err.buf);3209strbuf_release(&err);3210return-1;3211}3212if(!refs_reflog_exists(ref_store, refname)) {3213unlock_ref(lock);3214return0;3215}32163217files_reflog_path(refs, &log_file_sb, refname);3218 log_file =strbuf_detach(&log_file_sb, NULL);3219if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3220/*3221 * Even though holding $GIT_DIR/logs/$reflog.lock has3222 * no locking implications, we use the lock_file3223 * machinery here anyway because it does a lot of the3224 * work we need, including cleaning up if the program3225 * exits unexpectedly.3226 */3227if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3228struct strbuf err = STRBUF_INIT;3229unable_to_lock_message(log_file, errno, &err);3230error("%s", err.buf);3231strbuf_release(&err);3232goto failure;3233}3234 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3235if(!cb.newlog) {3236error("cannot fdopen%s(%s)",3237get_lock_file_path(&reflog_lock),strerror(errno));3238goto failure;3239}3240}32413242hashcpy(oid.hash, sha1);32433244(*prepare_fn)(refname, &oid, cb.policy_cb);3245refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3246(*cleanup_fn)(cb.policy_cb);32473248if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3249/*3250 * It doesn't make sense to adjust a reference pointed3251 * to by a symbolic ref based on expiring entries in3252 * the symbolic reference's reflog. Nor can we update3253 * a reference if there are no remaining reflog3254 * entries.3255 */3256int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3257!(type & REF_ISSYMREF) &&3258!is_null_oid(&cb.last_kept_oid);32593260if(close_lock_file(&reflog_lock)) {3261 status |=error("couldn't write%s:%s", log_file,3262strerror(errno));3263}else if(update &&3264(write_in_full(get_lock_file_fd(lock->lk),3265oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3266write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3267close_ref(lock) <0)) {3268 status |=error("couldn't write%s",3269get_lock_file_path(lock->lk));3270rollback_lock_file(&reflog_lock);3271}else if(commit_lock_file(&reflog_lock)) {3272 status |=error("unable to write reflog '%s' (%s)",3273 log_file,strerror(errno));3274}else if(update &&commit_ref(lock)) {3275 status |=error("couldn't set%s", lock->ref_name);3276}3277}3278free(log_file);3279unlock_ref(lock);3280return status;32813282 failure:3283rollback_lock_file(&reflog_lock);3284free(log_file);3285unlock_ref(lock);3286return-1;3287}32883289static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3290{3291struct files_ref_store *refs =3292files_downcast(ref_store, REF_STORE_WRITE,"init_db");3293struct strbuf sb = STRBUF_INIT;32943295/*3296 * Create .git/refs/{heads,tags}3297 */3298files_ref_path(refs, &sb,"refs/heads");3299safe_create_dir(sb.buf,1);33003301strbuf_reset(&sb);3302files_ref_path(refs, &sb,"refs/tags");3303safe_create_dir(sb.buf,1);33043305strbuf_release(&sb);3306return0;3307}33083309struct ref_storage_be refs_be_files = {3310 NULL,3311"files",3312 files_ref_store_create,3313 files_init_db,3314 files_transaction_commit,3315 files_initial_transaction_commit,33163317 files_pack_refs,3318 files_peel_ref,3319 files_create_symref,3320 files_delete_refs,3321 files_rename_ref,33223323 files_ref_iterator_begin,3324 files_read_raw_ref,33253326 files_reflog_iterator_begin,3327 files_for_each_reflog_ent,3328 files_for_each_reflog_ent_reverse,3329 files_reflog_exists,3330 files_create_reflog,3331 files_delete_reflog,3332 files_reflog_expire3333};