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 files_ref_store *refs, 606const char*refname) 607{ 608returnfind_ref_entry(get_packed_refs(refs->packed_ref_store), 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, 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 =get_packed_ref(refs, refname);1048if(r) {1049if(peel_entry(r,0))1050return-1;1051hashcpy(sha1, r->u.value.peeled.hash);1052return0;1053}1054}10551056returnpeel_object(base, sha1);1057}10581059struct files_ref_iterator {1060struct ref_iterator base;10611062struct packed_ref_cache *packed_ref_cache;1063struct ref_iterator *iter0;1064unsigned int flags;1065};10661067static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1068{1069struct files_ref_iterator *iter =1070(struct files_ref_iterator *)ref_iterator;1071int ok;10721073while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1074if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1075ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1076continue;10771078if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1079!ref_resolves_to_object(iter->iter0->refname,1080 iter->iter0->oid,1081 iter->iter0->flags))1082continue;10831084 iter->base.refname = iter->iter0->refname;1085 iter->base.oid = iter->iter0->oid;1086 iter->base.flags = iter->iter0->flags;1087return ITER_OK;1088}10891090 iter->iter0 = NULL;1091if(ref_iterator_abort(ref_iterator) != ITER_DONE)1092 ok = ITER_ERROR;10931094return ok;1095}10961097static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1098struct object_id *peeled)1099{1100struct files_ref_iterator *iter =1101(struct files_ref_iterator *)ref_iterator;11021103returnref_iterator_peel(iter->iter0, peeled);1104}11051106static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1107{1108struct files_ref_iterator *iter =1109(struct files_ref_iterator *)ref_iterator;1110int ok = ITER_DONE;11111112if(iter->iter0)1113 ok =ref_iterator_abort(iter->iter0);11141115release_packed_ref_cache(iter->packed_ref_cache);1116base_ref_iterator_free(ref_iterator);1117return ok;1118}11191120static struct ref_iterator_vtable files_ref_iterator_vtable = {1121 files_ref_iterator_advance,1122 files_ref_iterator_peel,1123 files_ref_iterator_abort1124};11251126static struct ref_iterator *files_ref_iterator_begin(1127struct ref_store *ref_store,1128const char*prefix,unsigned int flags)1129{1130struct files_ref_store *refs;1131struct ref_iterator *loose_iter, *packed_iter;1132struct files_ref_iterator *iter;1133struct ref_iterator *ref_iterator;1134unsigned int required_flags = REF_STORE_READ;11351136if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1137 required_flags |= REF_STORE_ODB;11381139 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11401141 iter =xcalloc(1,sizeof(*iter));1142 ref_iterator = &iter->base;1143base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11441145/*1146 * We must make sure that all loose refs are read before1147 * accessing the packed-refs file; this avoids a race1148 * condition if loose refs are migrated to the packed-refs1149 * file by a simultaneous process, but our in-memory view is1150 * from before the migration. We ensure this as follows:1151 * First, we call start the loose refs iteration with its1152 * `prime_ref` argument set to true. This causes the loose1153 * references in the subtree to be pre-read into the cache.1154 * (If they've already been read, that's OK; we only need to1155 * guarantee that they're read before the packed refs, not1156 * *how much* before.) After that, we call1157 * get_packed_ref_cache(), which internally checks whether the1158 * packed-ref cache is up to date with what is on disk, and1159 * re-reads it if not.1160 */11611162 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1163 prefix,1);11641165 iter->packed_ref_cache =get_packed_ref_cache(refs->packed_ref_store);1166acquire_packed_ref_cache(iter->packed_ref_cache);1167 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1168 prefix,0);11691170 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1171 iter->flags = flags;11721173return ref_iterator;1174}11751176/*1177 * Verify that the reference locked by lock has the value old_sha1.1178 * Fail if the reference doesn't exist and mustexist is set. Return 01179 * on success. On error, write an error message to err, set errno, and1180 * return a negative value.1181 */1182static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1183const unsigned char*old_sha1,int mustexist,1184struct strbuf *err)1185{1186assert(err);11871188if(refs_read_ref_full(ref_store, lock->ref_name,1189 mustexist ? RESOLVE_REF_READING :0,1190 lock->old_oid.hash, NULL)) {1191if(old_sha1) {1192int save_errno = errno;1193strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1194 errno = save_errno;1195return-1;1196}else{1197oidclr(&lock->old_oid);1198return0;1199}1200}1201if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1202strbuf_addf(err,"ref '%s' is at%sbut expected%s",1203 lock->ref_name,1204oid_to_hex(&lock->old_oid),1205sha1_to_hex(old_sha1));1206 errno = EBUSY;1207return-1;1208}1209return0;1210}12111212static intremove_empty_directories(struct strbuf *path)1213{1214/*1215 * we want to create a file but there is a directory there;1216 * if that is an empty directory (or a directory that contains1217 * only empty directories), remove them.1218 */1219returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1220}12211222static intcreate_reflock(const char*path,void*cb)1223{1224struct lock_file *lk = cb;12251226returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1227}12281229/*1230 * Locks a ref returning the lock on success and NULL on failure.1231 * On failure errno is set to something meaningful.1232 */1233static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1234const char*refname,1235const unsigned char*old_sha1,1236const struct string_list *extras,1237const struct string_list *skip,1238unsigned int flags,int*type,1239struct strbuf *err)1240{1241struct strbuf ref_file = STRBUF_INIT;1242struct ref_lock *lock;1243int last_errno =0;1244int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1245int resolve_flags = RESOLVE_REF_NO_RECURSE;1246int resolved;12471248files_assert_main_repository(refs,"lock_ref_sha1_basic");1249assert(err);12501251 lock =xcalloc(1,sizeof(struct ref_lock));12521253if(mustexist)1254 resolve_flags |= RESOLVE_REF_READING;1255if(flags & REF_DELETING)1256 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12571258files_ref_path(refs, &ref_file, refname);1259 resolved = !!refs_resolve_ref_unsafe(&refs->base,1260 refname, resolve_flags,1261 lock->old_oid.hash, type);1262if(!resolved && errno == EISDIR) {1263/*1264 * we are trying to lock foo but we used to1265 * have foo/bar which now does not exist;1266 * it is normal for the empty directory 'foo'1267 * to remain.1268 */1269if(remove_empty_directories(&ref_file)) {1270 last_errno = errno;1271if(!refs_verify_refname_available(1272&refs->base,1273 refname, extras, skip, err))1274strbuf_addf(err,"there are still refs under '%s'",1275 refname);1276goto error_return;1277}1278 resolved = !!refs_resolve_ref_unsafe(&refs->base,1279 refname, resolve_flags,1280 lock->old_oid.hash, type);1281}1282if(!resolved) {1283 last_errno = errno;1284if(last_errno != ENOTDIR ||1285!refs_verify_refname_available(&refs->base, refname,1286 extras, skip, err))1287strbuf_addf(err,"unable to resolve reference '%s':%s",1288 refname,strerror(last_errno));12891290goto error_return;1291}12921293/*1294 * If the ref did not exist and we are creating it, make sure1295 * there is no existing packed ref whose name begins with our1296 * refname, nor a packed ref whose name is a proper prefix of1297 * our refname.1298 */1299if(is_null_oid(&lock->old_oid) &&1300refs_verify_refname_available(&refs->base, refname,1301 extras, skip, err)) {1302 last_errno = ENOTDIR;1303goto error_return;1304}13051306 lock->lk =xcalloc(1,sizeof(struct lock_file));13071308 lock->ref_name =xstrdup(refname);13091310if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1311 last_errno = errno;1312unable_to_lock_message(ref_file.buf, errno, err);1313goto error_return;1314}13151316if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1317 last_errno = errno;1318goto error_return;1319}1320goto out;13211322 error_return:1323unlock_ref(lock);1324 lock = NULL;13251326 out:1327strbuf_release(&ref_file);1328 errno = last_errno;1329return lock;1330}13311332/*1333 * Write an entry to the packed-refs file for the specified refname.1334 * If peeled is non-NULL, write it as the entry's peeled value.1335 */1336static voidwrite_packed_entry(FILE*fh,const char*refname,1337const unsigned char*sha1,1338const unsigned char*peeled)1339{1340fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1341if(peeled)1342fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1343}13441345/*1346 * Lock the packed-refs file for writing. Flags is passed to1347 * hold_lock_file_for_update(). Return 0 on success. On errors, set1348 * errno appropriately and return a nonzero value.1349 */1350static intlock_packed_refs(struct packed_ref_store *refs,int flags)1351{1352static int timeout_configured =0;1353static int timeout_value =1000;1354struct packed_ref_cache *packed_ref_cache;13551356packed_assert_main_repository(refs,"lock_packed_refs");13571358if(!timeout_configured) {1359git_config_get_int("core.packedrefstimeout", &timeout_value);1360 timeout_configured =1;1361}13621363if(hold_lock_file_for_update_timeout(1364&refs->lock,1365 refs->path,1366 flags, timeout_value) <0)1367return-1;13681369/*1370 * Now that we hold the `packed-refs` lock, make sure that our1371 * cache matches the current version of the file. Normally1372 * `get_packed_ref_cache()` does that for us, but that1373 * function assumes that when the file is locked, any existing1374 * cache is still valid. We've just locked the file, but it1375 * might have changed the moment *before* we locked it.1376 */1377validate_packed_ref_cache(refs);13781379 packed_ref_cache =get_packed_ref_cache(refs);1380/* Increment the reference count to prevent it from being freed: */1381acquire_packed_ref_cache(packed_ref_cache);1382return0;1383}13841385/*1386 * Write the current version of the packed refs cache from memory to1387 * disk. The packed-refs file must already be locked for writing (see1388 * lock_packed_refs()). Return zero on success. On errors, set errno1389 * and return a nonzero value1390 */1391static intcommit_packed_refs(struct packed_ref_store *refs)1392{1393struct packed_ref_cache *packed_ref_cache =1394get_packed_ref_cache(refs);1395int ok, error =0;1396int save_errno =0;1397FILE*out;1398struct ref_iterator *iter;13991400packed_assert_main_repository(refs,"commit_packed_refs");14011402if(!is_lock_file_locked(&refs->lock))1403die("BUG: packed-refs not locked");14041405 out =fdopen_lock_file(&refs->lock,"w");1406if(!out)1407die_errno("unable to fdopen packed-refs descriptor");14081409fprintf_or_die(out,"%s", PACKED_REFS_HEADER);14101411 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1412while((ok =ref_iterator_advance(iter)) == ITER_OK) {1413struct object_id peeled;1414int peel_error =ref_iterator_peel(iter, &peeled);14151416write_packed_entry(out, iter->refname, iter->oid->hash,1417 peel_error ? NULL : peeled.hash);1418}14191420if(ok != ITER_DONE)1421die("error while iterating over references");14221423if(commit_lock_file(&refs->lock)) {1424 save_errno = errno;1425 error = -1;1426}1427release_packed_ref_cache(packed_ref_cache);1428 errno = save_errno;1429return error;1430}14311432/*1433 * Rollback the lockfile for the packed-refs file, and discard the1434 * in-memory packed reference cache. (The packed-refs file will be1435 * read anew if it is needed again after this function is called.)1436 */1437static voidrollback_packed_refs(struct files_ref_store *refs)1438{1439struct packed_ref_cache *packed_ref_cache =1440get_packed_ref_cache(refs->packed_ref_store);14411442files_assert_main_repository(refs,"rollback_packed_refs");14431444if(!is_lock_file_locked(&refs->packed_ref_store->lock))1445die("BUG: packed-refs not locked");1446rollback_lock_file(&refs->packed_ref_store->lock);1447release_packed_ref_cache(packed_ref_cache);1448clear_packed_ref_cache(refs->packed_ref_store);1449}14501451struct ref_to_prune {1452struct ref_to_prune *next;1453unsigned char sha1[20];1454char name[FLEX_ARRAY];1455};14561457enum{1458 REMOVE_EMPTY_PARENTS_REF =0x01,1459 REMOVE_EMPTY_PARENTS_REFLOG =0x021460};14611462/*1463 * Remove empty parent directories associated with the specified1464 * reference and/or its reflog, but spare [logs/]refs/ and immediate1465 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1466 * REMOVE_EMPTY_PARENTS_REFLOG.1467 */1468static voidtry_remove_empty_parents(struct files_ref_store *refs,1469const char*refname,1470unsigned int flags)1471{1472struct strbuf buf = STRBUF_INIT;1473struct strbuf sb = STRBUF_INIT;1474char*p, *q;1475int i;14761477strbuf_addstr(&buf, refname);1478 p = buf.buf;1479for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1480while(*p && *p !='/')1481 p++;1482/* tolerate duplicate slashes; see check_refname_format() */1483while(*p =='/')1484 p++;1485}1486 q = buf.buf + buf.len;1487while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1488while(q > p && *q !='/')1489 q--;1490while(q > p && *(q-1) =='/')1491 q--;1492if(q == p)1493break;1494strbuf_setlen(&buf, q - buf.buf);14951496strbuf_reset(&sb);1497files_ref_path(refs, &sb, buf.buf);1498if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1499 flags &= ~REMOVE_EMPTY_PARENTS_REF;15001501strbuf_reset(&sb);1502files_reflog_path(refs, &sb, buf.buf);1503if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1504 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1505}1506strbuf_release(&buf);1507strbuf_release(&sb);1508}15091510/* make sure nobody touched the ref, and unlink */1511static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1512{1513struct ref_transaction *transaction;1514struct strbuf err = STRBUF_INIT;15151516if(check_refname_format(r->name,0))1517return;15181519 transaction =ref_store_transaction_begin(&refs->base, &err);1520if(!transaction ||1521ref_transaction_delete(transaction, r->name, r->sha1,1522 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1523ref_transaction_commit(transaction, &err)) {1524ref_transaction_free(transaction);1525error("%s", err.buf);1526strbuf_release(&err);1527return;1528}1529ref_transaction_free(transaction);1530strbuf_release(&err);1531}15321533static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1534{1535while(r) {1536prune_ref(refs, r);1537 r = r->next;1538}1539}15401541/*1542 * Return true if the specified reference should be packed.1543 */1544static intshould_pack_ref(const char*refname,1545const struct object_id *oid,unsigned int ref_flags,1546unsigned int pack_flags)1547{1548/* Do not pack per-worktree refs: */1549if(ref_type(refname) != REF_TYPE_NORMAL)1550return0;15511552/* Do not pack non-tags unless PACK_REFS_ALL is set: */1553if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1554return0;15551556/* Do not pack symbolic refs: */1557if(ref_flags & REF_ISSYMREF)1558return0;15591560/* Do not pack broken refs: */1561if(!ref_resolves_to_object(refname, oid, ref_flags))1562return0;15631564return1;1565}15661567static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1568{1569struct files_ref_store *refs =1570files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1571"pack_refs");1572struct ref_iterator *iter;1573int ok;1574struct ref_to_prune *refs_to_prune = NULL;15751576lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);15771578 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1579while((ok =ref_iterator_advance(iter)) == ITER_OK) {1580/*1581 * If the loose reference can be packed, add an entry1582 * in the packed ref cache. If the reference should be1583 * pruned, also add it to refs_to_prune.1584 */1585if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1586 flags))1587continue;15881589/*1590 * Create an entry in the packed-refs cache equivalent1591 * to the one from the loose ref cache, except that1592 * we don't copy the peeled status, because we want it1593 * to be re-peeled.1594 */1595add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);15961597/* Schedule the loose reference for pruning if requested. */1598if((flags & PACK_REFS_PRUNE)) {1599struct ref_to_prune *n;1600FLEX_ALLOC_STR(n, name, iter->refname);1601hashcpy(n->sha1, iter->oid->hash);1602 n->next = refs_to_prune;1603 refs_to_prune = n;1604}1605}1606if(ok != ITER_DONE)1607die("error while iterating over references");16081609if(commit_packed_refs(refs->packed_ref_store))1610die_errno("unable to overwrite old ref-pack file");16111612prune_refs(refs, refs_to_prune);1613return0;1614}16151616/*1617 * Rewrite the packed-refs file, omitting any refs listed in1618 * 'refnames'. On error, leave packed-refs unchanged, write an error1619 * message to 'err', and return a nonzero value.1620 *1621 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1622 */1623static intrepack_without_refs(struct files_ref_store *refs,1624struct string_list *refnames,struct strbuf *err)1625{1626struct ref_dir *packed;1627struct string_list_item *refname;1628int ret, needs_repacking =0, removed =0;16291630files_assert_main_repository(refs,"repack_without_refs");1631assert(err);16321633/* Look for a packed ref */1634for_each_string_list_item(refname, refnames) {1635if(get_packed_ref(refs, refname->string)) {1636 needs_repacking =1;1637break;1638}1639}16401641/* Avoid locking if we have nothing to do */1642if(!needs_repacking)1643return0;/* no refname exists in packed refs */16441645if(lock_packed_refs(refs->packed_ref_store,0)) {1646unable_to_lock_message(refs->packed_ref_store->path, errno, err);1647return-1;1648}1649 packed =get_packed_refs(refs->packed_ref_store);16501651/* Remove refnames from the cache */1652for_each_string_list_item(refname, refnames)1653if(remove_entry_from_dir(packed, refname->string) != -1)1654 removed =1;1655if(!removed) {1656/*1657 * All packed entries disappeared while we were1658 * acquiring the lock.1659 */1660rollback_packed_refs(refs);1661return0;1662}16631664/* Write what remains */1665 ret =commit_packed_refs(refs->packed_ref_store);1666if(ret)1667strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1668strerror(errno));1669return ret;1670}16711672static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1673struct string_list *refnames,unsigned int flags)1674{1675struct files_ref_store *refs =1676files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1677struct strbuf err = STRBUF_INIT;1678int i, result =0;16791680if(!refnames->nr)1681return0;16821683 result =repack_without_refs(refs, refnames, &err);1684if(result) {1685/*1686 * If we failed to rewrite the packed-refs file, then1687 * it is unsafe to try to remove loose refs, because1688 * doing so might expose an obsolete packed value for1689 * a reference that might even point at an object that1690 * has been garbage collected.1691 */1692if(refnames->nr ==1)1693error(_("could not delete reference%s:%s"),1694 refnames->items[0].string, err.buf);1695else1696error(_("could not delete references:%s"), err.buf);16971698goto out;1699}17001701for(i =0; i < refnames->nr; i++) {1702const char*refname = refnames->items[i].string;17031704if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1705 result |=error(_("could not remove reference%s"), refname);1706}17071708out:1709strbuf_release(&err);1710return result;1711}17121713/*1714 * People using contrib's git-new-workdir have .git/logs/refs ->1715 * /some/other/path/.git/logs/refs, and that may live on another device.1716 *1717 * IOW, to avoid cross device rename errors, the temporary renamed log must1718 * live into logs/refs.1719 */1720#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"17211722struct rename_cb {1723const char*tmp_renamed_log;1724int true_errno;1725};17261727static intrename_tmp_log_callback(const char*path,void*cb_data)1728{1729struct rename_cb *cb = cb_data;17301731if(rename(cb->tmp_renamed_log, path)) {1732/*1733 * rename(a, b) when b is an existing directory ought1734 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1735 * Sheesh. Record the true errno for error reporting,1736 * but report EISDIR to raceproof_create_file() so1737 * that it knows to retry.1738 */1739 cb->true_errno = errno;1740if(errno == ENOTDIR)1741 errno = EISDIR;1742return-1;1743}else{1744return0;1745}1746}17471748static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1749{1750struct strbuf path = STRBUF_INIT;1751struct strbuf tmp = STRBUF_INIT;1752struct rename_cb cb;1753int ret;17541755files_reflog_path(refs, &path, newrefname);1756files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1757 cb.tmp_renamed_log = tmp.buf;1758 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1759if(ret) {1760if(errno == EISDIR)1761error("directory not empty:%s", path.buf);1762else1763error("unable to move logfile%sto%s:%s",1764 tmp.buf, path.buf,1765strerror(cb.true_errno));1766}17671768strbuf_release(&path);1769strbuf_release(&tmp);1770return ret;1771}17721773static intwrite_ref_to_lockfile(struct ref_lock *lock,1774const struct object_id *oid,struct strbuf *err);1775static intcommit_ref_update(struct files_ref_store *refs,1776struct ref_lock *lock,1777const struct object_id *oid,const char*logmsg,1778struct strbuf *err);17791780static intfiles_rename_ref(struct ref_store *ref_store,1781const char*oldrefname,const char*newrefname,1782const char*logmsg)1783{1784struct files_ref_store *refs =1785files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1786struct object_id oid, orig_oid;1787int flag =0, logmoved =0;1788struct ref_lock *lock;1789struct stat loginfo;1790struct strbuf sb_oldref = STRBUF_INIT;1791struct strbuf sb_newref = STRBUF_INIT;1792struct strbuf tmp_renamed_log = STRBUF_INIT;1793int log, ret;1794struct strbuf err = STRBUF_INIT;17951796files_reflog_path(refs, &sb_oldref, oldrefname);1797files_reflog_path(refs, &sb_newref, newrefname);1798files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17991800 log = !lstat(sb_oldref.buf, &loginfo);1801if(log &&S_ISLNK(loginfo.st_mode)) {1802 ret =error("reflog for%sis a symlink", oldrefname);1803goto out;1804}18051806if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1807 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1808 orig_oid.hash, &flag)) {1809 ret =error("refname%snot found", oldrefname);1810goto out;1811}18121813if(flag & REF_ISSYMREF) {1814 ret =error("refname%sis a symbolic ref, renaming it is not supported",1815 oldrefname);1816goto out;1817}1818if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1819 ret =1;1820goto out;1821}18221823if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1824 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1825 oldrefname,strerror(errno));1826goto out;1827}18281829if(refs_delete_ref(&refs->base, logmsg, oldrefname,1830 orig_oid.hash, REF_NODEREF)) {1831error("unable to delete old%s", oldrefname);1832goto rollback;1833}18341835/*1836 * Since we are doing a shallow lookup, oid is not the1837 * correct value to pass to delete_ref as old_oid. But that1838 * doesn't matter, because an old_oid check wouldn't add to1839 * the safety anyway; we want to delete the reference whatever1840 * its current value.1841 */1842if(!refs_read_ref_full(&refs->base, newrefname,1843 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1844 oid.hash, NULL) &&1845refs_delete_ref(&refs->base, NULL, newrefname,1846 NULL, REF_NODEREF)) {1847if(errno == EISDIR) {1848struct strbuf path = STRBUF_INIT;1849int result;18501851files_ref_path(refs, &path, newrefname);1852 result =remove_empty_directories(&path);1853strbuf_release(&path);18541855if(result) {1856error("Directory not empty:%s", newrefname);1857goto rollback;1858}1859}else{1860error("unable to delete existing%s", newrefname);1861goto rollback;1862}1863}18641865if(log &&rename_tmp_log(refs, newrefname))1866goto rollback;18671868 logmoved = log;18691870 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1871 REF_NODEREF, NULL, &err);1872if(!lock) {1873error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1874strbuf_release(&err);1875goto rollback;1876}1877oidcpy(&lock->old_oid, &orig_oid);18781879if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1880commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1881error("unable to write current sha1 into%s:%s", newrefname, err.buf);1882strbuf_release(&err);1883goto rollback;1884}18851886 ret =0;1887goto out;18881889 rollback:1890 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1891 REF_NODEREF, NULL, &err);1892if(!lock) {1893error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1894strbuf_release(&err);1895goto rollbacklog;1896}18971898 flag = log_all_ref_updates;1899 log_all_ref_updates = LOG_REFS_NONE;1900if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1901commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1902error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1903strbuf_release(&err);1904}1905 log_all_ref_updates = flag;19061907 rollbacklog:1908if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1909error("unable to restore logfile%sfrom%s:%s",1910 oldrefname, newrefname,strerror(errno));1911if(!logmoved && log &&1912rename(tmp_renamed_log.buf, sb_oldref.buf))1913error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1914 oldrefname,strerror(errno));1915 ret =1;1916 out:1917strbuf_release(&sb_newref);1918strbuf_release(&sb_oldref);1919strbuf_release(&tmp_renamed_log);19201921return ret;1922}19231924static intclose_ref(struct ref_lock *lock)1925{1926if(close_lock_file(lock->lk))1927return-1;1928return0;1929}19301931static intcommit_ref(struct ref_lock *lock)1932{1933char*path =get_locked_file_path(lock->lk);1934struct stat st;19351936if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1937/*1938 * There is a directory at the path we want to rename1939 * the lockfile to. Hopefully it is empty; try to1940 * delete it.1941 */1942size_t len =strlen(path);1943struct strbuf sb_path = STRBUF_INIT;19441945strbuf_attach(&sb_path, path, len, len);19461947/*1948 * If this fails, commit_lock_file() will also fail1949 * and will report the problem.1950 */1951remove_empty_directories(&sb_path);1952strbuf_release(&sb_path);1953}else{1954free(path);1955}19561957if(commit_lock_file(lock->lk))1958return-1;1959return0;1960}19611962static intopen_or_create_logfile(const char*path,void*cb)1963{1964int*fd = cb;19651966*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1967return(*fd <0) ? -1:0;1968}19691970/*1971 * Create a reflog for a ref. If force_create = 0, only create the1972 * reflog for certain refs (those for which should_autocreate_reflog1973 * returns non-zero). Otherwise, create it regardless of the reference1974 * name. If the logfile already existed or was created, return 0 and1975 * set *logfd to the file descriptor opened for appending to the file.1976 * If no logfile exists and we decided not to create one, return 0 and1977 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1978 * return -1.1979 */1980static intlog_ref_setup(struct files_ref_store *refs,1981const char*refname,int force_create,1982int*logfd,struct strbuf *err)1983{1984struct strbuf logfile_sb = STRBUF_INIT;1985char*logfile;19861987files_reflog_path(refs, &logfile_sb, refname);1988 logfile =strbuf_detach(&logfile_sb, NULL);19891990if(force_create ||should_autocreate_reflog(refname)) {1991if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1992if(errno == ENOENT)1993strbuf_addf(err,"unable to create directory for '%s': "1994"%s", logfile,strerror(errno));1995else if(errno == EISDIR)1996strbuf_addf(err,"there are still logs under '%s'",1997 logfile);1998else1999strbuf_addf(err,"unable to append to '%s':%s",2000 logfile,strerror(errno));20012002goto error;2003}2004}else{2005*logfd =open(logfile, O_APPEND | O_WRONLY,0666);2006if(*logfd <0) {2007if(errno == ENOENT || errno == EISDIR) {2008/*2009 * The logfile doesn't already exist,2010 * but that is not an error; it only2011 * means that we won't write log2012 * entries to it.2013 */2014;2015}else{2016strbuf_addf(err,"unable to append to '%s':%s",2017 logfile,strerror(errno));2018goto error;2019}2020}2021}20222023if(*logfd >=0)2024adjust_shared_perm(logfile);20252026free(logfile);2027return0;20282029error:2030free(logfile);2031return-1;2032}20332034static intfiles_create_reflog(struct ref_store *ref_store,2035const char*refname,int force_create,2036struct strbuf *err)2037{2038struct files_ref_store *refs =2039files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2040int fd;20412042if(log_ref_setup(refs, refname, force_create, &fd, err))2043return-1;20442045if(fd >=0)2046close(fd);20472048return0;2049}20502051static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2052const struct object_id *new_oid,2053const char*committer,const char*msg)2054{2055int msglen, written;2056unsigned maxlen, len;2057char*logrec;20582059 msglen = msg ?strlen(msg) :0;2060 maxlen =strlen(committer) + msglen +100;2061 logrec =xmalloc(maxlen);2062 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2063oid_to_hex(old_oid),2064oid_to_hex(new_oid),2065 committer);2066if(msglen)2067 len +=copy_reflog_msg(logrec + len -1, msg) -1;20682069 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2070free(logrec);2071if(written != len)2072return-1;20732074return0;2075}20762077static intfiles_log_ref_write(struct files_ref_store *refs,2078const char*refname,const struct object_id *old_oid,2079const struct object_id *new_oid,const char*msg,2080int flags,struct strbuf *err)2081{2082int logfd, result;20832084if(log_all_ref_updates == LOG_REFS_UNSET)2085 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20862087 result =log_ref_setup(refs, refname,2088 flags & REF_FORCE_CREATE_REFLOG,2089&logfd, err);20902091if(result)2092return result;20932094if(logfd <0)2095return0;2096 result =log_ref_write_fd(logfd, old_oid, new_oid,2097git_committer_info(0), msg);2098if(result) {2099struct strbuf sb = STRBUF_INIT;2100int save_errno = errno;21012102files_reflog_path(refs, &sb, refname);2103strbuf_addf(err,"unable to append to '%s':%s",2104 sb.buf,strerror(save_errno));2105strbuf_release(&sb);2106close(logfd);2107return-1;2108}2109if(close(logfd)) {2110struct strbuf sb = STRBUF_INIT;2111int save_errno = errno;21122113files_reflog_path(refs, &sb, refname);2114strbuf_addf(err,"unable to append to '%s':%s",2115 sb.buf,strerror(save_errno));2116strbuf_release(&sb);2117return-1;2118}2119return0;2120}21212122/*2123 * Write sha1 into the open lockfile, then close the lockfile. On2124 * errors, rollback the lockfile, fill in *err and2125 * return -1.2126 */2127static intwrite_ref_to_lockfile(struct ref_lock *lock,2128const struct object_id *oid,struct strbuf *err)2129{2130static char term ='\n';2131struct object *o;2132int fd;21332134 o =parse_object(oid);2135if(!o) {2136strbuf_addf(err,2137"trying to write ref '%s' with nonexistent object%s",2138 lock->ref_name,oid_to_hex(oid));2139unlock_ref(lock);2140return-1;2141}2142if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2143strbuf_addf(err,2144"trying to write non-commit object%sto branch '%s'",2145oid_to_hex(oid), lock->ref_name);2146unlock_ref(lock);2147return-1;2148}2149 fd =get_lock_file_fd(lock->lk);2150if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2151write_in_full(fd, &term,1) !=1||2152close_ref(lock) <0) {2153strbuf_addf(err,2154"couldn't write '%s'",get_lock_file_path(lock->lk));2155unlock_ref(lock);2156return-1;2157}2158return0;2159}21602161/*2162 * Commit a change to a loose reference that has already been written2163 * to the loose reference lockfile. Also update the reflogs if2164 * necessary, using the specified lockmsg (which can be NULL).2165 */2166static intcommit_ref_update(struct files_ref_store *refs,2167struct ref_lock *lock,2168const struct object_id *oid,const char*logmsg,2169struct strbuf *err)2170{2171files_assert_main_repository(refs,"commit_ref_update");21722173clear_loose_ref_cache(refs);2174if(files_log_ref_write(refs, lock->ref_name,2175&lock->old_oid, oid,2176 logmsg,0, err)) {2177char*old_msg =strbuf_detach(err, NULL);2178strbuf_addf(err,"cannot update the ref '%s':%s",2179 lock->ref_name, old_msg);2180free(old_msg);2181unlock_ref(lock);2182return-1;2183}21842185if(strcmp(lock->ref_name,"HEAD") !=0) {2186/*2187 * Special hack: If a branch is updated directly and HEAD2188 * points to it (may happen on the remote side of a push2189 * for example) then logically the HEAD reflog should be2190 * updated too.2191 * A generic solution implies reverse symref information,2192 * but finding all symrefs pointing to the given branch2193 * would be rather costly for this rare event (the direct2194 * update of a branch) to be worth it. So let's cheat and2195 * check with HEAD only which should cover 99% of all usage2196 * scenarios (even 100% of the default ones).2197 */2198struct object_id head_oid;2199int head_flag;2200const char*head_ref;22012202 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2203 RESOLVE_REF_READING,2204 head_oid.hash, &head_flag);2205if(head_ref && (head_flag & REF_ISSYMREF) &&2206!strcmp(head_ref, lock->ref_name)) {2207struct strbuf log_err = STRBUF_INIT;2208if(files_log_ref_write(refs,"HEAD",2209&lock->old_oid, oid,2210 logmsg,0, &log_err)) {2211error("%s", log_err.buf);2212strbuf_release(&log_err);2213}2214}2215}22162217if(commit_ref(lock)) {2218strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2219unlock_ref(lock);2220return-1;2221}22222223unlock_ref(lock);2224return0;2225}22262227static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2228{2229int ret = -1;2230#ifndef NO_SYMLINK_HEAD2231char*ref_path =get_locked_file_path(lock->lk);2232unlink(ref_path);2233 ret =symlink(target, ref_path);2234free(ref_path);22352236if(ret)2237fprintf(stderr,"no symlink - falling back to symbolic ref\n");2238#endif2239return ret;2240}22412242static voidupdate_symref_reflog(struct files_ref_store *refs,2243struct ref_lock *lock,const char*refname,2244const char*target,const char*logmsg)2245{2246struct strbuf err = STRBUF_INIT;2247struct object_id new_oid;2248if(logmsg &&2249!refs_read_ref_full(&refs->base, target,2250 RESOLVE_REF_READING, new_oid.hash, NULL) &&2251files_log_ref_write(refs, refname, &lock->old_oid,2252&new_oid, logmsg,0, &err)) {2253error("%s", err.buf);2254strbuf_release(&err);2255}2256}22572258static intcreate_symref_locked(struct files_ref_store *refs,2259struct ref_lock *lock,const char*refname,2260const char*target,const char*logmsg)2261{2262if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2263update_symref_reflog(refs, lock, refname, target, logmsg);2264return0;2265}22662267if(!fdopen_lock_file(lock->lk,"w"))2268returnerror("unable to fdopen%s:%s",2269 lock->lk->tempfile.filename.buf,strerror(errno));22702271update_symref_reflog(refs, lock, refname, target, logmsg);22722273/* no error check; commit_ref will check ferror */2274fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2275if(commit_ref(lock) <0)2276returnerror("unable to write symref for%s:%s", refname,2277strerror(errno));2278return0;2279}22802281static intfiles_create_symref(struct ref_store *ref_store,2282const char*refname,const char*target,2283const char*logmsg)2284{2285struct files_ref_store *refs =2286files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2287struct strbuf err = STRBUF_INIT;2288struct ref_lock *lock;2289int ret;22902291 lock =lock_ref_sha1_basic(refs, refname, NULL,2292 NULL, NULL, REF_NODEREF, NULL,2293&err);2294if(!lock) {2295error("%s", err.buf);2296strbuf_release(&err);2297return-1;2298}22992300 ret =create_symref_locked(refs, lock, refname, target, logmsg);2301unlock_ref(lock);2302return ret;2303}23042305static intfiles_reflog_exists(struct ref_store *ref_store,2306const char*refname)2307{2308struct files_ref_store *refs =2309files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2310struct strbuf sb = STRBUF_INIT;2311struct stat st;2312int ret;23132314files_reflog_path(refs, &sb, refname);2315 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2316strbuf_release(&sb);2317return ret;2318}23192320static intfiles_delete_reflog(struct ref_store *ref_store,2321const char*refname)2322{2323struct files_ref_store *refs =2324files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2325struct strbuf sb = STRBUF_INIT;2326int ret;23272328files_reflog_path(refs, &sb, refname);2329 ret =remove_path(sb.buf);2330strbuf_release(&sb);2331return ret;2332}23332334static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2335{2336struct object_id ooid, noid;2337char*email_end, *message;2338 timestamp_t timestamp;2339int tz;2340const char*p = sb->buf;23412342/* old SP new SP name <email> SP time TAB msg LF */2343if(!sb->len || sb->buf[sb->len -1] !='\n'||2344parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2345parse_oid_hex(p, &noid, &p) || *p++ !=' '||2346!(email_end =strchr(p,'>')) ||2347 email_end[1] !=' '||2348!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2349!message || message[0] !=' '||2350(message[1] !='+'&& message[1] !='-') ||2351!isdigit(message[2]) || !isdigit(message[3]) ||2352!isdigit(message[4]) || !isdigit(message[5]))2353return0;/* corrupt? */2354 email_end[1] ='\0';2355 tz =strtol(message +1, NULL,10);2356if(message[6] !='\t')2357 message +=6;2358else2359 message +=7;2360returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2361}23622363static char*find_beginning_of_line(char*bob,char*scan)2364{2365while(bob < scan && *(--scan) !='\n')2366;/* keep scanning backwards */2367/*2368 * Return either beginning of the buffer, or LF at the end of2369 * the previous line.2370 */2371return scan;2372}23732374static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2375const char*refname,2376 each_reflog_ent_fn fn,2377void*cb_data)2378{2379struct files_ref_store *refs =2380files_downcast(ref_store, REF_STORE_READ,2381"for_each_reflog_ent_reverse");2382struct strbuf sb = STRBUF_INIT;2383FILE*logfp;2384long pos;2385int ret =0, at_tail =1;23862387files_reflog_path(refs, &sb, refname);2388 logfp =fopen(sb.buf,"r");2389strbuf_release(&sb);2390if(!logfp)2391return-1;23922393/* Jump to the end */2394if(fseek(logfp,0, SEEK_END) <0)2395 ret =error("cannot seek back reflog for%s:%s",2396 refname,strerror(errno));2397 pos =ftell(logfp);2398while(!ret &&0< pos) {2399int cnt;2400size_t nread;2401char buf[BUFSIZ];2402char*endp, *scanp;24032404/* Fill next block from the end */2405 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2406if(fseek(logfp, pos - cnt, SEEK_SET)) {2407 ret =error("cannot seek back reflog for%s:%s",2408 refname,strerror(errno));2409break;2410}2411 nread =fread(buf, cnt,1, logfp);2412if(nread !=1) {2413 ret =error("cannot read%dbytes from reflog for%s:%s",2414 cnt, refname,strerror(errno));2415break;2416}2417 pos -= cnt;24182419 scanp = endp = buf + cnt;2420if(at_tail && scanp[-1] =='\n')2421/* Looking at the final LF at the end of the file */2422 scanp--;2423 at_tail =0;24242425while(buf < scanp) {2426/*2427 * terminating LF of the previous line, or the beginning2428 * of the buffer.2429 */2430char*bp;24312432 bp =find_beginning_of_line(buf, scanp);24332434if(*bp =='\n') {2435/*2436 * The newline is the end of the previous line,2437 * so we know we have complete line starting2438 * at (bp + 1). Prefix it onto any prior data2439 * we collected for the line and process it.2440 */2441strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2442 scanp = bp;2443 endp = bp +1;2444 ret =show_one_reflog_ent(&sb, fn, cb_data);2445strbuf_reset(&sb);2446if(ret)2447break;2448}else if(!pos) {2449/*2450 * We are at the start of the buffer, and the2451 * start of the file; there is no previous2452 * line, and we have everything for this one.2453 * Process it, and we can end the loop.2454 */2455strbuf_splice(&sb,0,0, buf, endp - buf);2456 ret =show_one_reflog_ent(&sb, fn, cb_data);2457strbuf_reset(&sb);2458break;2459}24602461if(bp == buf) {2462/*2463 * We are at the start of the buffer, and there2464 * is more file to read backwards. Which means2465 * we are in the middle of a line. Note that we2466 * may get here even if *bp was a newline; that2467 * just means we are at the exact end of the2468 * previous line, rather than some spot in the2469 * middle.2470 *2471 * Save away what we have to be combined with2472 * the data from the next read.2473 */2474strbuf_splice(&sb,0,0, buf, endp - buf);2475break;2476}2477}24782479}2480if(!ret && sb.len)2481die("BUG: reverse reflog parser had leftover data");24822483fclose(logfp);2484strbuf_release(&sb);2485return ret;2486}24872488static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2489const char*refname,2490 each_reflog_ent_fn fn,void*cb_data)2491{2492struct files_ref_store *refs =2493files_downcast(ref_store, REF_STORE_READ,2494"for_each_reflog_ent");2495FILE*logfp;2496struct strbuf sb = STRBUF_INIT;2497int ret =0;24982499files_reflog_path(refs, &sb, refname);2500 logfp =fopen(sb.buf,"r");2501strbuf_release(&sb);2502if(!logfp)2503return-1;25042505while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2506 ret =show_one_reflog_ent(&sb, fn, cb_data);2507fclose(logfp);2508strbuf_release(&sb);2509return ret;2510}25112512struct files_reflog_iterator {2513struct ref_iterator base;25142515struct ref_store *ref_store;2516struct dir_iterator *dir_iterator;2517struct object_id oid;2518};25192520static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2521{2522struct files_reflog_iterator *iter =2523(struct files_reflog_iterator *)ref_iterator;2524struct dir_iterator *diter = iter->dir_iterator;2525int ok;25262527while((ok =dir_iterator_advance(diter)) == ITER_OK) {2528int flags;25292530if(!S_ISREG(diter->st.st_mode))2531continue;2532if(diter->basename[0] =='.')2533continue;2534if(ends_with(diter->basename,".lock"))2535continue;25362537if(refs_read_ref_full(iter->ref_store,2538 diter->relative_path,0,2539 iter->oid.hash, &flags)) {2540error("bad ref for%s", diter->path.buf);2541continue;2542}25432544 iter->base.refname = diter->relative_path;2545 iter->base.oid = &iter->oid;2546 iter->base.flags = flags;2547return ITER_OK;2548}25492550 iter->dir_iterator = NULL;2551if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2552 ok = ITER_ERROR;2553return ok;2554}25552556static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2557struct object_id *peeled)2558{2559die("BUG: ref_iterator_peel() called for reflog_iterator");2560}25612562static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2563{2564struct files_reflog_iterator *iter =2565(struct files_reflog_iterator *)ref_iterator;2566int ok = ITER_DONE;25672568if(iter->dir_iterator)2569 ok =dir_iterator_abort(iter->dir_iterator);25702571base_ref_iterator_free(ref_iterator);2572return ok;2573}25742575static struct ref_iterator_vtable files_reflog_iterator_vtable = {2576 files_reflog_iterator_advance,2577 files_reflog_iterator_peel,2578 files_reflog_iterator_abort2579};25802581static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2582{2583struct files_ref_store *refs =2584files_downcast(ref_store, REF_STORE_READ,2585"reflog_iterator_begin");2586struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2587struct ref_iterator *ref_iterator = &iter->base;2588struct strbuf sb = STRBUF_INIT;25892590base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2591files_reflog_path(refs, &sb, NULL);2592 iter->dir_iterator =dir_iterator_begin(sb.buf);2593 iter->ref_store = ref_store;2594strbuf_release(&sb);2595return ref_iterator;2596}25972598/*2599 * If update is a direct update of head_ref (the reference pointed to2600 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2601 */2602static intsplit_head_update(struct ref_update *update,2603struct ref_transaction *transaction,2604const char*head_ref,2605struct string_list *affected_refnames,2606struct strbuf *err)2607{2608struct string_list_item *item;2609struct ref_update *new_update;26102611if((update->flags & REF_LOG_ONLY) ||2612(update->flags & REF_ISPRUNING) ||2613(update->flags & REF_UPDATE_VIA_HEAD))2614return0;26152616if(strcmp(update->refname, head_ref))2617return0;26182619/*2620 * First make sure that HEAD is not already in the2621 * transaction. This insertion is O(N) in the transaction2622 * size, but it happens at most once per transaction.2623 */2624 item =string_list_insert(affected_refnames,"HEAD");2625if(item->util) {2626/* An entry already existed */2627strbuf_addf(err,2628"multiple updates for 'HEAD' (including one "2629"via its referent '%s') are not allowed",2630 update->refname);2631return TRANSACTION_NAME_CONFLICT;2632}26332634 new_update =ref_transaction_add_update(2635 transaction,"HEAD",2636 update->flags | REF_LOG_ONLY | REF_NODEREF,2637 update->new_oid.hash, update->old_oid.hash,2638 update->msg);26392640 item->util = new_update;26412642return0;2643}26442645/*2646 * update is for a symref that points at referent and doesn't have2647 * REF_NODEREF set. Split it into two updates:2648 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2649 * - A new, separate update for the referent reference2650 * Note that the new update will itself be subject to splitting when2651 * the iteration gets to it.2652 */2653static intsplit_symref_update(struct files_ref_store *refs,2654struct ref_update *update,2655const char*referent,2656struct ref_transaction *transaction,2657struct string_list *affected_refnames,2658struct strbuf *err)2659{2660struct string_list_item *item;2661struct ref_update *new_update;2662unsigned int new_flags;26632664/*2665 * First make sure that referent is not already in the2666 * transaction. This insertion is O(N) in the transaction2667 * size, but it happens at most once per symref in a2668 * transaction.2669 */2670 item =string_list_insert(affected_refnames, referent);2671if(item->util) {2672/* An entry already existed */2673strbuf_addf(err,2674"multiple updates for '%s' (including one "2675"via symref '%s') are not allowed",2676 referent, update->refname);2677return TRANSACTION_NAME_CONFLICT;2678}26792680 new_flags = update->flags;2681if(!strcmp(update->refname,"HEAD")) {2682/*2683 * Record that the new update came via HEAD, so that2684 * when we process it, split_head_update() doesn't try2685 * to add another reflog update for HEAD. Note that2686 * this bit will be propagated if the new_update2687 * itself needs to be split.2688 */2689 new_flags |= REF_UPDATE_VIA_HEAD;2690}26912692 new_update =ref_transaction_add_update(2693 transaction, referent, new_flags,2694 update->new_oid.hash, update->old_oid.hash,2695 update->msg);26962697 new_update->parent_update = update;26982699/*2700 * Change the symbolic ref update to log only. Also, it2701 * doesn't need to check its old SHA-1 value, as that will be2702 * done when new_update is processed.2703 */2704 update->flags |= REF_LOG_ONLY | REF_NODEREF;2705 update->flags &= ~REF_HAVE_OLD;27062707 item->util = new_update;27082709return0;2710}27112712/*2713 * Return the refname under which update was originally requested.2714 */2715static const char*original_update_refname(struct ref_update *update)2716{2717while(update->parent_update)2718 update = update->parent_update;27192720return update->refname;2721}27222723/*2724 * Check whether the REF_HAVE_OLD and old_oid values stored in update2725 * are consistent with oid, which is the reference's current value. If2726 * everything is OK, return 0; otherwise, write an error message to2727 * err and return -1.2728 */2729static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2730struct strbuf *err)2731{2732if(!(update->flags & REF_HAVE_OLD) ||2733!oidcmp(oid, &update->old_oid))2734return0;27352736if(is_null_oid(&update->old_oid))2737strbuf_addf(err,"cannot lock ref '%s': "2738"reference already exists",2739original_update_refname(update));2740else if(is_null_oid(oid))2741strbuf_addf(err,"cannot lock ref '%s': "2742"reference is missing but expected%s",2743original_update_refname(update),2744oid_to_hex(&update->old_oid));2745else2746strbuf_addf(err,"cannot lock ref '%s': "2747"is at%sbut expected%s",2748original_update_refname(update),2749oid_to_hex(oid),2750oid_to_hex(&update->old_oid));27512752return-1;2753}27542755/*2756 * Prepare for carrying out update:2757 * - Lock the reference referred to by update.2758 * - Read the reference under lock.2759 * - Check that its old SHA-1 value (if specified) is correct, and in2760 * any case record it in update->lock->old_oid for later use when2761 * writing the reflog.2762 * - If it is a symref update without REF_NODEREF, split it up into a2763 * REF_LOG_ONLY update of the symref and add a separate update for2764 * the referent to transaction.2765 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2766 * update of HEAD.2767 */2768static intlock_ref_for_update(struct files_ref_store *refs,2769struct ref_update *update,2770struct ref_transaction *transaction,2771const char*head_ref,2772struct string_list *affected_refnames,2773struct strbuf *err)2774{2775struct strbuf referent = STRBUF_INIT;2776int mustexist = (update->flags & REF_HAVE_OLD) &&2777!is_null_oid(&update->old_oid);2778int ret;2779struct ref_lock *lock;27802781files_assert_main_repository(refs,"lock_ref_for_update");27822783if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2784 update->flags |= REF_DELETING;27852786if(head_ref) {2787 ret =split_head_update(update, transaction, head_ref,2788 affected_refnames, err);2789if(ret)2790return ret;2791}27922793 ret =lock_raw_ref(refs, update->refname, mustexist,2794 affected_refnames, NULL,2795&lock, &referent,2796&update->type, err);2797if(ret) {2798char*reason;27992800 reason =strbuf_detach(err, NULL);2801strbuf_addf(err,"cannot lock ref '%s':%s",2802original_update_refname(update), reason);2803free(reason);2804return ret;2805}28062807 update->backend_data = lock;28082809if(update->type & REF_ISSYMREF) {2810if(update->flags & REF_NODEREF) {2811/*2812 * We won't be reading the referent as part of2813 * the transaction, so we have to read it here2814 * to record and possibly check old_sha1:2815 */2816if(refs_read_ref_full(&refs->base,2817 referent.buf,0,2818 lock->old_oid.hash, NULL)) {2819if(update->flags & REF_HAVE_OLD) {2820strbuf_addf(err,"cannot lock ref '%s': "2821"error reading reference",2822original_update_refname(update));2823return-1;2824}2825}else if(check_old_oid(update, &lock->old_oid, err)) {2826return TRANSACTION_GENERIC_ERROR;2827}2828}else{2829/*2830 * Create a new update for the reference this2831 * symref is pointing at. Also, we will record2832 * and verify old_sha1 for this update as part2833 * of processing the split-off update, so we2834 * don't have to do it here.2835 */2836 ret =split_symref_update(refs, update,2837 referent.buf, transaction,2838 affected_refnames, err);2839if(ret)2840return ret;2841}2842}else{2843struct ref_update *parent_update;28442845if(check_old_oid(update, &lock->old_oid, err))2846return TRANSACTION_GENERIC_ERROR;28472848/*2849 * If this update is happening indirectly because of a2850 * symref update, record the old SHA-1 in the parent2851 * update:2852 */2853for(parent_update = update->parent_update;2854 parent_update;2855 parent_update = parent_update->parent_update) {2856struct ref_lock *parent_lock = parent_update->backend_data;2857oidcpy(&parent_lock->old_oid, &lock->old_oid);2858}2859}28602861if((update->flags & REF_HAVE_NEW) &&2862!(update->flags & REF_DELETING) &&2863!(update->flags & REF_LOG_ONLY)) {2864if(!(update->type & REF_ISSYMREF) &&2865!oidcmp(&lock->old_oid, &update->new_oid)) {2866/*2867 * The reference already has the desired2868 * value, so we don't need to write it.2869 */2870}else if(write_ref_to_lockfile(lock, &update->new_oid,2871 err)) {2872char*write_err =strbuf_detach(err, NULL);28732874/*2875 * The lock was freed upon failure of2876 * write_ref_to_lockfile():2877 */2878 update->backend_data = NULL;2879strbuf_addf(err,2880"cannot update ref '%s':%s",2881 update->refname, write_err);2882free(write_err);2883return TRANSACTION_GENERIC_ERROR;2884}else{2885 update->flags |= REF_NEEDS_COMMIT;2886}2887}2888if(!(update->flags & REF_NEEDS_COMMIT)) {2889/*2890 * We didn't call write_ref_to_lockfile(), so2891 * the lockfile is still open. Close it to2892 * free up the file descriptor:2893 */2894if(close_ref(lock)) {2895strbuf_addf(err,"couldn't close '%s.lock'",2896 update->refname);2897return TRANSACTION_GENERIC_ERROR;2898}2899}2900return0;2901}29022903/*2904 * Unlock any references in `transaction` that are still locked, and2905 * mark the transaction closed.2906 */2907static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2908{2909size_t i;29102911for(i =0; i < transaction->nr; i++) {2912struct ref_update *update = transaction->updates[i];2913struct ref_lock *lock = update->backend_data;29142915if(lock) {2916unlock_ref(lock);2917 update->backend_data = NULL;2918}2919}29202921 transaction->state = REF_TRANSACTION_CLOSED;2922}29232924static intfiles_transaction_prepare(struct ref_store *ref_store,2925struct ref_transaction *transaction,2926struct strbuf *err)2927{2928struct files_ref_store *refs =2929files_downcast(ref_store, REF_STORE_WRITE,2930"ref_transaction_prepare");2931size_t i;2932int ret =0;2933struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2934char*head_ref = NULL;2935int head_type;2936struct object_id head_oid;29372938assert(err);29392940if(!transaction->nr)2941goto cleanup;29422943/*2944 * Fail if a refname appears more than once in the2945 * transaction. (If we end up splitting up any updates using2946 * split_symref_update() or split_head_update(), those2947 * functions will check that the new updates don't have the2948 * same refname as any existing ones.)2949 */2950for(i =0; i < transaction->nr; i++) {2951struct ref_update *update = transaction->updates[i];2952struct string_list_item *item =2953string_list_append(&affected_refnames, update->refname);29542955/*2956 * We store a pointer to update in item->util, but at2957 * the moment we never use the value of this field2958 * except to check whether it is non-NULL.2959 */2960 item->util = update;2961}2962string_list_sort(&affected_refnames);2963if(ref_update_reject_duplicates(&affected_refnames, err)) {2964 ret = TRANSACTION_GENERIC_ERROR;2965goto cleanup;2966}29672968/*2969 * Special hack: If a branch is updated directly and HEAD2970 * points to it (may happen on the remote side of a push2971 * for example) then logically the HEAD reflog should be2972 * updated too.2973 *2974 * A generic solution would require reverse symref lookups,2975 * but finding all symrefs pointing to a given branch would be2976 * rather costly for this rare event (the direct update of a2977 * branch) to be worth it. So let's cheat and check with HEAD2978 * only, which should cover 99% of all usage scenarios (even2979 * 100% of the default ones).2980 *2981 * So if HEAD is a symbolic reference, then record the name of2982 * the reference that it points to. If we see an update of2983 * head_ref within the transaction, then split_head_update()2984 * arranges for the reflog of HEAD to be updated, too.2985 */2986 head_ref =refs_resolve_refdup(ref_store,"HEAD",2987 RESOLVE_REF_NO_RECURSE,2988 head_oid.hash, &head_type);29892990if(head_ref && !(head_type & REF_ISSYMREF)) {2991free(head_ref);2992 head_ref = NULL;2993}29942995/*2996 * Acquire all locks, verify old values if provided, check2997 * that new values are valid, and write new values to the2998 * lockfiles, ready to be activated. Only keep one lockfile2999 * open at a time to avoid running out of file descriptors.3000 * Note that lock_ref_for_update() might append more updates3001 * to the transaction.3002 */3003for(i =0; i < transaction->nr; i++) {3004struct ref_update *update = transaction->updates[i];30053006 ret =lock_ref_for_update(refs, update, transaction,3007 head_ref, &affected_refnames, err);3008if(ret)3009break;3010}30113012cleanup:3013free(head_ref);3014string_list_clear(&affected_refnames,0);30153016if(ret)3017files_transaction_cleanup(transaction);3018else3019 transaction->state = REF_TRANSACTION_PREPARED;30203021return ret;3022}30233024static intfiles_transaction_finish(struct ref_store *ref_store,3025struct ref_transaction *transaction,3026struct strbuf *err)3027{3028struct files_ref_store *refs =3029files_downcast(ref_store,0,"ref_transaction_finish");3030size_t i;3031int ret =0;3032struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3033struct string_list_item *ref_to_delete;3034struct strbuf sb = STRBUF_INIT;30353036assert(err);30373038if(!transaction->nr) {3039 transaction->state = REF_TRANSACTION_CLOSED;3040return0;3041}30423043/* Perform updates first so live commits remain referenced */3044for(i =0; i < transaction->nr; i++) {3045struct ref_update *update = transaction->updates[i];3046struct ref_lock *lock = update->backend_data;30473048if(update->flags & REF_NEEDS_COMMIT ||3049 update->flags & REF_LOG_ONLY) {3050if(files_log_ref_write(refs,3051 lock->ref_name,3052&lock->old_oid,3053&update->new_oid,3054 update->msg, update->flags,3055 err)) {3056char*old_msg =strbuf_detach(err, NULL);30573058strbuf_addf(err,"cannot update the ref '%s':%s",3059 lock->ref_name, old_msg);3060free(old_msg);3061unlock_ref(lock);3062 update->backend_data = NULL;3063 ret = TRANSACTION_GENERIC_ERROR;3064goto cleanup;3065}3066}3067if(update->flags & REF_NEEDS_COMMIT) {3068clear_loose_ref_cache(refs);3069if(commit_ref(lock)) {3070strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3071unlock_ref(lock);3072 update->backend_data = NULL;3073 ret = TRANSACTION_GENERIC_ERROR;3074goto cleanup;3075}3076}3077}3078/* Perform deletes now that updates are safely completed */3079for(i =0; i < transaction->nr; i++) {3080struct ref_update *update = transaction->updates[i];3081struct ref_lock *lock = update->backend_data;30823083if(update->flags & REF_DELETING &&3084!(update->flags & REF_LOG_ONLY)) {3085if(!(update->type & REF_ISPACKED) ||3086 update->type & REF_ISSYMREF) {3087/* It is a loose reference. */3088strbuf_reset(&sb);3089files_ref_path(refs, &sb, lock->ref_name);3090if(unlink_or_msg(sb.buf, err)) {3091 ret = TRANSACTION_GENERIC_ERROR;3092goto cleanup;3093}3094 update->flags |= REF_DELETED_LOOSE;3095}30963097if(!(update->flags & REF_ISPRUNING))3098string_list_append(&refs_to_delete,3099 lock->ref_name);3100}3101}31023103if(repack_without_refs(refs, &refs_to_delete, err)) {3104 ret = TRANSACTION_GENERIC_ERROR;3105goto cleanup;3106}31073108/* Delete the reflogs of any references that were deleted: */3109for_each_string_list_item(ref_to_delete, &refs_to_delete) {3110strbuf_reset(&sb);3111files_reflog_path(refs, &sb, ref_to_delete->string);3112if(!unlink_or_warn(sb.buf))3113try_remove_empty_parents(refs, ref_to_delete->string,3114 REMOVE_EMPTY_PARENTS_REFLOG);3115}31163117clear_loose_ref_cache(refs);31183119cleanup:3120files_transaction_cleanup(transaction);31213122for(i =0; i < transaction->nr; i++) {3123struct ref_update *update = transaction->updates[i];31243125if(update->flags & REF_DELETED_LOOSE) {3126/*3127 * The loose reference was deleted. Delete any3128 * empty parent directories. (Note that this3129 * can only work because we have already3130 * removed the lockfile.)3131 */3132try_remove_empty_parents(refs, update->refname,3133 REMOVE_EMPTY_PARENTS_REF);3134}3135}31363137strbuf_release(&sb);3138string_list_clear(&refs_to_delete,0);3139return ret;3140}31413142static intfiles_transaction_abort(struct ref_store *ref_store,3143struct ref_transaction *transaction,3144struct strbuf *err)3145{3146files_transaction_cleanup(transaction);3147return0;3148}31493150static intref_present(const char*refname,3151const struct object_id *oid,int flags,void*cb_data)3152{3153struct string_list *affected_refnames = cb_data;31543155returnstring_list_has_string(affected_refnames, refname);3156}31573158static intfiles_initial_transaction_commit(struct ref_store *ref_store,3159struct ref_transaction *transaction,3160struct strbuf *err)3161{3162struct files_ref_store *refs =3163files_downcast(ref_store, REF_STORE_WRITE,3164"initial_ref_transaction_commit");3165size_t i;3166int ret =0;3167struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31683169assert(err);31703171if(transaction->state != REF_TRANSACTION_OPEN)3172die("BUG: commit called for transaction that is not open");31733174/* Fail if a refname appears more than once in the transaction: */3175for(i =0; i < transaction->nr; i++)3176string_list_append(&affected_refnames,3177 transaction->updates[i]->refname);3178string_list_sort(&affected_refnames);3179if(ref_update_reject_duplicates(&affected_refnames, err)) {3180 ret = TRANSACTION_GENERIC_ERROR;3181goto cleanup;3182}31833184/*3185 * It's really undefined to call this function in an active3186 * repository or when there are existing references: we are3187 * only locking and changing packed-refs, so (1) any3188 * simultaneous processes might try to change a reference at3189 * the same time we do, and (2) any existing loose versions of3190 * the references that we are setting would have precedence3191 * over our values. But some remote helpers create the remote3192 * "HEAD" and "master" branches before calling this function,3193 * so here we really only check that none of the references3194 * that we are creating already exists.3195 */3196if(refs_for_each_rawref(&refs->base, ref_present,3197&affected_refnames))3198die("BUG: initial ref transaction called with existing refs");31993200for(i =0; i < transaction->nr; i++) {3201struct ref_update *update = transaction->updates[i];32023203if((update->flags & REF_HAVE_OLD) &&3204!is_null_oid(&update->old_oid))3205die("BUG: initial ref transaction with old_sha1 set");3206if(refs_verify_refname_available(&refs->base, update->refname,3207&affected_refnames, NULL,3208 err)) {3209 ret = TRANSACTION_NAME_CONFLICT;3210goto cleanup;3211}3212}32133214if(lock_packed_refs(refs->packed_ref_store,0)) {3215strbuf_addf(err,"unable to lock packed-refs file:%s",3216strerror(errno));3217 ret = TRANSACTION_GENERIC_ERROR;3218goto cleanup;3219}32203221for(i =0; i < transaction->nr; i++) {3222struct ref_update *update = transaction->updates[i];32233224if((update->flags & REF_HAVE_NEW) &&3225!is_null_oid(&update->new_oid))3226add_packed_ref(refs->packed_ref_store, update->refname,3227&update->new_oid);3228}32293230if(commit_packed_refs(refs->packed_ref_store)) {3231strbuf_addf(err,"unable to commit packed-refs file:%s",3232strerror(errno));3233 ret = TRANSACTION_GENERIC_ERROR;3234goto cleanup;3235}32363237cleanup:3238 transaction->state = REF_TRANSACTION_CLOSED;3239string_list_clear(&affected_refnames,0);3240return ret;3241}32423243struct expire_reflog_cb {3244unsigned int flags;3245 reflog_expiry_should_prune_fn *should_prune_fn;3246void*policy_cb;3247FILE*newlog;3248struct object_id last_kept_oid;3249};32503251static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3252const char*email, timestamp_t timestamp,int tz,3253const char*message,void*cb_data)3254{3255struct expire_reflog_cb *cb = cb_data;3256struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32573258if(cb->flags & EXPIRE_REFLOGS_REWRITE)3259 ooid = &cb->last_kept_oid;32603261if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3262 message, policy_cb)) {3263if(!cb->newlog)3264printf("would prune%s", message);3265else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3266printf("prune%s", message);3267}else{3268if(cb->newlog) {3269fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3270oid_to_hex(ooid),oid_to_hex(noid),3271 email, timestamp, tz, message);3272oidcpy(&cb->last_kept_oid, noid);3273}3274if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3275printf("keep%s", message);3276}3277return0;3278}32793280static intfiles_reflog_expire(struct ref_store *ref_store,3281const char*refname,const unsigned char*sha1,3282unsigned int flags,3283 reflog_expiry_prepare_fn prepare_fn,3284 reflog_expiry_should_prune_fn should_prune_fn,3285 reflog_expiry_cleanup_fn cleanup_fn,3286void*policy_cb_data)3287{3288struct files_ref_store *refs =3289files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3290static struct lock_file reflog_lock;3291struct expire_reflog_cb cb;3292struct ref_lock *lock;3293struct strbuf log_file_sb = STRBUF_INIT;3294char*log_file;3295int status =0;3296int type;3297struct strbuf err = STRBUF_INIT;3298struct object_id oid;32993300memset(&cb,0,sizeof(cb));3301 cb.flags = flags;3302 cb.policy_cb = policy_cb_data;3303 cb.should_prune_fn = should_prune_fn;33043305/*3306 * The reflog file is locked by holding the lock on the3307 * reference itself, plus we might need to update the3308 * reference if --updateref was specified:3309 */3310 lock =lock_ref_sha1_basic(refs, refname, sha1,3311 NULL, NULL, REF_NODEREF,3312&type, &err);3313if(!lock) {3314error("cannot lock ref '%s':%s", refname, err.buf);3315strbuf_release(&err);3316return-1;3317}3318if(!refs_reflog_exists(ref_store, refname)) {3319unlock_ref(lock);3320return0;3321}33223323files_reflog_path(refs, &log_file_sb, refname);3324 log_file =strbuf_detach(&log_file_sb, NULL);3325if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3326/*3327 * Even though holding $GIT_DIR/logs/$reflog.lock has3328 * no locking implications, we use the lock_file3329 * machinery here anyway because it does a lot of the3330 * work we need, including cleaning up if the program3331 * exits unexpectedly.3332 */3333if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3334struct strbuf err = STRBUF_INIT;3335unable_to_lock_message(log_file, errno, &err);3336error("%s", err.buf);3337strbuf_release(&err);3338goto failure;3339}3340 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3341if(!cb.newlog) {3342error("cannot fdopen%s(%s)",3343get_lock_file_path(&reflog_lock),strerror(errno));3344goto failure;3345}3346}33473348hashcpy(oid.hash, sha1);33493350(*prepare_fn)(refname, &oid, cb.policy_cb);3351refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3352(*cleanup_fn)(cb.policy_cb);33533354if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3355/*3356 * It doesn't make sense to adjust a reference pointed3357 * to by a symbolic ref based on expiring entries in3358 * the symbolic reference's reflog. Nor can we update3359 * a reference if there are no remaining reflog3360 * entries.3361 */3362int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3363!(type & REF_ISSYMREF) &&3364!is_null_oid(&cb.last_kept_oid);33653366if(close_lock_file(&reflog_lock)) {3367 status |=error("couldn't write%s:%s", log_file,3368strerror(errno));3369}else if(update &&3370(write_in_full(get_lock_file_fd(lock->lk),3371oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3372write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3373close_ref(lock) <0)) {3374 status |=error("couldn't write%s",3375get_lock_file_path(lock->lk));3376rollback_lock_file(&reflog_lock);3377}else if(commit_lock_file(&reflog_lock)) {3378 status |=error("unable to write reflog '%s' (%s)",3379 log_file,strerror(errno));3380}else if(update &&commit_ref(lock)) {3381 status |=error("couldn't set%s", lock->ref_name);3382}3383}3384free(log_file);3385unlock_ref(lock);3386return status;33873388 failure:3389rollback_lock_file(&reflog_lock);3390free(log_file);3391unlock_ref(lock);3392return-1;3393}33943395static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3396{3397struct files_ref_store *refs =3398files_downcast(ref_store, REF_STORE_WRITE,"init_db");3399struct strbuf sb = STRBUF_INIT;34003401/*3402 * Create .git/refs/{heads,tags}3403 */3404files_ref_path(refs, &sb,"refs/heads");3405safe_create_dir(sb.buf,1);34063407strbuf_reset(&sb);3408files_ref_path(refs, &sb,"refs/tags");3409safe_create_dir(sb.buf,1);34103411strbuf_release(&sb);3412return0;3413}34143415struct ref_storage_be refs_be_files = {3416 NULL,3417"files",3418 files_ref_store_create,3419 files_init_db,3420 files_transaction_prepare,3421 files_transaction_finish,3422 files_transaction_abort,3423 files_initial_transaction_commit,34243425 files_pack_refs,3426 files_peel_ref,3427 files_create_symref,3428 files_delete_refs,3429 files_rename_ref,34303431 files_ref_iterator_begin,3432 files_read_raw_ref,34333434 files_reflog_iterator_begin,3435 files_for_each_reflog_ent,3436 files_for_each_reflog_ent_reverse,3437 files_reflog_exists,3438 files_create_reflog,3439 files_delete_reflog,3440 files_reflog_expire3441};