1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * A container for `packed-refs`-related data. It is not (yet) a 52 * `ref_store`. 53 */ 54struct packed_ref_store { 55unsigned int store_flags; 56 57/* The path of the "packed-refs" file: */ 58char*path; 59 60/* 61 * A cache of the values read from the `packed-refs` file, if 62 * it might still be current; otherwise, NULL. 63 */ 64struct packed_ref_cache *cache; 65 66/* 67 * Lock used for the "packed-refs" file. Note that this (and 68 * thus the enclosing `packed_ref_store`) must not be freed. 69 */ 70struct lock_file lock; 71}; 72 73static struct packed_ref_store *packed_ref_store_create( 74const char*path,unsigned int store_flags) 75{ 76struct packed_ref_store *refs =xcalloc(1,sizeof(*refs)); 77 78 refs->store_flags = store_flags; 79 refs->path =xstrdup(path); 80return refs; 81} 82 83/* 84 * Die if refs is not the main ref store. caller is used in any 85 * necessary error messages. 86 */ 87static voidpacked_assert_main_repository(struct packed_ref_store *refs, 88const char*caller) 89{ 90if(refs->store_flags & REF_STORE_MAIN) 91return; 92 93die("BUG: operation%sonly allowed for main ref store", caller); 94} 95 96/* 97 * Future: need to be in "struct repository" 98 * when doing a full libification. 99 */ 100struct files_ref_store { 101struct ref_store base; 102unsigned int store_flags; 103 104char*gitdir; 105char*gitcommondir; 106 107struct ref_cache *loose; 108 109struct packed_ref_store *packed_ref_store; 110}; 111 112/* 113 * Increment the reference count of *packed_refs. 114 */ 115static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 116{ 117 packed_refs->referrers++; 118} 119 120/* 121 * Decrease the reference count of *packed_refs. If it goes to zero, 122 * free *packed_refs and return true; otherwise return false. 123 */ 124static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 125{ 126if(!--packed_refs->referrers) { 127free_ref_cache(packed_refs->cache); 128stat_validity_clear(&packed_refs->validity); 129free(packed_refs); 130return1; 131}else{ 132return0; 133} 134} 135 136static voidclear_packed_ref_cache(struct packed_ref_store *refs) 137{ 138if(refs->cache) { 139struct packed_ref_cache *cache = refs->cache; 140 141if(is_lock_file_locked(&refs->lock)) 142die("BUG: packed-ref cache cleared while locked"); 143 refs->cache = NULL; 144release_packed_ref_cache(cache); 145} 146} 147 148static voidclear_loose_ref_cache(struct files_ref_store *refs) 149{ 150if(refs->loose) { 151free_ref_cache(refs->loose); 152 refs->loose = NULL; 153} 154} 155 156/* 157 * Create a new submodule ref cache and add it to the internal 158 * set of caches. 159 */ 160static struct ref_store *files_ref_store_create(const char*gitdir, 161unsigned int flags) 162{ 163struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 164struct ref_store *ref_store = (struct ref_store *)refs; 165struct strbuf sb = STRBUF_INIT; 166 167base_ref_store_init(ref_store, &refs_be_files); 168 refs->store_flags = flags; 169 170 refs->gitdir =xstrdup(gitdir); 171get_common_dir_noenv(&sb, gitdir); 172 refs->gitcommondir =strbuf_detach(&sb, NULL); 173strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 174 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 175strbuf_release(&sb); 176 177return ref_store; 178} 179 180/* 181 * Die if refs is not the main ref store. caller is used in any 182 * necessary error messages. 183 */ 184static voidfiles_assert_main_repository(struct files_ref_store *refs, 185const char*caller) 186{ 187if(refs->store_flags & REF_STORE_MAIN) 188return; 189 190die("BUG: operation%sonly allowed for main ref store", caller); 191} 192 193/* 194 * Downcast ref_store to files_ref_store. Die if ref_store is not a 195 * files_ref_store. required_flags is compared with ref_store's 196 * store_flags to ensure the ref_store has all required capabilities. 197 * "caller" is used in any necessary error messages. 198 */ 199static struct files_ref_store *files_downcast(struct ref_store *ref_store, 200unsigned int required_flags, 201const char*caller) 202{ 203struct files_ref_store *refs; 204 205if(ref_store->be != &refs_be_files) 206die("BUG: ref_store is type\"%s\"not\"files\"in%s", 207 ref_store->be->name, caller); 208 209 refs = (struct files_ref_store *)ref_store; 210 211if((refs->store_flags & required_flags) != required_flags) 212die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 213 caller, required_flags, refs->store_flags); 214 215return refs; 216} 217 218/* The length of a peeled reference line in packed-refs, including EOL: */ 219#define PEELED_LINE_LENGTH 42 220 221/* 222 * The packed-refs header line that we write out. Perhaps other 223 * traits will be added later. The trailing space is required. 224 */ 225static const char PACKED_REFS_HEADER[] = 226"# pack-refs with: peeled fully-peeled\n"; 227 228/* 229 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 230 * Return a pointer to the refname within the line (null-terminated), 231 * or NULL if there was a problem. 232 */ 233static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 234{ 235const char*ref; 236 237if(parse_oid_hex(line->buf, oid, &ref) <0) 238return NULL; 239if(!isspace(*ref++)) 240return NULL; 241 242if(isspace(*ref)) 243return NULL; 244 245if(line->buf[line->len -1] !='\n') 246return NULL; 247 line->buf[--line->len] =0; 248 249return ref; 250} 251 252/* 253 * Read from `packed_refs_file` into a newly-allocated 254 * `packed_ref_cache` and return it. The return value will already 255 * have its reference count incremented. 256 * 257 * A comment line of the form "# pack-refs with: " may contain zero or 258 * more traits. We interpret the traits as follows: 259 * 260 * No traits: 261 * 262 * Probably no references are peeled. But if the file contains a 263 * peeled value for a reference, we will use it. 264 * 265 * peeled: 266 * 267 * References under "refs/tags/", if they *can* be peeled, *are* 268 * peeled in this file. References outside of "refs/tags/" are 269 * probably not peeled even if they could have been, but if we find 270 * a peeled value for such a reference we will use it. 271 * 272 * fully-peeled: 273 * 274 * All references in the file that can be peeled are peeled. 275 * Inversely (and this is more important), any references in the 276 * file for which no peeled value is recorded is not peelable. This 277 * trait should typically be written alongside "peeled" for 278 * compatibility with older clients, but we do not require it 279 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 280 */ 281static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 282{ 283FILE*f; 284struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 285struct ref_entry *last = NULL; 286struct strbuf line = STRBUF_INIT; 287enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 288struct ref_dir *dir; 289 290acquire_packed_ref_cache(packed_refs); 291 packed_refs->cache =create_ref_cache(NULL, NULL); 292 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 293 294 f =fopen(packed_refs_file,"r"); 295if(!f) { 296if(errno == ENOENT) { 297/* 298 * This is OK; it just means that no 299 * "packed-refs" file has been written yet, 300 * which is equivalent to it being empty. 301 */ 302return packed_refs; 303}else{ 304die_errno("couldn't read%s", packed_refs_file); 305} 306} 307 308stat_validity_update(&packed_refs->validity,fileno(f)); 309 310 dir =get_ref_dir(packed_refs->cache->root); 311while(strbuf_getwholeline(&line, f,'\n') != EOF) { 312struct object_id oid; 313const char*refname; 314const char*traits; 315 316if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 317if(strstr(traits," fully-peeled ")) 318 peeled = PEELED_FULLY; 319else if(strstr(traits," peeled ")) 320 peeled = PEELED_TAGS; 321/* perhaps other traits later as well */ 322continue; 323} 324 325 refname =parse_ref_line(&line, &oid); 326if(refname) { 327int flag = REF_ISPACKED; 328 329if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 330if(!refname_is_safe(refname)) 331die("packed refname is dangerous:%s", refname); 332oidclr(&oid); 333 flag |= REF_BAD_NAME | REF_ISBROKEN; 334} 335 last =create_ref_entry(refname, &oid, flag); 336if(peeled == PEELED_FULLY || 337(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 338 last->flag |= REF_KNOWS_PEELED; 339add_ref_entry(dir, last); 340continue; 341} 342if(last && 343 line.buf[0] =='^'&& 344 line.len == PEELED_LINE_LENGTH && 345 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 346!get_oid_hex(line.buf +1, &oid)) { 347oidcpy(&last->u.value.peeled, &oid); 348/* 349 * Regardless of what the file header said, 350 * we definitely know the value of *this* 351 * reference: 352 */ 353 last->flag |= REF_KNOWS_PEELED; 354} 355} 356 357fclose(f); 358strbuf_release(&line); 359 360return packed_refs; 361} 362 363static voidfiles_reflog_path(struct files_ref_store *refs, 364struct strbuf *sb, 365const char*refname) 366{ 367if(!refname) { 368/* 369 * FIXME: of course this is wrong in multi worktree 370 * setting. To be fixed real soon. 371 */ 372strbuf_addf(sb,"%s/logs", refs->gitcommondir); 373return; 374} 375 376switch(ref_type(refname)) { 377case REF_TYPE_PER_WORKTREE: 378case REF_TYPE_PSEUDOREF: 379strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 380break; 381case REF_TYPE_NORMAL: 382strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 383break; 384default: 385die("BUG: unknown ref type%dof ref%s", 386ref_type(refname), refname); 387} 388} 389 390static voidfiles_ref_path(struct files_ref_store *refs, 391struct strbuf *sb, 392const char*refname) 393{ 394switch(ref_type(refname)) { 395case REF_TYPE_PER_WORKTREE: 396case REF_TYPE_PSEUDOREF: 397strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 398break; 399case REF_TYPE_NORMAL: 400strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 401break; 402default: 403die("BUG: unknown ref type%dof ref%s", 404ref_type(refname), refname); 405} 406} 407 408/* 409 * Check that the packed refs cache (if any) still reflects the 410 * contents of the file. If not, clear the cache. 411 */ 412static voidvalidate_packed_ref_cache(struct packed_ref_store *refs) 413{ 414if(refs->cache && 415!stat_validity_check(&refs->cache->validity, refs->path)) 416clear_packed_ref_cache(refs); 417} 418 419/* 420 * Get the packed_ref_cache for the specified packed_ref_store, 421 * creating and populating it if it hasn't been read before or if the 422 * file has been changed (according to its `validity` field) since it 423 * was last read. On the other hand, if we hold the lock, then assume 424 * that the file hasn't been changed out from under us, so skip the 425 * extra `stat()` call in `stat_validity_check()`. 426 */ 427static struct packed_ref_cache *get_packed_ref_cache(struct packed_ref_store *refs) 428{ 429if(!is_lock_file_locked(&refs->lock)) 430validate_packed_ref_cache(refs); 431 432if(!refs->cache) 433 refs->cache =read_packed_refs(refs->path); 434 435return refs->cache; 436} 437 438static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 439{ 440returnget_ref_dir(packed_ref_cache->cache->root); 441} 442 443static struct ref_dir *get_packed_refs(struct packed_ref_store *refs) 444{ 445returnget_packed_ref_dir(get_packed_ref_cache(refs)); 446} 447 448/* 449 * Add or overwrite a reference in the in-memory packed reference 450 * cache. This may only be called while the packed-refs file is locked 451 * (see lock_packed_refs()). To actually write the packed-refs file, 452 * call commit_packed_refs(). 453 */ 454static voidadd_packed_ref(struct packed_ref_store *refs, 455const char*refname,const struct object_id *oid) 456{ 457struct ref_dir *packed_refs; 458struct ref_entry *packed_entry; 459 460if(!is_lock_file_locked(&refs->lock)) 461die("BUG: packed refs not locked"); 462 463if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 464die("Reference has invalid format: '%s'", refname); 465 466 packed_refs =get_packed_refs(refs); 467 packed_entry =find_ref_entry(packed_refs, refname); 468if(packed_entry) { 469/* Overwrite the existing entry: */ 470oidcpy(&packed_entry->u.value.oid, oid); 471 packed_entry->flag = REF_ISPACKED; 472oidclr(&packed_entry->u.value.peeled); 473}else{ 474 packed_entry =create_ref_entry(refname, oid, REF_ISPACKED); 475add_ref_entry(packed_refs, packed_entry); 476} 477} 478 479/* 480 * Read the loose references from the namespace dirname into dir 481 * (without recursing). dirname must end with '/'. dir must be the 482 * directory entry corresponding to dirname. 483 */ 484static voidloose_fill_ref_dir(struct ref_store *ref_store, 485struct ref_dir *dir,const char*dirname) 486{ 487struct files_ref_store *refs = 488files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 489DIR*d; 490struct dirent *de; 491int dirnamelen =strlen(dirname); 492struct strbuf refname; 493struct strbuf path = STRBUF_INIT; 494size_t path_baselen; 495 496files_ref_path(refs, &path, dirname); 497 path_baselen = path.len; 498 499 d =opendir(path.buf); 500if(!d) { 501strbuf_release(&path); 502return; 503} 504 505strbuf_init(&refname, dirnamelen +257); 506strbuf_add(&refname, dirname, dirnamelen); 507 508while((de =readdir(d)) != NULL) { 509struct object_id oid; 510struct stat st; 511int flag; 512 513if(de->d_name[0] =='.') 514continue; 515if(ends_with(de->d_name,".lock")) 516continue; 517strbuf_addstr(&refname, de->d_name); 518strbuf_addstr(&path, de->d_name); 519if(stat(path.buf, &st) <0) { 520;/* silently ignore */ 521}else if(S_ISDIR(st.st_mode)) { 522strbuf_addch(&refname,'/'); 523add_entry_to_dir(dir, 524create_dir_entry(dir->cache, refname.buf, 525 refname.len,1)); 526}else{ 527if(!refs_resolve_ref_unsafe(&refs->base, 528 refname.buf, 529 RESOLVE_REF_READING, 530 oid.hash, &flag)) { 531oidclr(&oid); 532 flag |= REF_ISBROKEN; 533}else if(is_null_oid(&oid)) { 534/* 535 * It is so astronomically unlikely 536 * that NULL_SHA1 is the SHA-1 of an 537 * actual object that we consider its 538 * appearance in a loose reference 539 * file to be repo corruption 540 * (probably due to a software bug). 541 */ 542 flag |= REF_ISBROKEN; 543} 544 545if(check_refname_format(refname.buf, 546 REFNAME_ALLOW_ONELEVEL)) { 547if(!refname_is_safe(refname.buf)) 548die("loose refname is dangerous:%s", refname.buf); 549oidclr(&oid); 550 flag |= REF_BAD_NAME | REF_ISBROKEN; 551} 552add_entry_to_dir(dir, 553create_ref_entry(refname.buf, &oid, flag)); 554} 555strbuf_setlen(&refname, dirnamelen); 556strbuf_setlen(&path, path_baselen); 557} 558strbuf_release(&refname); 559strbuf_release(&path); 560closedir(d); 561 562/* 563 * Manually add refs/bisect, which, being per-worktree, might 564 * not appear in the directory listing for refs/ in the main 565 * repo. 566 */ 567if(!strcmp(dirname,"refs/")) { 568int pos =search_ref_dir(dir,"refs/bisect/",12); 569 570if(pos <0) { 571struct ref_entry *child_entry =create_dir_entry( 572 dir->cache,"refs/bisect/",12,1); 573add_entry_to_dir(dir, child_entry); 574} 575} 576} 577 578static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 579{ 580if(!refs->loose) { 581/* 582 * Mark the top-level directory complete because we 583 * are about to read the only subdirectory that can 584 * hold references: 585 */ 586 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 587 588/* We're going to fill the top level ourselves: */ 589 refs->loose->root->flag &= ~REF_INCOMPLETE; 590 591/* 592 * Add an incomplete entry for "refs/" (to be filled 593 * lazily): 594 */ 595add_entry_to_dir(get_ref_dir(refs->loose->root), 596create_dir_entry(refs->loose,"refs/",5,1)); 597} 598return refs->loose; 599} 600 601/* 602 * Return the ref_entry for the given refname from the packed 603 * references. If it does not exist, return NULL. 604 */ 605static struct ref_entry *get_packed_ref(struct packed_ref_store *refs, 606const char*refname) 607{ 608returnfind_ref_entry(get_packed_refs(refs), refname); 609} 610 611/* 612 * A loose ref file doesn't exist; check for a packed ref. 613 */ 614static intresolve_packed_ref(struct files_ref_store *refs, 615const char*refname, 616unsigned char*sha1,unsigned int*flags) 617{ 618struct ref_entry *entry; 619 620/* 621 * The loose reference file does not exist; check for a packed 622 * reference. 623 */ 624 entry =get_packed_ref(refs->packed_ref_store, refname); 625if(entry) { 626hashcpy(sha1, entry->u.value.oid.hash); 627*flags |= REF_ISPACKED; 628return0; 629} 630/* refname is not a packed reference. */ 631return-1; 632} 633 634static intfiles_read_raw_ref(struct ref_store *ref_store, 635const char*refname,unsigned char*sha1, 636struct strbuf *referent,unsigned int*type) 637{ 638struct files_ref_store *refs = 639files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 640struct strbuf sb_contents = STRBUF_INIT; 641struct strbuf sb_path = STRBUF_INIT; 642const char*path; 643const char*buf; 644struct stat st; 645int fd; 646int ret = -1; 647int save_errno; 648int remaining_retries =3; 649 650*type =0; 651strbuf_reset(&sb_path); 652 653files_ref_path(refs, &sb_path, refname); 654 655 path = sb_path.buf; 656 657stat_ref: 658/* 659 * We might have to loop back here to avoid a race 660 * condition: first we lstat() the file, then we try 661 * to read it as a link or as a file. But if somebody 662 * changes the type of the file (file <-> directory 663 * <-> symlink) between the lstat() and reading, then 664 * we don't want to report that as an error but rather 665 * try again starting with the lstat(). 666 * 667 * We'll keep a count of the retries, though, just to avoid 668 * any confusing situation sending us into an infinite loop. 669 */ 670 671if(remaining_retries-- <=0) 672goto out; 673 674if(lstat(path, &st) <0) { 675if(errno != ENOENT) 676goto out; 677if(resolve_packed_ref(refs, refname, sha1, type)) { 678 errno = ENOENT; 679goto out; 680} 681 ret =0; 682goto out; 683} 684 685/* Follow "normalized" - ie "refs/.." symlinks by hand */ 686if(S_ISLNK(st.st_mode)) { 687strbuf_reset(&sb_contents); 688if(strbuf_readlink(&sb_contents, path,0) <0) { 689if(errno == ENOENT || errno == EINVAL) 690/* inconsistent with lstat; retry */ 691goto stat_ref; 692else 693goto out; 694} 695if(starts_with(sb_contents.buf,"refs/") && 696!check_refname_format(sb_contents.buf,0)) { 697strbuf_swap(&sb_contents, referent); 698*type |= REF_ISSYMREF; 699 ret =0; 700goto out; 701} 702/* 703 * It doesn't look like a refname; fall through to just 704 * treating it like a non-symlink, and reading whatever it 705 * points to. 706 */ 707} 708 709/* Is it a directory? */ 710if(S_ISDIR(st.st_mode)) { 711/* 712 * Even though there is a directory where the loose 713 * ref is supposed to be, there could still be a 714 * packed ref: 715 */ 716if(resolve_packed_ref(refs, refname, sha1, type)) { 717 errno = EISDIR; 718goto out; 719} 720 ret =0; 721goto out; 722} 723 724/* 725 * Anything else, just open it and try to use it as 726 * a ref 727 */ 728 fd =open(path, O_RDONLY); 729if(fd <0) { 730if(errno == ENOENT && !S_ISLNK(st.st_mode)) 731/* inconsistent with lstat; retry */ 732goto stat_ref; 733else 734goto out; 735} 736strbuf_reset(&sb_contents); 737if(strbuf_read(&sb_contents, fd,256) <0) { 738int save_errno = errno; 739close(fd); 740 errno = save_errno; 741goto out; 742} 743close(fd); 744strbuf_rtrim(&sb_contents); 745 buf = sb_contents.buf; 746if(starts_with(buf,"ref:")) { 747 buf +=4; 748while(isspace(*buf)) 749 buf++; 750 751strbuf_reset(referent); 752strbuf_addstr(referent, buf); 753*type |= REF_ISSYMREF; 754 ret =0; 755goto out; 756} 757 758/* 759 * Please note that FETCH_HEAD has additional 760 * data after the sha. 761 */ 762if(get_sha1_hex(buf, sha1) || 763(buf[40] !='\0'&& !isspace(buf[40]))) { 764*type |= REF_ISBROKEN; 765 errno = EINVAL; 766goto out; 767} 768 769 ret =0; 770 771out: 772 save_errno = errno; 773strbuf_release(&sb_path); 774strbuf_release(&sb_contents); 775 errno = save_errno; 776return ret; 777} 778 779static voidunlock_ref(struct ref_lock *lock) 780{ 781/* Do not free lock->lk -- atexit() still looks at them */ 782if(lock->lk) 783rollback_lock_file(lock->lk); 784free(lock->ref_name); 785free(lock); 786} 787 788/* 789 * Lock refname, without following symrefs, and set *lock_p to point 790 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 791 * and type similarly to read_raw_ref(). 792 * 793 * The caller must verify that refname is a "safe" reference name (in 794 * the sense of refname_is_safe()) before calling this function. 795 * 796 * If the reference doesn't already exist, verify that refname doesn't 797 * have a D/F conflict with any existing references. extras and skip 798 * are passed to refs_verify_refname_available() for this check. 799 * 800 * If mustexist is not set and the reference is not found or is 801 * broken, lock the reference anyway but clear sha1. 802 * 803 * Return 0 on success. On failure, write an error message to err and 804 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 805 * 806 * Implementation note: This function is basically 807 * 808 * lock reference 809 * read_raw_ref() 810 * 811 * but it includes a lot more code to 812 * - Deal with possible races with other processes 813 * - Avoid calling refs_verify_refname_available() when it can be 814 * avoided, namely if we were successfully able to read the ref 815 * - Generate informative error messages in the case of failure 816 */ 817static intlock_raw_ref(struct files_ref_store *refs, 818const char*refname,int mustexist, 819const struct string_list *extras, 820const struct string_list *skip, 821struct ref_lock **lock_p, 822struct strbuf *referent, 823unsigned int*type, 824struct strbuf *err) 825{ 826struct ref_lock *lock; 827struct strbuf ref_file = STRBUF_INIT; 828int attempts_remaining =3; 829int ret = TRANSACTION_GENERIC_ERROR; 830 831assert(err); 832files_assert_main_repository(refs,"lock_raw_ref"); 833 834*type =0; 835 836/* First lock the file so it can't change out from under us. */ 837 838*lock_p = lock =xcalloc(1,sizeof(*lock)); 839 840 lock->ref_name =xstrdup(refname); 841files_ref_path(refs, &ref_file, refname); 842 843retry: 844switch(safe_create_leading_directories(ref_file.buf)) { 845case SCLD_OK: 846break;/* success */ 847case SCLD_EXISTS: 848/* 849 * Suppose refname is "refs/foo/bar". We just failed 850 * to create the containing directory, "refs/foo", 851 * because there was a non-directory in the way. This 852 * indicates a D/F conflict, probably because of 853 * another reference such as "refs/foo". There is no 854 * reason to expect this error to be transitory. 855 */ 856if(refs_verify_refname_available(&refs->base, refname, 857 extras, skip, err)) { 858if(mustexist) { 859/* 860 * To the user the relevant error is 861 * that the "mustexist" reference is 862 * missing: 863 */ 864strbuf_reset(err); 865strbuf_addf(err,"unable to resolve reference '%s'", 866 refname); 867}else{ 868/* 869 * The error message set by 870 * refs_verify_refname_available() is 871 * OK. 872 */ 873 ret = TRANSACTION_NAME_CONFLICT; 874} 875}else{ 876/* 877 * The file that is in the way isn't a loose 878 * reference. Report it as a low-level 879 * failure. 880 */ 881strbuf_addf(err,"unable to create lock file%s.lock; " 882"non-directory in the way", 883 ref_file.buf); 884} 885goto error_return; 886case SCLD_VANISHED: 887/* Maybe another process was tidying up. Try again. */ 888if(--attempts_remaining >0) 889goto retry; 890/* fall through */ 891default: 892strbuf_addf(err,"unable to create directory for%s", 893 ref_file.buf); 894goto error_return; 895} 896 897if(!lock->lk) 898 lock->lk =xcalloc(1,sizeof(struct lock_file)); 899 900if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 901if(errno == ENOENT && --attempts_remaining >0) { 902/* 903 * Maybe somebody just deleted one of the 904 * directories leading to ref_file. Try 905 * again: 906 */ 907goto retry; 908}else{ 909unable_to_lock_message(ref_file.buf, errno, err); 910goto error_return; 911} 912} 913 914/* 915 * Now we hold the lock and can read the reference without 916 * fear that its value will change. 917 */ 918 919if(files_read_raw_ref(&refs->base, refname, 920 lock->old_oid.hash, referent, type)) { 921if(errno == ENOENT) { 922if(mustexist) { 923/* Garden variety missing reference. */ 924strbuf_addf(err,"unable to resolve reference '%s'", 925 refname); 926goto error_return; 927}else{ 928/* 929 * Reference is missing, but that's OK. We 930 * know that there is not a conflict with 931 * another loose reference because 932 * (supposing that we are trying to lock 933 * reference "refs/foo/bar"): 934 * 935 * - We were successfully able to create 936 * the lockfile refs/foo/bar.lock, so we 937 * know there cannot be a loose reference 938 * named "refs/foo". 939 * 940 * - We got ENOENT and not EISDIR, so we 941 * know that there cannot be a loose 942 * reference named "refs/foo/bar/baz". 943 */ 944} 945}else if(errno == EISDIR) { 946/* 947 * There is a directory in the way. It might have 948 * contained references that have been deleted. If 949 * we don't require that the reference already 950 * exists, try to remove the directory so that it 951 * doesn't cause trouble when we want to rename the 952 * lockfile into place later. 953 */ 954if(mustexist) { 955/* Garden variety missing reference. */ 956strbuf_addf(err,"unable to resolve reference '%s'", 957 refname); 958goto error_return; 959}else if(remove_dir_recursively(&ref_file, 960 REMOVE_DIR_EMPTY_ONLY)) { 961if(refs_verify_refname_available( 962&refs->base, refname, 963 extras, skip, err)) { 964/* 965 * The error message set by 966 * verify_refname_available() is OK. 967 */ 968 ret = TRANSACTION_NAME_CONFLICT; 969goto error_return; 970}else{ 971/* 972 * We can't delete the directory, 973 * but we also don't know of any 974 * references that it should 975 * contain. 976 */ 977strbuf_addf(err,"there is a non-empty directory '%s' " 978"blocking reference '%s'", 979 ref_file.buf, refname); 980goto error_return; 981} 982} 983}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 984strbuf_addf(err,"unable to resolve reference '%s': " 985"reference broken", refname); 986goto error_return; 987}else{ 988strbuf_addf(err,"unable to resolve reference '%s':%s", 989 refname,strerror(errno)); 990goto error_return; 991} 992 993/* 994 * If the ref did not exist and we are creating it, 995 * make sure there is no existing ref that conflicts 996 * with refname: 997 */ 998if(refs_verify_refname_available( 999&refs->base, refname,1000 extras, skip, err))1001goto error_return;1002}10031004 ret =0;1005goto out;10061007error_return:1008unlock_ref(lock);1009*lock_p = NULL;10101011out:1012strbuf_release(&ref_file);1013return ret;1014}10151016static intfiles_peel_ref(struct ref_store *ref_store,1017const char*refname,unsigned char*sha1)1018{1019struct files_ref_store *refs =1020files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,1021"peel_ref");1022int flag;1023unsigned char base[20];10241025if(current_ref_iter && current_ref_iter->refname == refname) {1026struct object_id peeled;10271028if(ref_iterator_peel(current_ref_iter, &peeled))1029return-1;1030hashcpy(sha1, peeled.hash);1031return0;1032}10331034if(refs_read_ref_full(ref_store, refname,1035 RESOLVE_REF_READING, base, &flag))1036return-1;10371038/*1039 * If the reference is packed, read its ref_entry from the1040 * cache in the hope that we already know its peeled value.1041 * We only try this optimization on packed references because1042 * (a) forcing the filling of the loose reference cache could1043 * be expensive and (b) loose references anyway usually do not1044 * have REF_KNOWS_PEELED.1045 */1046if(flag & REF_ISPACKED) {1047struct ref_entry *r =1048get_packed_ref(refs->packed_ref_store, refname);10491050if(r) {1051if(peel_entry(r,0))1052return-1;1053hashcpy(sha1, r->u.value.peeled.hash);1054return0;1055}1056}10571058returnpeel_object(base, sha1);1059}10601061struct files_ref_iterator {1062struct ref_iterator base;10631064struct packed_ref_cache *packed_ref_cache;1065struct ref_iterator *iter0;1066unsigned int flags;1067};10681069static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1070{1071struct files_ref_iterator *iter =1072(struct files_ref_iterator *)ref_iterator;1073int ok;10741075while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1076if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1077ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1078continue;10791080if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1081!ref_resolves_to_object(iter->iter0->refname,1082 iter->iter0->oid,1083 iter->iter0->flags))1084continue;10851086 iter->base.refname = iter->iter0->refname;1087 iter->base.oid = iter->iter0->oid;1088 iter->base.flags = iter->iter0->flags;1089return ITER_OK;1090}10911092 iter->iter0 = NULL;1093if(ref_iterator_abort(ref_iterator) != ITER_DONE)1094 ok = ITER_ERROR;10951096return ok;1097}10981099static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1100struct object_id *peeled)1101{1102struct files_ref_iterator *iter =1103(struct files_ref_iterator *)ref_iterator;11041105returnref_iterator_peel(iter->iter0, peeled);1106}11071108static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1109{1110struct files_ref_iterator *iter =1111(struct files_ref_iterator *)ref_iterator;1112int ok = ITER_DONE;11131114if(iter->iter0)1115 ok =ref_iterator_abort(iter->iter0);11161117release_packed_ref_cache(iter->packed_ref_cache);1118base_ref_iterator_free(ref_iterator);1119return ok;1120}11211122static struct ref_iterator_vtable files_ref_iterator_vtable = {1123 files_ref_iterator_advance,1124 files_ref_iterator_peel,1125 files_ref_iterator_abort1126};11271128static struct ref_iterator *files_ref_iterator_begin(1129struct ref_store *ref_store,1130const char*prefix,unsigned int flags)1131{1132struct files_ref_store *refs;1133struct ref_iterator *loose_iter, *packed_iter;1134struct files_ref_iterator *iter;1135struct ref_iterator *ref_iterator;1136unsigned int required_flags = REF_STORE_READ;11371138if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1139 required_flags |= REF_STORE_ODB;11401141 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11421143 iter =xcalloc(1,sizeof(*iter));1144 ref_iterator = &iter->base;1145base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11461147/*1148 * We must make sure that all loose refs are read before1149 * accessing the packed-refs file; this avoids a race1150 * condition if loose refs are migrated to the packed-refs1151 * file by a simultaneous process, but our in-memory view is1152 * from before the migration. We ensure this as follows:1153 * First, we call start the loose refs iteration with its1154 * `prime_ref` argument set to true. This causes the loose1155 * references in the subtree to be pre-read into the cache.1156 * (If they've already been read, that's OK; we only need to1157 * guarantee that they're read before the packed refs, not1158 * *how much* before.) After that, we call1159 * get_packed_ref_cache(), which internally checks whether the1160 * packed-ref cache is up to date with what is on disk, and1161 * re-reads it if not.1162 */11631164 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1165 prefix,1);11661167 iter->packed_ref_cache =get_packed_ref_cache(refs->packed_ref_store);1168acquire_packed_ref_cache(iter->packed_ref_cache);1169 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1170 prefix,0);11711172 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1173 iter->flags = flags;11741175return ref_iterator;1176}11771178/*1179 * Verify that the reference locked by lock has the value old_sha1.1180 * Fail if the reference doesn't exist and mustexist is set. Return 01181 * on success. On error, write an error message to err, set errno, and1182 * return a negative value.1183 */1184static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1185const unsigned char*old_sha1,int mustexist,1186struct strbuf *err)1187{1188assert(err);11891190if(refs_read_ref_full(ref_store, lock->ref_name,1191 mustexist ? RESOLVE_REF_READING :0,1192 lock->old_oid.hash, NULL)) {1193if(old_sha1) {1194int save_errno = errno;1195strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1196 errno = save_errno;1197return-1;1198}else{1199oidclr(&lock->old_oid);1200return0;1201}1202}1203if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1204strbuf_addf(err,"ref '%s' is at%sbut expected%s",1205 lock->ref_name,1206oid_to_hex(&lock->old_oid),1207sha1_to_hex(old_sha1));1208 errno = EBUSY;1209return-1;1210}1211return0;1212}12131214static intremove_empty_directories(struct strbuf *path)1215{1216/*1217 * we want to create a file but there is a directory there;1218 * if that is an empty directory (or a directory that contains1219 * only empty directories), remove them.1220 */1221returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1222}12231224static intcreate_reflock(const char*path,void*cb)1225{1226struct lock_file *lk = cb;12271228returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1229}12301231/*1232 * Locks a ref returning the lock on success and NULL on failure.1233 * On failure errno is set to something meaningful.1234 */1235static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1236const char*refname,1237const unsigned char*old_sha1,1238const struct string_list *extras,1239const struct string_list *skip,1240unsigned int flags,int*type,1241struct strbuf *err)1242{1243struct strbuf ref_file = STRBUF_INIT;1244struct ref_lock *lock;1245int last_errno =0;1246int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1247int resolve_flags = RESOLVE_REF_NO_RECURSE;1248int resolved;12491250files_assert_main_repository(refs,"lock_ref_sha1_basic");1251assert(err);12521253 lock =xcalloc(1,sizeof(struct ref_lock));12541255if(mustexist)1256 resolve_flags |= RESOLVE_REF_READING;1257if(flags & REF_DELETING)1258 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12591260files_ref_path(refs, &ref_file, refname);1261 resolved = !!refs_resolve_ref_unsafe(&refs->base,1262 refname, resolve_flags,1263 lock->old_oid.hash, type);1264if(!resolved && errno == EISDIR) {1265/*1266 * we are trying to lock foo but we used to1267 * have foo/bar which now does not exist;1268 * it is normal for the empty directory 'foo'1269 * to remain.1270 */1271if(remove_empty_directories(&ref_file)) {1272 last_errno = errno;1273if(!refs_verify_refname_available(1274&refs->base,1275 refname, extras, skip, err))1276strbuf_addf(err,"there are still refs under '%s'",1277 refname);1278goto error_return;1279}1280 resolved = !!refs_resolve_ref_unsafe(&refs->base,1281 refname, resolve_flags,1282 lock->old_oid.hash, type);1283}1284if(!resolved) {1285 last_errno = errno;1286if(last_errno != ENOTDIR ||1287!refs_verify_refname_available(&refs->base, refname,1288 extras, skip, err))1289strbuf_addf(err,"unable to resolve reference '%s':%s",1290 refname,strerror(last_errno));12911292goto error_return;1293}12941295/*1296 * If the ref did not exist and we are creating it, make sure1297 * there is no existing packed ref whose name begins with our1298 * refname, nor a packed ref whose name is a proper prefix of1299 * our refname.1300 */1301if(is_null_oid(&lock->old_oid) &&1302refs_verify_refname_available(&refs->base, refname,1303 extras, skip, err)) {1304 last_errno = ENOTDIR;1305goto error_return;1306}13071308 lock->lk =xcalloc(1,sizeof(struct lock_file));13091310 lock->ref_name =xstrdup(refname);13111312if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1313 last_errno = errno;1314unable_to_lock_message(ref_file.buf, errno, err);1315goto error_return;1316}13171318if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1319 last_errno = errno;1320goto error_return;1321}1322goto out;13231324 error_return:1325unlock_ref(lock);1326 lock = NULL;13271328 out:1329strbuf_release(&ref_file);1330 errno = last_errno;1331return lock;1332}13331334/*1335 * Write an entry to the packed-refs file for the specified refname.1336 * If peeled is non-NULL, write it as the entry's peeled value.1337 */1338static voidwrite_packed_entry(FILE*fh,const char*refname,1339const unsigned char*sha1,1340const unsigned char*peeled)1341{1342fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1343if(peeled)1344fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1345}13461347/*1348 * Lock the packed-refs file for writing. Flags is passed to1349 * hold_lock_file_for_update(). Return 0 on success. On errors, set1350 * errno appropriately and return a nonzero value.1351 */1352static intlock_packed_refs(struct packed_ref_store *refs,int flags)1353{1354static int timeout_configured =0;1355static int timeout_value =1000;1356struct packed_ref_cache *packed_ref_cache;13571358packed_assert_main_repository(refs,"lock_packed_refs");13591360if(!timeout_configured) {1361git_config_get_int("core.packedrefstimeout", &timeout_value);1362 timeout_configured =1;1363}13641365if(hold_lock_file_for_update_timeout(1366&refs->lock,1367 refs->path,1368 flags, timeout_value) <0)1369return-1;13701371/*1372 * Now that we hold the `packed-refs` lock, make sure that our1373 * cache matches the current version of the file. Normally1374 * `get_packed_ref_cache()` does that for us, but that1375 * function assumes that when the file is locked, any existing1376 * cache is still valid. We've just locked the file, but it1377 * might have changed the moment *before* we locked it.1378 */1379validate_packed_ref_cache(refs);13801381 packed_ref_cache =get_packed_ref_cache(refs);1382/* Increment the reference count to prevent it from being freed: */1383acquire_packed_ref_cache(packed_ref_cache);1384return0;1385}13861387/*1388 * Write the current version of the packed refs cache from memory to1389 * disk. The packed-refs file must already be locked for writing (see1390 * lock_packed_refs()). Return zero on success. On errors, set errno1391 * and return a nonzero value1392 */1393static intcommit_packed_refs(struct packed_ref_store *refs)1394{1395struct packed_ref_cache *packed_ref_cache =1396get_packed_ref_cache(refs);1397int ok, error =0;1398int save_errno =0;1399FILE*out;1400struct ref_iterator *iter;14011402packed_assert_main_repository(refs,"commit_packed_refs");14031404if(!is_lock_file_locked(&refs->lock))1405die("BUG: packed-refs not locked");14061407 out =fdopen_lock_file(&refs->lock,"w");1408if(!out)1409die_errno("unable to fdopen packed-refs descriptor");14101411fprintf_or_die(out,"%s", PACKED_REFS_HEADER);14121413 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1414while((ok =ref_iterator_advance(iter)) == ITER_OK) {1415struct object_id peeled;1416int peel_error =ref_iterator_peel(iter, &peeled);14171418write_packed_entry(out, iter->refname, iter->oid->hash,1419 peel_error ? NULL : peeled.hash);1420}14211422if(ok != ITER_DONE)1423die("error while iterating over references");14241425if(commit_lock_file(&refs->lock)) {1426 save_errno = errno;1427 error = -1;1428}1429release_packed_ref_cache(packed_ref_cache);1430 errno = save_errno;1431return error;1432}14331434/*1435 * Rollback the lockfile for the packed-refs file, and discard the1436 * in-memory packed reference cache. (The packed-refs file will be1437 * read anew if it is needed again after this function is called.)1438 */1439static voidrollback_packed_refs(struct packed_ref_store *refs)1440{1441struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs);14421443packed_assert_main_repository(refs,"rollback_packed_refs");14441445if(!is_lock_file_locked(&refs->lock))1446die("BUG: packed-refs not locked");1447rollback_lock_file(&refs->lock);1448release_packed_ref_cache(packed_ref_cache);1449clear_packed_ref_cache(refs);1450}14511452struct ref_to_prune {1453struct ref_to_prune *next;1454unsigned char sha1[20];1455char name[FLEX_ARRAY];1456};14571458enum{1459 REMOVE_EMPTY_PARENTS_REF =0x01,1460 REMOVE_EMPTY_PARENTS_REFLOG =0x021461};14621463/*1464 * Remove empty parent directories associated with the specified1465 * reference and/or its reflog, but spare [logs/]refs/ and immediate1466 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1467 * REMOVE_EMPTY_PARENTS_REFLOG.1468 */1469static voidtry_remove_empty_parents(struct files_ref_store *refs,1470const char*refname,1471unsigned int flags)1472{1473struct strbuf buf = STRBUF_INIT;1474struct strbuf sb = STRBUF_INIT;1475char*p, *q;1476int i;14771478strbuf_addstr(&buf, refname);1479 p = buf.buf;1480for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1481while(*p && *p !='/')1482 p++;1483/* tolerate duplicate slashes; see check_refname_format() */1484while(*p =='/')1485 p++;1486}1487 q = buf.buf + buf.len;1488while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1489while(q > p && *q !='/')1490 q--;1491while(q > p && *(q-1) =='/')1492 q--;1493if(q == p)1494break;1495strbuf_setlen(&buf, q - buf.buf);14961497strbuf_reset(&sb);1498files_ref_path(refs, &sb, buf.buf);1499if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1500 flags &= ~REMOVE_EMPTY_PARENTS_REF;15011502strbuf_reset(&sb);1503files_reflog_path(refs, &sb, buf.buf);1504if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1505 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1506}1507strbuf_release(&buf);1508strbuf_release(&sb);1509}15101511/* make sure nobody touched the ref, and unlink */1512static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1513{1514struct ref_transaction *transaction;1515struct strbuf err = STRBUF_INIT;15161517if(check_refname_format(r->name,0))1518return;15191520 transaction =ref_store_transaction_begin(&refs->base, &err);1521if(!transaction ||1522ref_transaction_delete(transaction, r->name, r->sha1,1523 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1524ref_transaction_commit(transaction, &err)) {1525ref_transaction_free(transaction);1526error("%s", err.buf);1527strbuf_release(&err);1528return;1529}1530ref_transaction_free(transaction);1531strbuf_release(&err);1532}15331534static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1535{1536while(r) {1537prune_ref(refs, r);1538 r = r->next;1539}1540}15411542/*1543 * Return true if the specified reference should be packed.1544 */1545static intshould_pack_ref(const char*refname,1546const struct object_id *oid,unsigned int ref_flags,1547unsigned int pack_flags)1548{1549/* Do not pack per-worktree refs: */1550if(ref_type(refname) != REF_TYPE_NORMAL)1551return0;15521553/* Do not pack non-tags unless PACK_REFS_ALL is set: */1554if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1555return0;15561557/* Do not pack symbolic refs: */1558if(ref_flags & REF_ISSYMREF)1559return0;15601561/* Do not pack broken refs: */1562if(!ref_resolves_to_object(refname, oid, ref_flags))1563return0;15641565return1;1566}15671568static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1569{1570struct files_ref_store *refs =1571files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1572"pack_refs");1573struct ref_iterator *iter;1574int ok;1575struct ref_to_prune *refs_to_prune = NULL;15761577lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);15781579 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1580while((ok =ref_iterator_advance(iter)) == ITER_OK) {1581/*1582 * If the loose reference can be packed, add an entry1583 * in the packed ref cache. If the reference should be1584 * pruned, also add it to refs_to_prune.1585 */1586if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1587 flags))1588continue;15891590/*1591 * Create an entry in the packed-refs cache equivalent1592 * to the one from the loose ref cache, except that1593 * we don't copy the peeled status, because we want it1594 * to be re-peeled.1595 */1596add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);15971598/* Schedule the loose reference for pruning if requested. */1599if((flags & PACK_REFS_PRUNE)) {1600struct ref_to_prune *n;1601FLEX_ALLOC_STR(n, name, iter->refname);1602hashcpy(n->sha1, iter->oid->hash);1603 n->next = refs_to_prune;1604 refs_to_prune = n;1605}1606}1607if(ok != ITER_DONE)1608die("error while iterating over references");16091610if(commit_packed_refs(refs->packed_ref_store))1611die_errno("unable to overwrite old ref-pack file");16121613prune_refs(refs, refs_to_prune);1614return0;1615}16161617/*1618 * Rewrite the packed-refs file, omitting any refs listed in1619 * 'refnames'. On error, leave packed-refs unchanged, write an error1620 * message to 'err', and return a nonzero value.1621 *1622 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1623 */1624static intrepack_without_refs(struct packed_ref_store *refs,1625struct string_list *refnames,struct strbuf *err)1626{1627struct ref_dir *packed;1628struct string_list_item *refname;1629int ret, needs_repacking =0, removed =0;16301631packed_assert_main_repository(refs,"repack_without_refs");1632assert(err);16331634/* Look for a packed ref */1635for_each_string_list_item(refname, refnames) {1636if(get_packed_ref(refs, refname->string)) {1637 needs_repacking =1;1638break;1639}1640}16411642/* Avoid locking if we have nothing to do */1643if(!needs_repacking)1644return0;/* no refname exists in packed refs */16451646if(lock_packed_refs(refs,0)) {1647unable_to_lock_message(refs->path, errno, err);1648return-1;1649}1650 packed =get_packed_refs(refs);16511652/* Remove refnames from the cache */1653for_each_string_list_item(refname, refnames)1654if(remove_entry_from_dir(packed, refname->string) != -1)1655 removed =1;1656if(!removed) {1657/*1658 * All packed entries disappeared while we were1659 * acquiring the lock.1660 */1661rollback_packed_refs(refs);1662return0;1663}16641665/* Write what remains */1666 ret =commit_packed_refs(refs);1667if(ret)1668strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1669strerror(errno));1670return ret;1671}16721673static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1674struct string_list *refnames,unsigned int flags)1675{1676struct files_ref_store *refs =1677files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1678struct strbuf err = STRBUF_INIT;1679int i, result =0;16801681if(!refnames->nr)1682return0;16831684 result =repack_without_refs(refs->packed_ref_store, refnames, &err);1685if(result) {1686/*1687 * If we failed to rewrite the packed-refs file, then1688 * it is unsafe to try to remove loose refs, because1689 * doing so might expose an obsolete packed value for1690 * a reference that might even point at an object that1691 * has been garbage collected.1692 */1693if(refnames->nr ==1)1694error(_("could not delete reference%s:%s"),1695 refnames->items[0].string, err.buf);1696else1697error(_("could not delete references:%s"), err.buf);16981699goto out;1700}17011702for(i =0; i < refnames->nr; i++) {1703const char*refname = refnames->items[i].string;17041705if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1706 result |=error(_("could not remove reference%s"), refname);1707}17081709out:1710strbuf_release(&err);1711return result;1712}17131714/*1715 * People using contrib's git-new-workdir have .git/logs/refs ->1716 * /some/other/path/.git/logs/refs, and that may live on another device.1717 *1718 * IOW, to avoid cross device rename errors, the temporary renamed log must1719 * live into logs/refs.1720 */1721#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"17221723struct rename_cb {1724const char*tmp_renamed_log;1725int true_errno;1726};17271728static intrename_tmp_log_callback(const char*path,void*cb_data)1729{1730struct rename_cb *cb = cb_data;17311732if(rename(cb->tmp_renamed_log, path)) {1733/*1734 * rename(a, b) when b is an existing directory ought1735 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1736 * Sheesh. Record the true errno for error reporting,1737 * but report EISDIR to raceproof_create_file() so1738 * that it knows to retry.1739 */1740 cb->true_errno = errno;1741if(errno == ENOTDIR)1742 errno = EISDIR;1743return-1;1744}else{1745return0;1746}1747}17481749static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1750{1751struct strbuf path = STRBUF_INIT;1752struct strbuf tmp = STRBUF_INIT;1753struct rename_cb cb;1754int ret;17551756files_reflog_path(refs, &path, newrefname);1757files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1758 cb.tmp_renamed_log = tmp.buf;1759 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1760if(ret) {1761if(errno == EISDIR)1762error("directory not empty:%s", path.buf);1763else1764error("unable to move logfile%sto%s:%s",1765 tmp.buf, path.buf,1766strerror(cb.true_errno));1767}17681769strbuf_release(&path);1770strbuf_release(&tmp);1771return ret;1772}17731774static intwrite_ref_to_lockfile(struct ref_lock *lock,1775const struct object_id *oid,struct strbuf *err);1776static intcommit_ref_update(struct files_ref_store *refs,1777struct ref_lock *lock,1778const struct object_id *oid,const char*logmsg,1779struct strbuf *err);17801781static intfiles_rename_ref(struct ref_store *ref_store,1782const char*oldrefname,const char*newrefname,1783const char*logmsg)1784{1785struct files_ref_store *refs =1786files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1787struct object_id oid, orig_oid;1788int flag =0, logmoved =0;1789struct ref_lock *lock;1790struct stat loginfo;1791struct strbuf sb_oldref = STRBUF_INIT;1792struct strbuf sb_newref = STRBUF_INIT;1793struct strbuf tmp_renamed_log = STRBUF_INIT;1794int log, ret;1795struct strbuf err = STRBUF_INIT;17961797files_reflog_path(refs, &sb_oldref, oldrefname);1798files_reflog_path(refs, &sb_newref, newrefname);1799files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);18001801 log = !lstat(sb_oldref.buf, &loginfo);1802if(log &&S_ISLNK(loginfo.st_mode)) {1803 ret =error("reflog for%sis a symlink", oldrefname);1804goto out;1805}18061807if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1808 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1809 orig_oid.hash, &flag)) {1810 ret =error("refname%snot found", oldrefname);1811goto out;1812}18131814if(flag & REF_ISSYMREF) {1815 ret =error("refname%sis a symbolic ref, renaming it is not supported",1816 oldrefname);1817goto out;1818}1819if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1820 ret =1;1821goto out;1822}18231824if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1825 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1826 oldrefname,strerror(errno));1827goto out;1828}18291830if(refs_delete_ref(&refs->base, logmsg, oldrefname,1831 orig_oid.hash, REF_NODEREF)) {1832error("unable to delete old%s", oldrefname);1833goto rollback;1834}18351836/*1837 * Since we are doing a shallow lookup, oid is not the1838 * correct value to pass to delete_ref as old_oid. But that1839 * doesn't matter, because an old_oid check wouldn't add to1840 * the safety anyway; we want to delete the reference whatever1841 * its current value.1842 */1843if(!refs_read_ref_full(&refs->base, newrefname,1844 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1845 oid.hash, NULL) &&1846refs_delete_ref(&refs->base, NULL, newrefname,1847 NULL, REF_NODEREF)) {1848if(errno == EISDIR) {1849struct strbuf path = STRBUF_INIT;1850int result;18511852files_ref_path(refs, &path, newrefname);1853 result =remove_empty_directories(&path);1854strbuf_release(&path);18551856if(result) {1857error("Directory not empty:%s", newrefname);1858goto rollback;1859}1860}else{1861error("unable to delete existing%s", newrefname);1862goto rollback;1863}1864}18651866if(log &&rename_tmp_log(refs, newrefname))1867goto rollback;18681869 logmoved = log;18701871 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1872 REF_NODEREF, NULL, &err);1873if(!lock) {1874error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1875strbuf_release(&err);1876goto rollback;1877}1878oidcpy(&lock->old_oid, &orig_oid);18791880if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1881commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1882error("unable to write current sha1 into%s:%s", newrefname, err.buf);1883strbuf_release(&err);1884goto rollback;1885}18861887 ret =0;1888goto out;18891890 rollback:1891 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1892 REF_NODEREF, NULL, &err);1893if(!lock) {1894error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1895strbuf_release(&err);1896goto rollbacklog;1897}18981899 flag = log_all_ref_updates;1900 log_all_ref_updates = LOG_REFS_NONE;1901if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1902commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1903error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1904strbuf_release(&err);1905}1906 log_all_ref_updates = flag;19071908 rollbacklog:1909if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1910error("unable to restore logfile%sfrom%s:%s",1911 oldrefname, newrefname,strerror(errno));1912if(!logmoved && log &&1913rename(tmp_renamed_log.buf, sb_oldref.buf))1914error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1915 oldrefname,strerror(errno));1916 ret =1;1917 out:1918strbuf_release(&sb_newref);1919strbuf_release(&sb_oldref);1920strbuf_release(&tmp_renamed_log);19211922return ret;1923}19241925static intclose_ref(struct ref_lock *lock)1926{1927if(close_lock_file(lock->lk))1928return-1;1929return0;1930}19311932static intcommit_ref(struct ref_lock *lock)1933{1934char*path =get_locked_file_path(lock->lk);1935struct stat st;19361937if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1938/*1939 * There is a directory at the path we want to rename1940 * the lockfile to. Hopefully it is empty; try to1941 * delete it.1942 */1943size_t len =strlen(path);1944struct strbuf sb_path = STRBUF_INIT;19451946strbuf_attach(&sb_path, path, len, len);19471948/*1949 * If this fails, commit_lock_file() will also fail1950 * and will report the problem.1951 */1952remove_empty_directories(&sb_path);1953strbuf_release(&sb_path);1954}else{1955free(path);1956}19571958if(commit_lock_file(lock->lk))1959return-1;1960return0;1961}19621963static intopen_or_create_logfile(const char*path,void*cb)1964{1965int*fd = cb;19661967*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1968return(*fd <0) ? -1:0;1969}19701971/*1972 * Create a reflog for a ref. If force_create = 0, only create the1973 * reflog for certain refs (those for which should_autocreate_reflog1974 * returns non-zero). Otherwise, create it regardless of the reference1975 * name. If the logfile already existed or was created, return 0 and1976 * set *logfd to the file descriptor opened for appending to the file.1977 * If no logfile exists and we decided not to create one, return 0 and1978 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1979 * return -1.1980 */1981static intlog_ref_setup(struct files_ref_store *refs,1982const char*refname,int force_create,1983int*logfd,struct strbuf *err)1984{1985struct strbuf logfile_sb = STRBUF_INIT;1986char*logfile;19871988files_reflog_path(refs, &logfile_sb, refname);1989 logfile =strbuf_detach(&logfile_sb, NULL);19901991if(force_create ||should_autocreate_reflog(refname)) {1992if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1993if(errno == ENOENT)1994strbuf_addf(err,"unable to create directory for '%s': "1995"%s", logfile,strerror(errno));1996else if(errno == EISDIR)1997strbuf_addf(err,"there are still logs under '%s'",1998 logfile);1999else2000strbuf_addf(err,"unable to append to '%s':%s",2001 logfile,strerror(errno));20022003goto error;2004}2005}else{2006*logfd =open(logfile, O_APPEND | O_WRONLY,0666);2007if(*logfd <0) {2008if(errno == ENOENT || errno == EISDIR) {2009/*2010 * The logfile doesn't already exist,2011 * but that is not an error; it only2012 * means that we won't write log2013 * entries to it.2014 */2015;2016}else{2017strbuf_addf(err,"unable to append to '%s':%s",2018 logfile,strerror(errno));2019goto error;2020}2021}2022}20232024if(*logfd >=0)2025adjust_shared_perm(logfile);20262027free(logfile);2028return0;20292030error:2031free(logfile);2032return-1;2033}20342035static intfiles_create_reflog(struct ref_store *ref_store,2036const char*refname,int force_create,2037struct strbuf *err)2038{2039struct files_ref_store *refs =2040files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2041int fd;20422043if(log_ref_setup(refs, refname, force_create, &fd, err))2044return-1;20452046if(fd >=0)2047close(fd);20482049return0;2050}20512052static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2053const struct object_id *new_oid,2054const char*committer,const char*msg)2055{2056int msglen, written;2057unsigned maxlen, len;2058char*logrec;20592060 msglen = msg ?strlen(msg) :0;2061 maxlen =strlen(committer) + msglen +100;2062 logrec =xmalloc(maxlen);2063 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2064oid_to_hex(old_oid),2065oid_to_hex(new_oid),2066 committer);2067if(msglen)2068 len +=copy_reflog_msg(logrec + len -1, msg) -1;20692070 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2071free(logrec);2072if(written != len)2073return-1;20742075return0;2076}20772078static intfiles_log_ref_write(struct files_ref_store *refs,2079const char*refname,const struct object_id *old_oid,2080const struct object_id *new_oid,const char*msg,2081int flags,struct strbuf *err)2082{2083int logfd, result;20842085if(log_all_ref_updates == LOG_REFS_UNSET)2086 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20872088 result =log_ref_setup(refs, refname,2089 flags & REF_FORCE_CREATE_REFLOG,2090&logfd, err);20912092if(result)2093return result;20942095if(logfd <0)2096return0;2097 result =log_ref_write_fd(logfd, old_oid, new_oid,2098git_committer_info(0), msg);2099if(result) {2100struct strbuf sb = STRBUF_INIT;2101int save_errno = errno;21022103files_reflog_path(refs, &sb, refname);2104strbuf_addf(err,"unable to append to '%s':%s",2105 sb.buf,strerror(save_errno));2106strbuf_release(&sb);2107close(logfd);2108return-1;2109}2110if(close(logfd)) {2111struct strbuf sb = STRBUF_INIT;2112int save_errno = errno;21132114files_reflog_path(refs, &sb, refname);2115strbuf_addf(err,"unable to append to '%s':%s",2116 sb.buf,strerror(save_errno));2117strbuf_release(&sb);2118return-1;2119}2120return0;2121}21222123/*2124 * Write sha1 into the open lockfile, then close the lockfile. On2125 * errors, rollback the lockfile, fill in *err and2126 * return -1.2127 */2128static intwrite_ref_to_lockfile(struct ref_lock *lock,2129const struct object_id *oid,struct strbuf *err)2130{2131static char term ='\n';2132struct object *o;2133int fd;21342135 o =parse_object(oid);2136if(!o) {2137strbuf_addf(err,2138"trying to write ref '%s' with nonexistent object%s",2139 lock->ref_name,oid_to_hex(oid));2140unlock_ref(lock);2141return-1;2142}2143if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2144strbuf_addf(err,2145"trying to write non-commit object%sto branch '%s'",2146oid_to_hex(oid), lock->ref_name);2147unlock_ref(lock);2148return-1;2149}2150 fd =get_lock_file_fd(lock->lk);2151if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2152write_in_full(fd, &term,1) !=1||2153close_ref(lock) <0) {2154strbuf_addf(err,2155"couldn't write '%s'",get_lock_file_path(lock->lk));2156unlock_ref(lock);2157return-1;2158}2159return0;2160}21612162/*2163 * Commit a change to a loose reference that has already been written2164 * to the loose reference lockfile. Also update the reflogs if2165 * necessary, using the specified lockmsg (which can be NULL).2166 */2167static intcommit_ref_update(struct files_ref_store *refs,2168struct ref_lock *lock,2169const struct object_id *oid,const char*logmsg,2170struct strbuf *err)2171{2172files_assert_main_repository(refs,"commit_ref_update");21732174clear_loose_ref_cache(refs);2175if(files_log_ref_write(refs, lock->ref_name,2176&lock->old_oid, oid,2177 logmsg,0, err)) {2178char*old_msg =strbuf_detach(err, NULL);2179strbuf_addf(err,"cannot update the ref '%s':%s",2180 lock->ref_name, old_msg);2181free(old_msg);2182unlock_ref(lock);2183return-1;2184}21852186if(strcmp(lock->ref_name,"HEAD") !=0) {2187/*2188 * Special hack: If a branch is updated directly and HEAD2189 * points to it (may happen on the remote side of a push2190 * for example) then logically the HEAD reflog should be2191 * updated too.2192 * A generic solution implies reverse symref information,2193 * but finding all symrefs pointing to the given branch2194 * would be rather costly for this rare event (the direct2195 * update of a branch) to be worth it. So let's cheat and2196 * check with HEAD only which should cover 99% of all usage2197 * scenarios (even 100% of the default ones).2198 */2199struct object_id head_oid;2200int head_flag;2201const char*head_ref;22022203 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2204 RESOLVE_REF_READING,2205 head_oid.hash, &head_flag);2206if(head_ref && (head_flag & REF_ISSYMREF) &&2207!strcmp(head_ref, lock->ref_name)) {2208struct strbuf log_err = STRBUF_INIT;2209if(files_log_ref_write(refs,"HEAD",2210&lock->old_oid, oid,2211 logmsg,0, &log_err)) {2212error("%s", log_err.buf);2213strbuf_release(&log_err);2214}2215}2216}22172218if(commit_ref(lock)) {2219strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2220unlock_ref(lock);2221return-1;2222}22232224unlock_ref(lock);2225return0;2226}22272228static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2229{2230int ret = -1;2231#ifndef NO_SYMLINK_HEAD2232char*ref_path =get_locked_file_path(lock->lk);2233unlink(ref_path);2234 ret =symlink(target, ref_path);2235free(ref_path);22362237if(ret)2238fprintf(stderr,"no symlink - falling back to symbolic ref\n");2239#endif2240return ret;2241}22422243static voidupdate_symref_reflog(struct files_ref_store *refs,2244struct ref_lock *lock,const char*refname,2245const char*target,const char*logmsg)2246{2247struct strbuf err = STRBUF_INIT;2248struct object_id new_oid;2249if(logmsg &&2250!refs_read_ref_full(&refs->base, target,2251 RESOLVE_REF_READING, new_oid.hash, NULL) &&2252files_log_ref_write(refs, refname, &lock->old_oid,2253&new_oid, logmsg,0, &err)) {2254error("%s", err.buf);2255strbuf_release(&err);2256}2257}22582259static intcreate_symref_locked(struct files_ref_store *refs,2260struct ref_lock *lock,const char*refname,2261const char*target,const char*logmsg)2262{2263if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2264update_symref_reflog(refs, lock, refname, target, logmsg);2265return0;2266}22672268if(!fdopen_lock_file(lock->lk,"w"))2269returnerror("unable to fdopen%s:%s",2270 lock->lk->tempfile.filename.buf,strerror(errno));22712272update_symref_reflog(refs, lock, refname, target, logmsg);22732274/* no error check; commit_ref will check ferror */2275fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2276if(commit_ref(lock) <0)2277returnerror("unable to write symref for%s:%s", refname,2278strerror(errno));2279return0;2280}22812282static intfiles_create_symref(struct ref_store *ref_store,2283const char*refname,const char*target,2284const char*logmsg)2285{2286struct files_ref_store *refs =2287files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2288struct strbuf err = STRBUF_INIT;2289struct ref_lock *lock;2290int ret;22912292 lock =lock_ref_sha1_basic(refs, refname, NULL,2293 NULL, NULL, REF_NODEREF, NULL,2294&err);2295if(!lock) {2296error("%s", err.buf);2297strbuf_release(&err);2298return-1;2299}23002301 ret =create_symref_locked(refs, lock, refname, target, logmsg);2302unlock_ref(lock);2303return ret;2304}23052306static intfiles_reflog_exists(struct ref_store *ref_store,2307const char*refname)2308{2309struct files_ref_store *refs =2310files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2311struct strbuf sb = STRBUF_INIT;2312struct stat st;2313int ret;23142315files_reflog_path(refs, &sb, refname);2316 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2317strbuf_release(&sb);2318return ret;2319}23202321static intfiles_delete_reflog(struct ref_store *ref_store,2322const char*refname)2323{2324struct files_ref_store *refs =2325files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2326struct strbuf sb = STRBUF_INIT;2327int ret;23282329files_reflog_path(refs, &sb, refname);2330 ret =remove_path(sb.buf);2331strbuf_release(&sb);2332return ret;2333}23342335static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2336{2337struct object_id ooid, noid;2338char*email_end, *message;2339 timestamp_t timestamp;2340int tz;2341const char*p = sb->buf;23422343/* old SP new SP name <email> SP time TAB msg LF */2344if(!sb->len || sb->buf[sb->len -1] !='\n'||2345parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2346parse_oid_hex(p, &noid, &p) || *p++ !=' '||2347!(email_end =strchr(p,'>')) ||2348 email_end[1] !=' '||2349!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2350!message || message[0] !=' '||2351(message[1] !='+'&& message[1] !='-') ||2352!isdigit(message[2]) || !isdigit(message[3]) ||2353!isdigit(message[4]) || !isdigit(message[5]))2354return0;/* corrupt? */2355 email_end[1] ='\0';2356 tz =strtol(message +1, NULL,10);2357if(message[6] !='\t')2358 message +=6;2359else2360 message +=7;2361returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2362}23632364static char*find_beginning_of_line(char*bob,char*scan)2365{2366while(bob < scan && *(--scan) !='\n')2367;/* keep scanning backwards */2368/*2369 * Return either beginning of the buffer, or LF at the end of2370 * the previous line.2371 */2372return scan;2373}23742375static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2376const char*refname,2377 each_reflog_ent_fn fn,2378void*cb_data)2379{2380struct files_ref_store *refs =2381files_downcast(ref_store, REF_STORE_READ,2382"for_each_reflog_ent_reverse");2383struct strbuf sb = STRBUF_INIT;2384FILE*logfp;2385long pos;2386int ret =0, at_tail =1;23872388files_reflog_path(refs, &sb, refname);2389 logfp =fopen(sb.buf,"r");2390strbuf_release(&sb);2391if(!logfp)2392return-1;23932394/* Jump to the end */2395if(fseek(logfp,0, SEEK_END) <0)2396 ret =error("cannot seek back reflog for%s:%s",2397 refname,strerror(errno));2398 pos =ftell(logfp);2399while(!ret &&0< pos) {2400int cnt;2401size_t nread;2402char buf[BUFSIZ];2403char*endp, *scanp;24042405/* Fill next block from the end */2406 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2407if(fseek(logfp, pos - cnt, SEEK_SET)) {2408 ret =error("cannot seek back reflog for%s:%s",2409 refname,strerror(errno));2410break;2411}2412 nread =fread(buf, cnt,1, logfp);2413if(nread !=1) {2414 ret =error("cannot read%dbytes from reflog for%s:%s",2415 cnt, refname,strerror(errno));2416break;2417}2418 pos -= cnt;24192420 scanp = endp = buf + cnt;2421if(at_tail && scanp[-1] =='\n')2422/* Looking at the final LF at the end of the file */2423 scanp--;2424 at_tail =0;24252426while(buf < scanp) {2427/*2428 * terminating LF of the previous line, or the beginning2429 * of the buffer.2430 */2431char*bp;24322433 bp =find_beginning_of_line(buf, scanp);24342435if(*bp =='\n') {2436/*2437 * The newline is the end of the previous line,2438 * so we know we have complete line starting2439 * at (bp + 1). Prefix it onto any prior data2440 * we collected for the line and process it.2441 */2442strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2443 scanp = bp;2444 endp = bp +1;2445 ret =show_one_reflog_ent(&sb, fn, cb_data);2446strbuf_reset(&sb);2447if(ret)2448break;2449}else if(!pos) {2450/*2451 * We are at the start of the buffer, and the2452 * start of the file; there is no previous2453 * line, and we have everything for this one.2454 * Process it, and we can end the loop.2455 */2456strbuf_splice(&sb,0,0, buf, endp - buf);2457 ret =show_one_reflog_ent(&sb, fn, cb_data);2458strbuf_reset(&sb);2459break;2460}24612462if(bp == buf) {2463/*2464 * We are at the start of the buffer, and there2465 * is more file to read backwards. Which means2466 * we are in the middle of a line. Note that we2467 * may get here even if *bp was a newline; that2468 * just means we are at the exact end of the2469 * previous line, rather than some spot in the2470 * middle.2471 *2472 * Save away what we have to be combined with2473 * the data from the next read.2474 */2475strbuf_splice(&sb,0,0, buf, endp - buf);2476break;2477}2478}24792480}2481if(!ret && sb.len)2482die("BUG: reverse reflog parser had leftover data");24832484fclose(logfp);2485strbuf_release(&sb);2486return ret;2487}24882489static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2490const char*refname,2491 each_reflog_ent_fn fn,void*cb_data)2492{2493struct files_ref_store *refs =2494files_downcast(ref_store, REF_STORE_READ,2495"for_each_reflog_ent");2496FILE*logfp;2497struct strbuf sb = STRBUF_INIT;2498int ret =0;24992500files_reflog_path(refs, &sb, refname);2501 logfp =fopen(sb.buf,"r");2502strbuf_release(&sb);2503if(!logfp)2504return-1;25052506while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2507 ret =show_one_reflog_ent(&sb, fn, cb_data);2508fclose(logfp);2509strbuf_release(&sb);2510return ret;2511}25122513struct files_reflog_iterator {2514struct ref_iterator base;25152516struct ref_store *ref_store;2517struct dir_iterator *dir_iterator;2518struct object_id oid;2519};25202521static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2522{2523struct files_reflog_iterator *iter =2524(struct files_reflog_iterator *)ref_iterator;2525struct dir_iterator *diter = iter->dir_iterator;2526int ok;25272528while((ok =dir_iterator_advance(diter)) == ITER_OK) {2529int flags;25302531if(!S_ISREG(diter->st.st_mode))2532continue;2533if(diter->basename[0] =='.')2534continue;2535if(ends_with(diter->basename,".lock"))2536continue;25372538if(refs_read_ref_full(iter->ref_store,2539 diter->relative_path,0,2540 iter->oid.hash, &flags)) {2541error("bad ref for%s", diter->path.buf);2542continue;2543}25442545 iter->base.refname = diter->relative_path;2546 iter->base.oid = &iter->oid;2547 iter->base.flags = flags;2548return ITER_OK;2549}25502551 iter->dir_iterator = NULL;2552if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2553 ok = ITER_ERROR;2554return ok;2555}25562557static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2558struct object_id *peeled)2559{2560die("BUG: ref_iterator_peel() called for reflog_iterator");2561}25622563static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2564{2565struct files_reflog_iterator *iter =2566(struct files_reflog_iterator *)ref_iterator;2567int ok = ITER_DONE;25682569if(iter->dir_iterator)2570 ok =dir_iterator_abort(iter->dir_iterator);25712572base_ref_iterator_free(ref_iterator);2573return ok;2574}25752576static struct ref_iterator_vtable files_reflog_iterator_vtable = {2577 files_reflog_iterator_advance,2578 files_reflog_iterator_peel,2579 files_reflog_iterator_abort2580};25812582static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2583{2584struct files_ref_store *refs =2585files_downcast(ref_store, REF_STORE_READ,2586"reflog_iterator_begin");2587struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2588struct ref_iterator *ref_iterator = &iter->base;2589struct strbuf sb = STRBUF_INIT;25902591base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2592files_reflog_path(refs, &sb, NULL);2593 iter->dir_iterator =dir_iterator_begin(sb.buf);2594 iter->ref_store = ref_store;2595strbuf_release(&sb);2596return ref_iterator;2597}25982599/*2600 * If update is a direct update of head_ref (the reference pointed to2601 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2602 */2603static intsplit_head_update(struct ref_update *update,2604struct ref_transaction *transaction,2605const char*head_ref,2606struct string_list *affected_refnames,2607struct strbuf *err)2608{2609struct string_list_item *item;2610struct ref_update *new_update;26112612if((update->flags & REF_LOG_ONLY) ||2613(update->flags & REF_ISPRUNING) ||2614(update->flags & REF_UPDATE_VIA_HEAD))2615return0;26162617if(strcmp(update->refname, head_ref))2618return0;26192620/*2621 * First make sure that HEAD is not already in the2622 * transaction. This insertion is O(N) in the transaction2623 * size, but it happens at most once per transaction.2624 */2625 item =string_list_insert(affected_refnames,"HEAD");2626if(item->util) {2627/* An entry already existed */2628strbuf_addf(err,2629"multiple updates for 'HEAD' (including one "2630"via its referent '%s') are not allowed",2631 update->refname);2632return TRANSACTION_NAME_CONFLICT;2633}26342635 new_update =ref_transaction_add_update(2636 transaction,"HEAD",2637 update->flags | REF_LOG_ONLY | REF_NODEREF,2638 update->new_oid.hash, update->old_oid.hash,2639 update->msg);26402641 item->util = new_update;26422643return0;2644}26452646/*2647 * update is for a symref that points at referent and doesn't have2648 * REF_NODEREF set. Split it into two updates:2649 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2650 * - A new, separate update for the referent reference2651 * Note that the new update will itself be subject to splitting when2652 * the iteration gets to it.2653 */2654static intsplit_symref_update(struct files_ref_store *refs,2655struct ref_update *update,2656const char*referent,2657struct ref_transaction *transaction,2658struct string_list *affected_refnames,2659struct strbuf *err)2660{2661struct string_list_item *item;2662struct ref_update *new_update;2663unsigned int new_flags;26642665/*2666 * First make sure that referent is not already in the2667 * transaction. This insertion is O(N) in the transaction2668 * size, but it happens at most once per symref in a2669 * transaction.2670 */2671 item =string_list_insert(affected_refnames, referent);2672if(item->util) {2673/* An entry already existed */2674strbuf_addf(err,2675"multiple updates for '%s' (including one "2676"via symref '%s') are not allowed",2677 referent, update->refname);2678return TRANSACTION_NAME_CONFLICT;2679}26802681 new_flags = update->flags;2682if(!strcmp(update->refname,"HEAD")) {2683/*2684 * Record that the new update came via HEAD, so that2685 * when we process it, split_head_update() doesn't try2686 * to add another reflog update for HEAD. Note that2687 * this bit will be propagated if the new_update2688 * itself needs to be split.2689 */2690 new_flags |= REF_UPDATE_VIA_HEAD;2691}26922693 new_update =ref_transaction_add_update(2694 transaction, referent, new_flags,2695 update->new_oid.hash, update->old_oid.hash,2696 update->msg);26972698 new_update->parent_update = update;26992700/*2701 * Change the symbolic ref update to log only. Also, it2702 * doesn't need to check its old SHA-1 value, as that will be2703 * done when new_update is processed.2704 */2705 update->flags |= REF_LOG_ONLY | REF_NODEREF;2706 update->flags &= ~REF_HAVE_OLD;27072708 item->util = new_update;27092710return0;2711}27122713/*2714 * Return the refname under which update was originally requested.2715 */2716static const char*original_update_refname(struct ref_update *update)2717{2718while(update->parent_update)2719 update = update->parent_update;27202721return update->refname;2722}27232724/*2725 * Check whether the REF_HAVE_OLD and old_oid values stored in update2726 * are consistent with oid, which is the reference's current value. If2727 * everything is OK, return 0; otherwise, write an error message to2728 * err and return -1.2729 */2730static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2731struct strbuf *err)2732{2733if(!(update->flags & REF_HAVE_OLD) ||2734!oidcmp(oid, &update->old_oid))2735return0;27362737if(is_null_oid(&update->old_oid))2738strbuf_addf(err,"cannot lock ref '%s': "2739"reference already exists",2740original_update_refname(update));2741else if(is_null_oid(oid))2742strbuf_addf(err,"cannot lock ref '%s': "2743"reference is missing but expected%s",2744original_update_refname(update),2745oid_to_hex(&update->old_oid));2746else2747strbuf_addf(err,"cannot lock ref '%s': "2748"is at%sbut expected%s",2749original_update_refname(update),2750oid_to_hex(oid),2751oid_to_hex(&update->old_oid));27522753return-1;2754}27552756/*2757 * Prepare for carrying out update:2758 * - Lock the reference referred to by update.2759 * - Read the reference under lock.2760 * - Check that its old SHA-1 value (if specified) is correct, and in2761 * any case record it in update->lock->old_oid for later use when2762 * writing the reflog.2763 * - If it is a symref update without REF_NODEREF, split it up into a2764 * REF_LOG_ONLY update of the symref and add a separate update for2765 * the referent to transaction.2766 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2767 * update of HEAD.2768 */2769static intlock_ref_for_update(struct files_ref_store *refs,2770struct ref_update *update,2771struct ref_transaction *transaction,2772const char*head_ref,2773struct string_list *affected_refnames,2774struct strbuf *err)2775{2776struct strbuf referent = STRBUF_INIT;2777int mustexist = (update->flags & REF_HAVE_OLD) &&2778!is_null_oid(&update->old_oid);2779int ret;2780struct ref_lock *lock;27812782files_assert_main_repository(refs,"lock_ref_for_update");27832784if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2785 update->flags |= REF_DELETING;27862787if(head_ref) {2788 ret =split_head_update(update, transaction, head_ref,2789 affected_refnames, err);2790if(ret)2791return ret;2792}27932794 ret =lock_raw_ref(refs, update->refname, mustexist,2795 affected_refnames, NULL,2796&lock, &referent,2797&update->type, err);2798if(ret) {2799char*reason;28002801 reason =strbuf_detach(err, NULL);2802strbuf_addf(err,"cannot lock ref '%s':%s",2803original_update_refname(update), reason);2804free(reason);2805return ret;2806}28072808 update->backend_data = lock;28092810if(update->type & REF_ISSYMREF) {2811if(update->flags & REF_NODEREF) {2812/*2813 * We won't be reading the referent as part of2814 * the transaction, so we have to read it here2815 * to record and possibly check old_sha1:2816 */2817if(refs_read_ref_full(&refs->base,2818 referent.buf,0,2819 lock->old_oid.hash, NULL)) {2820if(update->flags & REF_HAVE_OLD) {2821strbuf_addf(err,"cannot lock ref '%s': "2822"error reading reference",2823original_update_refname(update));2824return-1;2825}2826}else if(check_old_oid(update, &lock->old_oid, err)) {2827return TRANSACTION_GENERIC_ERROR;2828}2829}else{2830/*2831 * Create a new update for the reference this2832 * symref is pointing at. Also, we will record2833 * and verify old_sha1 for this update as part2834 * of processing the split-off update, so we2835 * don't have to do it here.2836 */2837 ret =split_symref_update(refs, update,2838 referent.buf, transaction,2839 affected_refnames, err);2840if(ret)2841return ret;2842}2843}else{2844struct ref_update *parent_update;28452846if(check_old_oid(update, &lock->old_oid, err))2847return TRANSACTION_GENERIC_ERROR;28482849/*2850 * If this update is happening indirectly because of a2851 * symref update, record the old SHA-1 in the parent2852 * update:2853 */2854for(parent_update = update->parent_update;2855 parent_update;2856 parent_update = parent_update->parent_update) {2857struct ref_lock *parent_lock = parent_update->backend_data;2858oidcpy(&parent_lock->old_oid, &lock->old_oid);2859}2860}28612862if((update->flags & REF_HAVE_NEW) &&2863!(update->flags & REF_DELETING) &&2864!(update->flags & REF_LOG_ONLY)) {2865if(!(update->type & REF_ISSYMREF) &&2866!oidcmp(&lock->old_oid, &update->new_oid)) {2867/*2868 * The reference already has the desired2869 * value, so we don't need to write it.2870 */2871}else if(write_ref_to_lockfile(lock, &update->new_oid,2872 err)) {2873char*write_err =strbuf_detach(err, NULL);28742875/*2876 * The lock was freed upon failure of2877 * write_ref_to_lockfile():2878 */2879 update->backend_data = NULL;2880strbuf_addf(err,2881"cannot update ref '%s':%s",2882 update->refname, write_err);2883free(write_err);2884return TRANSACTION_GENERIC_ERROR;2885}else{2886 update->flags |= REF_NEEDS_COMMIT;2887}2888}2889if(!(update->flags & REF_NEEDS_COMMIT)) {2890/*2891 * We didn't call write_ref_to_lockfile(), so2892 * the lockfile is still open. Close it to2893 * free up the file descriptor:2894 */2895if(close_ref(lock)) {2896strbuf_addf(err,"couldn't close '%s.lock'",2897 update->refname);2898return TRANSACTION_GENERIC_ERROR;2899}2900}2901return0;2902}29032904/*2905 * Unlock any references in `transaction` that are still locked, and2906 * mark the transaction closed.2907 */2908static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2909{2910size_t i;29112912for(i =0; i < transaction->nr; i++) {2913struct ref_update *update = transaction->updates[i];2914struct ref_lock *lock = update->backend_data;29152916if(lock) {2917unlock_ref(lock);2918 update->backend_data = NULL;2919}2920}29212922 transaction->state = REF_TRANSACTION_CLOSED;2923}29242925static intfiles_transaction_prepare(struct ref_store *ref_store,2926struct ref_transaction *transaction,2927struct strbuf *err)2928{2929struct files_ref_store *refs =2930files_downcast(ref_store, REF_STORE_WRITE,2931"ref_transaction_prepare");2932size_t i;2933int ret =0;2934struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2935char*head_ref = NULL;2936int head_type;2937struct object_id head_oid;29382939assert(err);29402941if(!transaction->nr)2942goto cleanup;29432944/*2945 * Fail if a refname appears more than once in the2946 * transaction. (If we end up splitting up any updates using2947 * split_symref_update() or split_head_update(), those2948 * functions will check that the new updates don't have the2949 * same refname as any existing ones.)2950 */2951for(i =0; i < transaction->nr; i++) {2952struct ref_update *update = transaction->updates[i];2953struct string_list_item *item =2954string_list_append(&affected_refnames, update->refname);29552956/*2957 * We store a pointer to update in item->util, but at2958 * the moment we never use the value of this field2959 * except to check whether it is non-NULL.2960 */2961 item->util = update;2962}2963string_list_sort(&affected_refnames);2964if(ref_update_reject_duplicates(&affected_refnames, err)) {2965 ret = TRANSACTION_GENERIC_ERROR;2966goto cleanup;2967}29682969/*2970 * Special hack: If a branch is updated directly and HEAD2971 * points to it (may happen on the remote side of a push2972 * for example) then logically the HEAD reflog should be2973 * updated too.2974 *2975 * A generic solution would require reverse symref lookups,2976 * but finding all symrefs pointing to a given branch would be2977 * rather costly for this rare event (the direct update of a2978 * branch) to be worth it. So let's cheat and check with HEAD2979 * only, which should cover 99% of all usage scenarios (even2980 * 100% of the default ones).2981 *2982 * So if HEAD is a symbolic reference, then record the name of2983 * the reference that it points to. If we see an update of2984 * head_ref within the transaction, then split_head_update()2985 * arranges for the reflog of HEAD to be updated, too.2986 */2987 head_ref =refs_resolve_refdup(ref_store,"HEAD",2988 RESOLVE_REF_NO_RECURSE,2989 head_oid.hash, &head_type);29902991if(head_ref && !(head_type & REF_ISSYMREF)) {2992free(head_ref);2993 head_ref = NULL;2994}29952996/*2997 * Acquire all locks, verify old values if provided, check2998 * that new values are valid, and write new values to the2999 * lockfiles, ready to be activated. Only keep one lockfile3000 * open at a time to avoid running out of file descriptors.3001 * Note that lock_ref_for_update() might append more updates3002 * to the transaction.3003 */3004for(i =0; i < transaction->nr; i++) {3005struct ref_update *update = transaction->updates[i];30063007 ret =lock_ref_for_update(refs, update, transaction,3008 head_ref, &affected_refnames, err);3009if(ret)3010break;3011}30123013cleanup:3014free(head_ref);3015string_list_clear(&affected_refnames,0);30163017if(ret)3018files_transaction_cleanup(transaction);3019else3020 transaction->state = REF_TRANSACTION_PREPARED;30213022return ret;3023}30243025static intfiles_transaction_finish(struct ref_store *ref_store,3026struct ref_transaction *transaction,3027struct strbuf *err)3028{3029struct files_ref_store *refs =3030files_downcast(ref_store,0,"ref_transaction_finish");3031size_t i;3032int ret =0;3033struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3034struct string_list_item *ref_to_delete;3035struct strbuf sb = STRBUF_INIT;30363037assert(err);30383039if(!transaction->nr) {3040 transaction->state = REF_TRANSACTION_CLOSED;3041return0;3042}30433044/* Perform updates first so live commits remain referenced */3045for(i =0; i < transaction->nr; i++) {3046struct ref_update *update = transaction->updates[i];3047struct ref_lock *lock = update->backend_data;30483049if(update->flags & REF_NEEDS_COMMIT ||3050 update->flags & REF_LOG_ONLY) {3051if(files_log_ref_write(refs,3052 lock->ref_name,3053&lock->old_oid,3054&update->new_oid,3055 update->msg, update->flags,3056 err)) {3057char*old_msg =strbuf_detach(err, NULL);30583059strbuf_addf(err,"cannot update the ref '%s':%s",3060 lock->ref_name, old_msg);3061free(old_msg);3062unlock_ref(lock);3063 update->backend_data = NULL;3064 ret = TRANSACTION_GENERIC_ERROR;3065goto cleanup;3066}3067}3068if(update->flags & REF_NEEDS_COMMIT) {3069clear_loose_ref_cache(refs);3070if(commit_ref(lock)) {3071strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3072unlock_ref(lock);3073 update->backend_data = NULL;3074 ret = TRANSACTION_GENERIC_ERROR;3075goto cleanup;3076}3077}3078}3079/* Perform deletes now that updates are safely completed */3080for(i =0; i < transaction->nr; i++) {3081struct ref_update *update = transaction->updates[i];3082struct ref_lock *lock = update->backend_data;30833084if(update->flags & REF_DELETING &&3085!(update->flags & REF_LOG_ONLY)) {3086if(!(update->type & REF_ISPACKED) ||3087 update->type & REF_ISSYMREF) {3088/* It is a loose reference. */3089strbuf_reset(&sb);3090files_ref_path(refs, &sb, lock->ref_name);3091if(unlink_or_msg(sb.buf, err)) {3092 ret = TRANSACTION_GENERIC_ERROR;3093goto cleanup;3094}3095 update->flags |= REF_DELETED_LOOSE;3096}30973098if(!(update->flags & REF_ISPRUNING))3099string_list_append(&refs_to_delete,3100 lock->ref_name);3101}3102}31033104if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {3105 ret = TRANSACTION_GENERIC_ERROR;3106goto cleanup;3107}31083109/* Delete the reflogs of any references that were deleted: */3110for_each_string_list_item(ref_to_delete, &refs_to_delete) {3111strbuf_reset(&sb);3112files_reflog_path(refs, &sb, ref_to_delete->string);3113if(!unlink_or_warn(sb.buf))3114try_remove_empty_parents(refs, ref_to_delete->string,3115 REMOVE_EMPTY_PARENTS_REFLOG);3116}31173118clear_loose_ref_cache(refs);31193120cleanup:3121files_transaction_cleanup(transaction);31223123for(i =0; i < transaction->nr; i++) {3124struct ref_update *update = transaction->updates[i];31253126if(update->flags & REF_DELETED_LOOSE) {3127/*3128 * The loose reference was deleted. Delete any3129 * empty parent directories. (Note that this3130 * can only work because we have already3131 * removed the lockfile.)3132 */3133try_remove_empty_parents(refs, update->refname,3134 REMOVE_EMPTY_PARENTS_REF);3135}3136}31373138strbuf_release(&sb);3139string_list_clear(&refs_to_delete,0);3140return ret;3141}31423143static intfiles_transaction_abort(struct ref_store *ref_store,3144struct ref_transaction *transaction,3145struct strbuf *err)3146{3147files_transaction_cleanup(transaction);3148return0;3149}31503151static intref_present(const char*refname,3152const struct object_id *oid,int flags,void*cb_data)3153{3154struct string_list *affected_refnames = cb_data;31553156returnstring_list_has_string(affected_refnames, refname);3157}31583159static intfiles_initial_transaction_commit(struct ref_store *ref_store,3160struct ref_transaction *transaction,3161struct strbuf *err)3162{3163struct files_ref_store *refs =3164files_downcast(ref_store, REF_STORE_WRITE,3165"initial_ref_transaction_commit");3166size_t i;3167int ret =0;3168struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31693170assert(err);31713172if(transaction->state != REF_TRANSACTION_OPEN)3173die("BUG: commit called for transaction that is not open");31743175/* Fail if a refname appears more than once in the transaction: */3176for(i =0; i < transaction->nr; i++)3177string_list_append(&affected_refnames,3178 transaction->updates[i]->refname);3179string_list_sort(&affected_refnames);3180if(ref_update_reject_duplicates(&affected_refnames, err)) {3181 ret = TRANSACTION_GENERIC_ERROR;3182goto cleanup;3183}31843185/*3186 * It's really undefined to call this function in an active3187 * repository or when there are existing references: we are3188 * only locking and changing packed-refs, so (1) any3189 * simultaneous processes might try to change a reference at3190 * the same time we do, and (2) any existing loose versions of3191 * the references that we are setting would have precedence3192 * over our values. But some remote helpers create the remote3193 * "HEAD" and "master" branches before calling this function,3194 * so here we really only check that none of the references3195 * that we are creating already exists.3196 */3197if(refs_for_each_rawref(&refs->base, ref_present,3198&affected_refnames))3199die("BUG: initial ref transaction called with existing refs");32003201for(i =0; i < transaction->nr; i++) {3202struct ref_update *update = transaction->updates[i];32033204if((update->flags & REF_HAVE_OLD) &&3205!is_null_oid(&update->old_oid))3206die("BUG: initial ref transaction with old_sha1 set");3207if(refs_verify_refname_available(&refs->base, update->refname,3208&affected_refnames, NULL,3209 err)) {3210 ret = TRANSACTION_NAME_CONFLICT;3211goto cleanup;3212}3213}32143215if(lock_packed_refs(refs->packed_ref_store,0)) {3216strbuf_addf(err,"unable to lock packed-refs file:%s",3217strerror(errno));3218 ret = TRANSACTION_GENERIC_ERROR;3219goto cleanup;3220}32213222for(i =0; i < transaction->nr; i++) {3223struct ref_update *update = transaction->updates[i];32243225if((update->flags & REF_HAVE_NEW) &&3226!is_null_oid(&update->new_oid))3227add_packed_ref(refs->packed_ref_store, update->refname,3228&update->new_oid);3229}32303231if(commit_packed_refs(refs->packed_ref_store)) {3232strbuf_addf(err,"unable to commit packed-refs file:%s",3233strerror(errno));3234 ret = TRANSACTION_GENERIC_ERROR;3235goto cleanup;3236}32373238cleanup:3239 transaction->state = REF_TRANSACTION_CLOSED;3240string_list_clear(&affected_refnames,0);3241return ret;3242}32433244struct expire_reflog_cb {3245unsigned int flags;3246 reflog_expiry_should_prune_fn *should_prune_fn;3247void*policy_cb;3248FILE*newlog;3249struct object_id last_kept_oid;3250};32513252static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3253const char*email, timestamp_t timestamp,int tz,3254const char*message,void*cb_data)3255{3256struct expire_reflog_cb *cb = cb_data;3257struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32583259if(cb->flags & EXPIRE_REFLOGS_REWRITE)3260 ooid = &cb->last_kept_oid;32613262if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3263 message, policy_cb)) {3264if(!cb->newlog)3265printf("would prune%s", message);3266else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3267printf("prune%s", message);3268}else{3269if(cb->newlog) {3270fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3271oid_to_hex(ooid),oid_to_hex(noid),3272 email, timestamp, tz, message);3273oidcpy(&cb->last_kept_oid, noid);3274}3275if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3276printf("keep%s", message);3277}3278return0;3279}32803281static intfiles_reflog_expire(struct ref_store *ref_store,3282const char*refname,const unsigned char*sha1,3283unsigned int flags,3284 reflog_expiry_prepare_fn prepare_fn,3285 reflog_expiry_should_prune_fn should_prune_fn,3286 reflog_expiry_cleanup_fn cleanup_fn,3287void*policy_cb_data)3288{3289struct files_ref_store *refs =3290files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3291static struct lock_file reflog_lock;3292struct expire_reflog_cb cb;3293struct ref_lock *lock;3294struct strbuf log_file_sb = STRBUF_INIT;3295char*log_file;3296int status =0;3297int type;3298struct strbuf err = STRBUF_INIT;3299struct object_id oid;33003301memset(&cb,0,sizeof(cb));3302 cb.flags = flags;3303 cb.policy_cb = policy_cb_data;3304 cb.should_prune_fn = should_prune_fn;33053306/*3307 * The reflog file is locked by holding the lock on the3308 * reference itself, plus we might need to update the3309 * reference if --updateref was specified:3310 */3311 lock =lock_ref_sha1_basic(refs, refname, sha1,3312 NULL, NULL, REF_NODEREF,3313&type, &err);3314if(!lock) {3315error("cannot lock ref '%s':%s", refname, err.buf);3316strbuf_release(&err);3317return-1;3318}3319if(!refs_reflog_exists(ref_store, refname)) {3320unlock_ref(lock);3321return0;3322}33233324files_reflog_path(refs, &log_file_sb, refname);3325 log_file =strbuf_detach(&log_file_sb, NULL);3326if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3327/*3328 * Even though holding $GIT_DIR/logs/$reflog.lock has3329 * no locking implications, we use the lock_file3330 * machinery here anyway because it does a lot of the3331 * work we need, including cleaning up if the program3332 * exits unexpectedly.3333 */3334if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3335struct strbuf err = STRBUF_INIT;3336unable_to_lock_message(log_file, errno, &err);3337error("%s", err.buf);3338strbuf_release(&err);3339goto failure;3340}3341 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3342if(!cb.newlog) {3343error("cannot fdopen%s(%s)",3344get_lock_file_path(&reflog_lock),strerror(errno));3345goto failure;3346}3347}33483349hashcpy(oid.hash, sha1);33503351(*prepare_fn)(refname, &oid, cb.policy_cb);3352refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3353(*cleanup_fn)(cb.policy_cb);33543355if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3356/*3357 * It doesn't make sense to adjust a reference pointed3358 * to by a symbolic ref based on expiring entries in3359 * the symbolic reference's reflog. Nor can we update3360 * a reference if there are no remaining reflog3361 * entries.3362 */3363int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3364!(type & REF_ISSYMREF) &&3365!is_null_oid(&cb.last_kept_oid);33663367if(close_lock_file(&reflog_lock)) {3368 status |=error("couldn't write%s:%s", log_file,3369strerror(errno));3370}else if(update &&3371(write_in_full(get_lock_file_fd(lock->lk),3372oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3373write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3374close_ref(lock) <0)) {3375 status |=error("couldn't write%s",3376get_lock_file_path(lock->lk));3377rollback_lock_file(&reflog_lock);3378}else if(commit_lock_file(&reflog_lock)) {3379 status |=error("unable to write reflog '%s' (%s)",3380 log_file,strerror(errno));3381}else if(update &&commit_ref(lock)) {3382 status |=error("couldn't set%s", lock->ref_name);3383}3384}3385free(log_file);3386unlock_ref(lock);3387return status;33883389 failure:3390rollback_lock_file(&reflog_lock);3391free(log_file);3392unlock_ref(lock);3393return-1;3394}33953396static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3397{3398struct files_ref_store *refs =3399files_downcast(ref_store, REF_STORE_WRITE,"init_db");3400struct strbuf sb = STRBUF_INIT;34013402/*3403 * Create .git/refs/{heads,tags}3404 */3405files_ref_path(refs, &sb,"refs/heads");3406safe_create_dir(sb.buf,1);34073408strbuf_reset(&sb);3409files_ref_path(refs, &sb,"refs/tags");3410safe_create_dir(sb.buf,1);34113412strbuf_release(&sb);3413return0;3414}34153416struct ref_storage_be refs_be_files = {3417 NULL,3418"files",3419 files_ref_store_create,3420 files_init_db,3421 files_transaction_prepare,3422 files_transaction_finish,3423 files_transaction_abort,3424 files_initial_transaction_commit,34253426 files_pack_refs,3427 files_peel_ref,3428 files_create_symref,3429 files_delete_refs,3430 files_rename_ref,34313432 files_ref_iterator_begin,3433 files_read_raw_ref,34343435 files_reflog_iterator_begin,3436 files_for_each_reflog_ent,3437 files_for_each_reflog_ent_reverse,3438 files_reflog_exists,3439 files_create_reflog,3440 files_delete_reflog,3441 files_reflog_expire3442};