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/* 58 * A cache of the values read from the `packed-refs` file, if 59 * it might still be current; otherwise, NULL. 60 */ 61struct packed_ref_cache *cache; 62}; 63 64static struct packed_ref_store *packed_ref_store_create(unsigned int store_flags) 65{ 66struct packed_ref_store *refs =xcalloc(1,sizeof(*refs)); 67 68 refs->store_flags = store_flags; 69return refs; 70} 71 72/* 73 * Future: need to be in "struct repository" 74 * when doing a full libification. 75 */ 76struct files_ref_store { 77struct ref_store base; 78unsigned int store_flags; 79 80char*gitdir; 81char*gitcommondir; 82char*packed_refs_path; 83 84struct ref_cache *loose; 85 86/* 87 * Lock used for the "packed-refs" file. Note that this (and 88 * thus the enclosing `files_ref_store`) must not be freed. 89 */ 90struct lock_file packed_refs_lock; 91 92struct packed_ref_store *packed_ref_store; 93}; 94 95/* 96 * Increment the reference count of *packed_refs. 97 */ 98static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 99{ 100 packed_refs->referrers++; 101} 102 103/* 104 * Decrease the reference count of *packed_refs. If it goes to zero, 105 * free *packed_refs and return true; otherwise return false. 106 */ 107static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 108{ 109if(!--packed_refs->referrers) { 110free_ref_cache(packed_refs->cache); 111stat_validity_clear(&packed_refs->validity); 112free(packed_refs); 113return1; 114}else{ 115return0; 116} 117} 118 119static voidclear_packed_ref_cache(struct files_ref_store *refs) 120{ 121if(refs->packed_ref_store->cache) { 122struct packed_ref_cache *packed_refs = refs->packed_ref_store->cache; 123 124if(is_lock_file_locked(&refs->packed_refs_lock)) 125die("BUG: packed-ref cache cleared while locked"); 126 refs->packed_ref_store->cache = NULL; 127release_packed_ref_cache(packed_refs); 128} 129} 130 131static voidclear_loose_ref_cache(struct files_ref_store *refs) 132{ 133if(refs->loose) { 134free_ref_cache(refs->loose); 135 refs->loose = NULL; 136} 137} 138 139/* 140 * Create a new submodule ref cache and add it to the internal 141 * set of caches. 142 */ 143static struct ref_store *files_ref_store_create(const char*gitdir, 144unsigned int flags) 145{ 146struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 147struct ref_store *ref_store = (struct ref_store *)refs; 148struct strbuf sb = STRBUF_INIT; 149 150base_ref_store_init(ref_store, &refs_be_files); 151 refs->store_flags = flags; 152 153 refs->gitdir =xstrdup(gitdir); 154get_common_dir_noenv(&sb, gitdir); 155 refs->gitcommondir =strbuf_detach(&sb, NULL); 156strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 157 refs->packed_refs_path =strbuf_detach(&sb, NULL); 158 refs->packed_ref_store =packed_ref_store_create(flags); 159 160return ref_store; 161} 162 163/* 164 * Die if refs is not the main ref store. caller is used in any 165 * necessary error messages. 166 */ 167static voidfiles_assert_main_repository(struct files_ref_store *refs, 168const char*caller) 169{ 170if(refs->store_flags & REF_STORE_MAIN) 171return; 172 173die("BUG: operation%sonly allowed for main ref store", caller); 174} 175 176/* 177 * Downcast ref_store to files_ref_store. Die if ref_store is not a 178 * files_ref_store. required_flags is compared with ref_store's 179 * store_flags to ensure the ref_store has all required capabilities. 180 * "caller" is used in any necessary error messages. 181 */ 182static struct files_ref_store *files_downcast(struct ref_store *ref_store, 183unsigned int required_flags, 184const char*caller) 185{ 186struct files_ref_store *refs; 187 188if(ref_store->be != &refs_be_files) 189die("BUG: ref_store is type\"%s\"not\"files\"in%s", 190 ref_store->be->name, caller); 191 192 refs = (struct files_ref_store *)ref_store; 193 194if((refs->store_flags & required_flags) != required_flags) 195die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 196 caller, required_flags, refs->store_flags); 197 198return refs; 199} 200 201/* The length of a peeled reference line in packed-refs, including EOL: */ 202#define PEELED_LINE_LENGTH 42 203 204/* 205 * The packed-refs header line that we write out. Perhaps other 206 * traits will be added later. The trailing space is required. 207 */ 208static const char PACKED_REFS_HEADER[] = 209"# pack-refs with: peeled fully-peeled\n"; 210 211/* 212 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 213 * Return a pointer to the refname within the line (null-terminated), 214 * or NULL if there was a problem. 215 */ 216static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 217{ 218const char*ref; 219 220if(parse_oid_hex(line->buf, oid, &ref) <0) 221return NULL; 222if(!isspace(*ref++)) 223return NULL; 224 225if(isspace(*ref)) 226return NULL; 227 228if(line->buf[line->len -1] !='\n') 229return NULL; 230 line->buf[--line->len] =0; 231 232return ref; 233} 234 235/* 236 * Read from `packed_refs_file` into a newly-allocated 237 * `packed_ref_cache` and return it. The return value will already 238 * have its reference count incremented. 239 * 240 * A comment line of the form "# pack-refs with: " may contain zero or 241 * more traits. We interpret the traits as follows: 242 * 243 * No traits: 244 * 245 * Probably no references are peeled. But if the file contains a 246 * peeled value for a reference, we will use it. 247 * 248 * peeled: 249 * 250 * References under "refs/tags/", if they *can* be peeled, *are* 251 * peeled in this file. References outside of "refs/tags/" are 252 * probably not peeled even if they could have been, but if we find 253 * a peeled value for such a reference we will use it. 254 * 255 * fully-peeled: 256 * 257 * All references in the file that can be peeled are peeled. 258 * Inversely (and this is more important), any references in the 259 * file for which no peeled value is recorded is not peelable. This 260 * trait should typically be written alongside "peeled" for 261 * compatibility with older clients, but we do not require it 262 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 263 */ 264static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 265{ 266FILE*f; 267struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 268struct ref_entry *last = NULL; 269struct strbuf line = STRBUF_INIT; 270enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 271struct ref_dir *dir; 272 273acquire_packed_ref_cache(packed_refs); 274 packed_refs->cache =create_ref_cache(NULL, NULL); 275 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 276 277 f =fopen(packed_refs_file,"r"); 278if(!f) { 279if(errno == ENOENT) { 280/* 281 * This is OK; it just means that no 282 * "packed-refs" file has been written yet, 283 * which is equivalent to it being empty. 284 */ 285return packed_refs; 286}else{ 287die_errno("couldn't read%s", packed_refs_file); 288} 289} 290 291stat_validity_update(&packed_refs->validity,fileno(f)); 292 293 dir =get_ref_dir(packed_refs->cache->root); 294while(strbuf_getwholeline(&line, f,'\n') != EOF) { 295struct object_id oid; 296const char*refname; 297const char*traits; 298 299if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 300if(strstr(traits," fully-peeled ")) 301 peeled = PEELED_FULLY; 302else if(strstr(traits," peeled ")) 303 peeled = PEELED_TAGS; 304/* perhaps other traits later as well */ 305continue; 306} 307 308 refname =parse_ref_line(&line, &oid); 309if(refname) { 310int flag = REF_ISPACKED; 311 312if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 313if(!refname_is_safe(refname)) 314die("packed refname is dangerous:%s", refname); 315oidclr(&oid); 316 flag |= REF_BAD_NAME | REF_ISBROKEN; 317} 318 last =create_ref_entry(refname, &oid, flag); 319if(peeled == PEELED_FULLY || 320(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 321 last->flag |= REF_KNOWS_PEELED; 322add_ref_entry(dir, last); 323continue; 324} 325if(last && 326 line.buf[0] =='^'&& 327 line.len == PEELED_LINE_LENGTH && 328 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 329!get_oid_hex(line.buf +1, &oid)) { 330oidcpy(&last->u.value.peeled, &oid); 331/* 332 * Regardless of what the file header said, 333 * we definitely know the value of *this* 334 * reference: 335 */ 336 last->flag |= REF_KNOWS_PEELED; 337} 338} 339 340fclose(f); 341strbuf_release(&line); 342 343return packed_refs; 344} 345 346static const char*files_packed_refs_path(struct files_ref_store *refs) 347{ 348return refs->packed_refs_path; 349} 350 351static voidfiles_reflog_path(struct files_ref_store *refs, 352struct strbuf *sb, 353const char*refname) 354{ 355if(!refname) { 356/* 357 * FIXME: of course this is wrong in multi worktree 358 * setting. To be fixed real soon. 359 */ 360strbuf_addf(sb,"%s/logs", refs->gitcommondir); 361return; 362} 363 364switch(ref_type(refname)) { 365case REF_TYPE_PER_WORKTREE: 366case REF_TYPE_PSEUDOREF: 367strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 368break; 369case REF_TYPE_NORMAL: 370strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 371break; 372default: 373die("BUG: unknown ref type%dof ref%s", 374ref_type(refname), refname); 375} 376} 377 378static voidfiles_ref_path(struct files_ref_store *refs, 379struct strbuf *sb, 380const char*refname) 381{ 382switch(ref_type(refname)) { 383case REF_TYPE_PER_WORKTREE: 384case REF_TYPE_PSEUDOREF: 385strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 386break; 387case REF_TYPE_NORMAL: 388strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 389break; 390default: 391die("BUG: unknown ref type%dof ref%s", 392ref_type(refname), refname); 393} 394} 395 396/* 397 * Check that the packed refs cache (if any) still reflects the 398 * contents of the file. If not, clear the cache. 399 */ 400static voidvalidate_packed_ref_cache(struct files_ref_store *refs) 401{ 402if(refs->packed_ref_store->cache && 403!stat_validity_check(&refs->packed_ref_store->cache->validity, 404files_packed_refs_path(refs))) 405clear_packed_ref_cache(refs); 406} 407 408/* 409 * Get the packed_ref_cache for the specified files_ref_store, 410 * creating and populating it if it hasn't been read before or if the 411 * file has been changed (according to its `validity` field) since it 412 * was last read. On the other hand, if we hold the lock, then assume 413 * that the file hasn't been changed out from under us, so skip the 414 * extra `stat()` call in `stat_validity_check()`. 415 */ 416static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 417{ 418const char*packed_refs_file =files_packed_refs_path(refs); 419 420if(!is_lock_file_locked(&refs->packed_refs_lock)) 421validate_packed_ref_cache(refs); 422 423if(!refs->packed_ref_store->cache) 424 refs->packed_ref_store->cache =read_packed_refs(packed_refs_file); 425 426return refs->packed_ref_store->cache; 427} 428 429static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 430{ 431returnget_ref_dir(packed_ref_cache->cache->root); 432} 433 434static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 435{ 436returnget_packed_ref_dir(get_packed_ref_cache(refs)); 437} 438 439/* 440 * Add or overwrite a reference in the in-memory packed reference 441 * cache. This may only be called while the packed-refs file is locked 442 * (see lock_packed_refs()). To actually write the packed-refs file, 443 * call commit_packed_refs(). 444 */ 445static voidadd_packed_ref(struct files_ref_store *refs, 446const char*refname,const struct object_id *oid) 447{ 448struct ref_dir *packed_refs; 449struct ref_entry *packed_entry; 450 451if(!is_lock_file_locked(&refs->packed_refs_lock)) 452die("BUG: packed refs not locked"); 453 454if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 455die("Reference has invalid format: '%s'", refname); 456 457 packed_refs =get_packed_refs(refs); 458 packed_entry =find_ref_entry(packed_refs, refname); 459if(packed_entry) { 460/* Overwrite the existing entry: */ 461oidcpy(&packed_entry->u.value.oid, oid); 462 packed_entry->flag = REF_ISPACKED; 463oidclr(&packed_entry->u.value.peeled); 464}else{ 465 packed_entry =create_ref_entry(refname, oid, REF_ISPACKED); 466add_ref_entry(packed_refs, packed_entry); 467} 468} 469 470/* 471 * Read the loose references from the namespace dirname into dir 472 * (without recursing). dirname must end with '/'. dir must be the 473 * directory entry corresponding to dirname. 474 */ 475static voidloose_fill_ref_dir(struct ref_store *ref_store, 476struct ref_dir *dir,const char*dirname) 477{ 478struct files_ref_store *refs = 479files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 480DIR*d; 481struct dirent *de; 482int dirnamelen =strlen(dirname); 483struct strbuf refname; 484struct strbuf path = STRBUF_INIT; 485size_t path_baselen; 486 487files_ref_path(refs, &path, dirname); 488 path_baselen = path.len; 489 490 d =opendir(path.buf); 491if(!d) { 492strbuf_release(&path); 493return; 494} 495 496strbuf_init(&refname, dirnamelen +257); 497strbuf_add(&refname, dirname, dirnamelen); 498 499while((de =readdir(d)) != NULL) { 500struct object_id oid; 501struct stat st; 502int flag; 503 504if(de->d_name[0] =='.') 505continue; 506if(ends_with(de->d_name,".lock")) 507continue; 508strbuf_addstr(&refname, de->d_name); 509strbuf_addstr(&path, de->d_name); 510if(stat(path.buf, &st) <0) { 511;/* silently ignore */ 512}else if(S_ISDIR(st.st_mode)) { 513strbuf_addch(&refname,'/'); 514add_entry_to_dir(dir, 515create_dir_entry(dir->cache, refname.buf, 516 refname.len,1)); 517}else{ 518if(!refs_resolve_ref_unsafe(&refs->base, 519 refname.buf, 520 RESOLVE_REF_READING, 521 oid.hash, &flag)) { 522oidclr(&oid); 523 flag |= REF_ISBROKEN; 524}else if(is_null_oid(&oid)) { 525/* 526 * It is so astronomically unlikely 527 * that NULL_SHA1 is the SHA-1 of an 528 * actual object that we consider its 529 * appearance in a loose reference 530 * file to be repo corruption 531 * (probably due to a software bug). 532 */ 533 flag |= REF_ISBROKEN; 534} 535 536if(check_refname_format(refname.buf, 537 REFNAME_ALLOW_ONELEVEL)) { 538if(!refname_is_safe(refname.buf)) 539die("loose refname is dangerous:%s", refname.buf); 540oidclr(&oid); 541 flag |= REF_BAD_NAME | REF_ISBROKEN; 542} 543add_entry_to_dir(dir, 544create_ref_entry(refname.buf, &oid, flag)); 545} 546strbuf_setlen(&refname, dirnamelen); 547strbuf_setlen(&path, path_baselen); 548} 549strbuf_release(&refname); 550strbuf_release(&path); 551closedir(d); 552 553/* 554 * Manually add refs/bisect, which, being per-worktree, might 555 * not appear in the directory listing for refs/ in the main 556 * repo. 557 */ 558if(!strcmp(dirname,"refs/")) { 559int pos =search_ref_dir(dir,"refs/bisect/",12); 560 561if(pos <0) { 562struct ref_entry *child_entry =create_dir_entry( 563 dir->cache,"refs/bisect/",12,1); 564add_entry_to_dir(dir, child_entry); 565} 566} 567} 568 569static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 570{ 571if(!refs->loose) { 572/* 573 * Mark the top-level directory complete because we 574 * are about to read the only subdirectory that can 575 * hold references: 576 */ 577 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 578 579/* We're going to fill the top level ourselves: */ 580 refs->loose->root->flag &= ~REF_INCOMPLETE; 581 582/* 583 * Add an incomplete entry for "refs/" (to be filled 584 * lazily): 585 */ 586add_entry_to_dir(get_ref_dir(refs->loose->root), 587create_dir_entry(refs->loose,"refs/",5,1)); 588} 589return refs->loose; 590} 591 592/* 593 * Return the ref_entry for the given refname from the packed 594 * references. If it does not exist, return NULL. 595 */ 596static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 597const char*refname) 598{ 599returnfind_ref_entry(get_packed_refs(refs), refname); 600} 601 602/* 603 * A loose ref file doesn't exist; check for a packed ref. 604 */ 605static intresolve_packed_ref(struct files_ref_store *refs, 606const char*refname, 607unsigned char*sha1,unsigned int*flags) 608{ 609struct ref_entry *entry; 610 611/* 612 * The loose reference file does not exist; check for a packed 613 * reference. 614 */ 615 entry =get_packed_ref(refs, refname); 616if(entry) { 617hashcpy(sha1, entry->u.value.oid.hash); 618*flags |= REF_ISPACKED; 619return0; 620} 621/* refname is not a packed reference. */ 622return-1; 623} 624 625static intfiles_read_raw_ref(struct ref_store *ref_store, 626const char*refname,unsigned char*sha1, 627struct strbuf *referent,unsigned int*type) 628{ 629struct files_ref_store *refs = 630files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 631struct strbuf sb_contents = STRBUF_INIT; 632struct strbuf sb_path = STRBUF_INIT; 633const char*path; 634const char*buf; 635struct stat st; 636int fd; 637int ret = -1; 638int save_errno; 639int remaining_retries =3; 640 641*type =0; 642strbuf_reset(&sb_path); 643 644files_ref_path(refs, &sb_path, refname); 645 646 path = sb_path.buf; 647 648stat_ref: 649/* 650 * We might have to loop back here to avoid a race 651 * condition: first we lstat() the file, then we try 652 * to read it as a link or as a file. But if somebody 653 * changes the type of the file (file <-> directory 654 * <-> symlink) between the lstat() and reading, then 655 * we don't want to report that as an error but rather 656 * try again starting with the lstat(). 657 * 658 * We'll keep a count of the retries, though, just to avoid 659 * any confusing situation sending us into an infinite loop. 660 */ 661 662if(remaining_retries-- <=0) 663goto out; 664 665if(lstat(path, &st) <0) { 666if(errno != ENOENT) 667goto out; 668if(resolve_packed_ref(refs, refname, sha1, type)) { 669 errno = ENOENT; 670goto out; 671} 672 ret =0; 673goto out; 674} 675 676/* Follow "normalized" - ie "refs/.." symlinks by hand */ 677if(S_ISLNK(st.st_mode)) { 678strbuf_reset(&sb_contents); 679if(strbuf_readlink(&sb_contents, path,0) <0) { 680if(errno == ENOENT || errno == EINVAL) 681/* inconsistent with lstat; retry */ 682goto stat_ref; 683else 684goto out; 685} 686if(starts_with(sb_contents.buf,"refs/") && 687!check_refname_format(sb_contents.buf,0)) { 688strbuf_swap(&sb_contents, referent); 689*type |= REF_ISSYMREF; 690 ret =0; 691goto out; 692} 693/* 694 * It doesn't look like a refname; fall through to just 695 * treating it like a non-symlink, and reading whatever it 696 * points to. 697 */ 698} 699 700/* Is it a directory? */ 701if(S_ISDIR(st.st_mode)) { 702/* 703 * Even though there is a directory where the loose 704 * ref is supposed to be, there could still be a 705 * packed ref: 706 */ 707if(resolve_packed_ref(refs, refname, sha1, type)) { 708 errno = EISDIR; 709goto out; 710} 711 ret =0; 712goto out; 713} 714 715/* 716 * Anything else, just open it and try to use it as 717 * a ref 718 */ 719 fd =open(path, O_RDONLY); 720if(fd <0) { 721if(errno == ENOENT && !S_ISLNK(st.st_mode)) 722/* inconsistent with lstat; retry */ 723goto stat_ref; 724else 725goto out; 726} 727strbuf_reset(&sb_contents); 728if(strbuf_read(&sb_contents, fd,256) <0) { 729int save_errno = errno; 730close(fd); 731 errno = save_errno; 732goto out; 733} 734close(fd); 735strbuf_rtrim(&sb_contents); 736 buf = sb_contents.buf; 737if(starts_with(buf,"ref:")) { 738 buf +=4; 739while(isspace(*buf)) 740 buf++; 741 742strbuf_reset(referent); 743strbuf_addstr(referent, buf); 744*type |= REF_ISSYMREF; 745 ret =0; 746goto out; 747} 748 749/* 750 * Please note that FETCH_HEAD has additional 751 * data after the sha. 752 */ 753if(get_sha1_hex(buf, sha1) || 754(buf[40] !='\0'&& !isspace(buf[40]))) { 755*type |= REF_ISBROKEN; 756 errno = EINVAL; 757goto out; 758} 759 760 ret =0; 761 762out: 763 save_errno = errno; 764strbuf_release(&sb_path); 765strbuf_release(&sb_contents); 766 errno = save_errno; 767return ret; 768} 769 770static voidunlock_ref(struct ref_lock *lock) 771{ 772/* Do not free lock->lk -- atexit() still looks at them */ 773if(lock->lk) 774rollback_lock_file(lock->lk); 775free(lock->ref_name); 776free(lock); 777} 778 779/* 780 * Lock refname, without following symrefs, and set *lock_p to point 781 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 782 * and type similarly to read_raw_ref(). 783 * 784 * The caller must verify that refname is a "safe" reference name (in 785 * the sense of refname_is_safe()) before calling this function. 786 * 787 * If the reference doesn't already exist, verify that refname doesn't 788 * have a D/F conflict with any existing references. extras and skip 789 * are passed to refs_verify_refname_available() for this check. 790 * 791 * If mustexist is not set and the reference is not found or is 792 * broken, lock the reference anyway but clear sha1. 793 * 794 * Return 0 on success. On failure, write an error message to err and 795 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 796 * 797 * Implementation note: This function is basically 798 * 799 * lock reference 800 * read_raw_ref() 801 * 802 * but it includes a lot more code to 803 * - Deal with possible races with other processes 804 * - Avoid calling refs_verify_refname_available() when it can be 805 * avoided, namely if we were successfully able to read the ref 806 * - Generate informative error messages in the case of failure 807 */ 808static intlock_raw_ref(struct files_ref_store *refs, 809const char*refname,int mustexist, 810const struct string_list *extras, 811const struct string_list *skip, 812struct ref_lock **lock_p, 813struct strbuf *referent, 814unsigned int*type, 815struct strbuf *err) 816{ 817struct ref_lock *lock; 818struct strbuf ref_file = STRBUF_INIT; 819int attempts_remaining =3; 820int ret = TRANSACTION_GENERIC_ERROR; 821 822assert(err); 823files_assert_main_repository(refs,"lock_raw_ref"); 824 825*type =0; 826 827/* First lock the file so it can't change out from under us. */ 828 829*lock_p = lock =xcalloc(1,sizeof(*lock)); 830 831 lock->ref_name =xstrdup(refname); 832files_ref_path(refs, &ref_file, refname); 833 834retry: 835switch(safe_create_leading_directories(ref_file.buf)) { 836case SCLD_OK: 837break;/* success */ 838case SCLD_EXISTS: 839/* 840 * Suppose refname is "refs/foo/bar". We just failed 841 * to create the containing directory, "refs/foo", 842 * because there was a non-directory in the way. This 843 * indicates a D/F conflict, probably because of 844 * another reference such as "refs/foo". There is no 845 * reason to expect this error to be transitory. 846 */ 847if(refs_verify_refname_available(&refs->base, refname, 848 extras, skip, err)) { 849if(mustexist) { 850/* 851 * To the user the relevant error is 852 * that the "mustexist" reference is 853 * missing: 854 */ 855strbuf_reset(err); 856strbuf_addf(err,"unable to resolve reference '%s'", 857 refname); 858}else{ 859/* 860 * The error message set by 861 * refs_verify_refname_available() is 862 * OK. 863 */ 864 ret = TRANSACTION_NAME_CONFLICT; 865} 866}else{ 867/* 868 * The file that is in the way isn't a loose 869 * reference. Report it as a low-level 870 * failure. 871 */ 872strbuf_addf(err,"unable to create lock file%s.lock; " 873"non-directory in the way", 874 ref_file.buf); 875} 876goto error_return; 877case SCLD_VANISHED: 878/* Maybe another process was tidying up. Try again. */ 879if(--attempts_remaining >0) 880goto retry; 881/* fall through */ 882default: 883strbuf_addf(err,"unable to create directory for%s", 884 ref_file.buf); 885goto error_return; 886} 887 888if(!lock->lk) 889 lock->lk =xcalloc(1,sizeof(struct lock_file)); 890 891if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 892if(errno == ENOENT && --attempts_remaining >0) { 893/* 894 * Maybe somebody just deleted one of the 895 * directories leading to ref_file. Try 896 * again: 897 */ 898goto retry; 899}else{ 900unable_to_lock_message(ref_file.buf, errno, err); 901goto error_return; 902} 903} 904 905/* 906 * Now we hold the lock and can read the reference without 907 * fear that its value will change. 908 */ 909 910if(files_read_raw_ref(&refs->base, refname, 911 lock->old_oid.hash, referent, type)) { 912if(errno == ENOENT) { 913if(mustexist) { 914/* Garden variety missing reference. */ 915strbuf_addf(err,"unable to resolve reference '%s'", 916 refname); 917goto error_return; 918}else{ 919/* 920 * Reference is missing, but that's OK. We 921 * know that there is not a conflict with 922 * another loose reference because 923 * (supposing that we are trying to lock 924 * reference "refs/foo/bar"): 925 * 926 * - We were successfully able to create 927 * the lockfile refs/foo/bar.lock, so we 928 * know there cannot be a loose reference 929 * named "refs/foo". 930 * 931 * - We got ENOENT and not EISDIR, so we 932 * know that there cannot be a loose 933 * reference named "refs/foo/bar/baz". 934 */ 935} 936}else if(errno == EISDIR) { 937/* 938 * There is a directory in the way. It might have 939 * contained references that have been deleted. If 940 * we don't require that the reference already 941 * exists, try to remove the directory so that it 942 * doesn't cause trouble when we want to rename the 943 * lockfile into place later. 944 */ 945if(mustexist) { 946/* Garden variety missing reference. */ 947strbuf_addf(err,"unable to resolve reference '%s'", 948 refname); 949goto error_return; 950}else if(remove_dir_recursively(&ref_file, 951 REMOVE_DIR_EMPTY_ONLY)) { 952if(refs_verify_refname_available( 953&refs->base, refname, 954 extras, skip, err)) { 955/* 956 * The error message set by 957 * verify_refname_available() is OK. 958 */ 959 ret = TRANSACTION_NAME_CONFLICT; 960goto error_return; 961}else{ 962/* 963 * We can't delete the directory, 964 * but we also don't know of any 965 * references that it should 966 * contain. 967 */ 968strbuf_addf(err,"there is a non-empty directory '%s' " 969"blocking reference '%s'", 970 ref_file.buf, refname); 971goto error_return; 972} 973} 974}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 975strbuf_addf(err,"unable to resolve reference '%s': " 976"reference broken", refname); 977goto error_return; 978}else{ 979strbuf_addf(err,"unable to resolve reference '%s':%s", 980 refname,strerror(errno)); 981goto error_return; 982} 983 984/* 985 * If the ref did not exist and we are creating it, 986 * make sure there is no existing ref that conflicts 987 * with refname: 988 */ 989if(refs_verify_refname_available( 990&refs->base, refname, 991 extras, skip, err)) 992goto error_return; 993} 994 995 ret =0; 996goto out; 997 998error_return: 999unlock_ref(lock);1000*lock_p = NULL;10011002out:1003strbuf_release(&ref_file);1004return ret;1005}10061007static intfiles_peel_ref(struct ref_store *ref_store,1008const char*refname,unsigned char*sha1)1009{1010struct files_ref_store *refs =1011files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,1012"peel_ref");1013int flag;1014unsigned char base[20];10151016if(current_ref_iter && current_ref_iter->refname == refname) {1017struct object_id peeled;10181019if(ref_iterator_peel(current_ref_iter, &peeled))1020return-1;1021hashcpy(sha1, peeled.hash);1022return0;1023}10241025if(refs_read_ref_full(ref_store, refname,1026 RESOLVE_REF_READING, base, &flag))1027return-1;10281029/*1030 * If the reference is packed, read its ref_entry from the1031 * cache in the hope that we already know its peeled value.1032 * We only try this optimization on packed references because1033 * (a) forcing the filling of the loose reference cache could1034 * be expensive and (b) loose references anyway usually do not1035 * have REF_KNOWS_PEELED.1036 */1037if(flag & REF_ISPACKED) {1038struct ref_entry *r =get_packed_ref(refs, refname);1039if(r) {1040if(peel_entry(r,0))1041return-1;1042hashcpy(sha1, r->u.value.peeled.hash);1043return0;1044}1045}10461047returnpeel_object(base, sha1);1048}10491050struct files_ref_iterator {1051struct ref_iterator base;10521053struct packed_ref_cache *packed_ref_cache;1054struct ref_iterator *iter0;1055unsigned int flags;1056};10571058static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1059{1060struct files_ref_iterator *iter =1061(struct files_ref_iterator *)ref_iterator;1062int ok;10631064while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1065if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1066ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1067continue;10681069if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1070!ref_resolves_to_object(iter->iter0->refname,1071 iter->iter0->oid,1072 iter->iter0->flags))1073continue;10741075 iter->base.refname = iter->iter0->refname;1076 iter->base.oid = iter->iter0->oid;1077 iter->base.flags = iter->iter0->flags;1078return ITER_OK;1079}10801081 iter->iter0 = NULL;1082if(ref_iterator_abort(ref_iterator) != ITER_DONE)1083 ok = ITER_ERROR;10841085return ok;1086}10871088static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1089struct object_id *peeled)1090{1091struct files_ref_iterator *iter =1092(struct files_ref_iterator *)ref_iterator;10931094returnref_iterator_peel(iter->iter0, peeled);1095}10961097static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1098{1099struct files_ref_iterator *iter =1100(struct files_ref_iterator *)ref_iterator;1101int ok = ITER_DONE;11021103if(iter->iter0)1104 ok =ref_iterator_abort(iter->iter0);11051106release_packed_ref_cache(iter->packed_ref_cache);1107base_ref_iterator_free(ref_iterator);1108return ok;1109}11101111static struct ref_iterator_vtable files_ref_iterator_vtable = {1112 files_ref_iterator_advance,1113 files_ref_iterator_peel,1114 files_ref_iterator_abort1115};11161117static struct ref_iterator *files_ref_iterator_begin(1118struct ref_store *ref_store,1119const char*prefix,unsigned int flags)1120{1121struct files_ref_store *refs;1122struct ref_iterator *loose_iter, *packed_iter;1123struct files_ref_iterator *iter;1124struct ref_iterator *ref_iterator;1125unsigned int required_flags = REF_STORE_READ;11261127if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1128 required_flags |= REF_STORE_ODB;11291130 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11311132 iter =xcalloc(1,sizeof(*iter));1133 ref_iterator = &iter->base;1134base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11351136/*1137 * We must make sure that all loose refs are read before1138 * accessing the packed-refs file; this avoids a race1139 * condition if loose refs are migrated to the packed-refs1140 * file by a simultaneous process, but our in-memory view is1141 * from before the migration. We ensure this as follows:1142 * First, we call start the loose refs iteration with its1143 * `prime_ref` argument set to true. This causes the loose1144 * references in the subtree to be pre-read into the cache.1145 * (If they've already been read, that's OK; we only need to1146 * guarantee that they're read before the packed refs, not1147 * *how much* before.) After that, we call1148 * get_packed_ref_cache(), which internally checks whether the1149 * packed-ref cache is up to date with what is on disk, and1150 * re-reads it if not.1151 */11521153 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1154 prefix,1);11551156 iter->packed_ref_cache =get_packed_ref_cache(refs);1157acquire_packed_ref_cache(iter->packed_ref_cache);1158 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1159 prefix,0);11601161 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1162 iter->flags = flags;11631164return ref_iterator;1165}11661167/*1168 * Verify that the reference locked by lock has the value old_sha1.1169 * Fail if the reference doesn't exist and mustexist is set. Return 01170 * on success. On error, write an error message to err, set errno, and1171 * return a negative value.1172 */1173static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1174const unsigned char*old_sha1,int mustexist,1175struct strbuf *err)1176{1177assert(err);11781179if(refs_read_ref_full(ref_store, lock->ref_name,1180 mustexist ? RESOLVE_REF_READING :0,1181 lock->old_oid.hash, NULL)) {1182if(old_sha1) {1183int save_errno = errno;1184strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1185 errno = save_errno;1186return-1;1187}else{1188oidclr(&lock->old_oid);1189return0;1190}1191}1192if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1193strbuf_addf(err,"ref '%s' is at%sbut expected%s",1194 lock->ref_name,1195oid_to_hex(&lock->old_oid),1196sha1_to_hex(old_sha1));1197 errno = EBUSY;1198return-1;1199}1200return0;1201}12021203static intremove_empty_directories(struct strbuf *path)1204{1205/*1206 * we want to create a file but there is a directory there;1207 * if that is an empty directory (or a directory that contains1208 * only empty directories), remove them.1209 */1210returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1211}12121213static intcreate_reflock(const char*path,void*cb)1214{1215struct lock_file *lk = cb;12161217returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1218}12191220/*1221 * Locks a ref returning the lock on success and NULL on failure.1222 * On failure errno is set to something meaningful.1223 */1224static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1225const char*refname,1226const unsigned char*old_sha1,1227const struct string_list *extras,1228const struct string_list *skip,1229unsigned int flags,int*type,1230struct strbuf *err)1231{1232struct strbuf ref_file = STRBUF_INIT;1233struct ref_lock *lock;1234int last_errno =0;1235int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1236int resolve_flags = RESOLVE_REF_NO_RECURSE;1237int resolved;12381239files_assert_main_repository(refs,"lock_ref_sha1_basic");1240assert(err);12411242 lock =xcalloc(1,sizeof(struct ref_lock));12431244if(mustexist)1245 resolve_flags |= RESOLVE_REF_READING;1246if(flags & REF_DELETING)1247 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12481249files_ref_path(refs, &ref_file, refname);1250 resolved = !!refs_resolve_ref_unsafe(&refs->base,1251 refname, resolve_flags,1252 lock->old_oid.hash, type);1253if(!resolved && errno == EISDIR) {1254/*1255 * we are trying to lock foo but we used to1256 * have foo/bar which now does not exist;1257 * it is normal for the empty directory 'foo'1258 * to remain.1259 */1260if(remove_empty_directories(&ref_file)) {1261 last_errno = errno;1262if(!refs_verify_refname_available(1263&refs->base,1264 refname, extras, skip, err))1265strbuf_addf(err,"there are still refs under '%s'",1266 refname);1267goto error_return;1268}1269 resolved = !!refs_resolve_ref_unsafe(&refs->base,1270 refname, resolve_flags,1271 lock->old_oid.hash, type);1272}1273if(!resolved) {1274 last_errno = errno;1275if(last_errno != ENOTDIR ||1276!refs_verify_refname_available(&refs->base, refname,1277 extras, skip, err))1278strbuf_addf(err,"unable to resolve reference '%s':%s",1279 refname,strerror(last_errno));12801281goto error_return;1282}12831284/*1285 * If the ref did not exist and we are creating it, make sure1286 * there is no existing packed ref whose name begins with our1287 * refname, nor a packed ref whose name is a proper prefix of1288 * our refname.1289 */1290if(is_null_oid(&lock->old_oid) &&1291refs_verify_refname_available(&refs->base, refname,1292 extras, skip, err)) {1293 last_errno = ENOTDIR;1294goto error_return;1295}12961297 lock->lk =xcalloc(1,sizeof(struct lock_file));12981299 lock->ref_name =xstrdup(refname);13001301if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1302 last_errno = errno;1303unable_to_lock_message(ref_file.buf, errno, err);1304goto error_return;1305}13061307if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1308 last_errno = errno;1309goto error_return;1310}1311goto out;13121313 error_return:1314unlock_ref(lock);1315 lock = NULL;13161317 out:1318strbuf_release(&ref_file);1319 errno = last_errno;1320return lock;1321}13221323/*1324 * Write an entry to the packed-refs file for the specified refname.1325 * If peeled is non-NULL, write it as the entry's peeled value.1326 */1327static voidwrite_packed_entry(FILE*fh,const char*refname,1328const unsigned char*sha1,1329const unsigned char*peeled)1330{1331fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1332if(peeled)1333fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1334}13351336/*1337 * Lock the packed-refs file for writing. Flags is passed to1338 * hold_lock_file_for_update(). Return 0 on success. On errors, set1339 * errno appropriately and return a nonzero value.1340 */1341static intlock_packed_refs(struct files_ref_store *refs,int flags)1342{1343static int timeout_configured =0;1344static int timeout_value =1000;1345struct packed_ref_cache *packed_ref_cache;13461347files_assert_main_repository(refs,"lock_packed_refs");13481349if(!timeout_configured) {1350git_config_get_int("core.packedrefstimeout", &timeout_value);1351 timeout_configured =1;1352}13531354if(hold_lock_file_for_update_timeout(1355&refs->packed_refs_lock,files_packed_refs_path(refs),1356 flags, timeout_value) <0)1357return-1;13581359/*1360 * Now that we hold the `packed-refs` lock, make sure that our1361 * cache matches the current version of the file. Normally1362 * `get_packed_ref_cache()` does that for us, but that1363 * function assumes that when the file is locked, any existing1364 * cache is still valid. We've just locked the file, but it1365 * might have changed the moment *before* we locked it.1366 */1367validate_packed_ref_cache(refs);13681369 packed_ref_cache =get_packed_ref_cache(refs);1370/* Increment the reference count to prevent it from being freed: */1371acquire_packed_ref_cache(packed_ref_cache);1372return0;1373}13741375/*1376 * Write the current version of the packed refs cache from memory to1377 * disk. The packed-refs file must already be locked for writing (see1378 * lock_packed_refs()). Return zero on success. On errors, set errno1379 * and return a nonzero value1380 */1381static intcommit_packed_refs(struct files_ref_store *refs)1382{1383struct packed_ref_cache *packed_ref_cache =1384get_packed_ref_cache(refs);1385int ok, error =0;1386int save_errno =0;1387FILE*out;1388struct ref_iterator *iter;13891390files_assert_main_repository(refs,"commit_packed_refs");13911392if(!is_lock_file_locked(&refs->packed_refs_lock))1393die("BUG: packed-refs not locked");13941395 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1396if(!out)1397die_errno("unable to fdopen packed-refs descriptor");13981399fprintf_or_die(out,"%s", PACKED_REFS_HEADER);14001401 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1402while((ok =ref_iterator_advance(iter)) == ITER_OK) {1403struct object_id peeled;1404int peel_error =ref_iterator_peel(iter, &peeled);14051406write_packed_entry(out, iter->refname, iter->oid->hash,1407 peel_error ? NULL : peeled.hash);1408}14091410if(ok != ITER_DONE)1411die("error while iterating over references");14121413if(commit_lock_file(&refs->packed_refs_lock)) {1414 save_errno = errno;1415 error = -1;1416}1417release_packed_ref_cache(packed_ref_cache);1418 errno = save_errno;1419return error;1420}14211422/*1423 * Rollback the lockfile for the packed-refs file, and discard the1424 * in-memory packed reference cache. (The packed-refs file will be1425 * read anew if it is needed again after this function is called.)1426 */1427static voidrollback_packed_refs(struct files_ref_store *refs)1428{1429struct packed_ref_cache *packed_ref_cache =1430get_packed_ref_cache(refs);14311432files_assert_main_repository(refs,"rollback_packed_refs");14331434if(!is_lock_file_locked(&refs->packed_refs_lock))1435die("BUG: packed-refs not locked");1436rollback_lock_file(&refs->packed_refs_lock);1437release_packed_ref_cache(packed_ref_cache);1438clear_packed_ref_cache(refs);1439}14401441struct ref_to_prune {1442struct ref_to_prune *next;1443unsigned char sha1[20];1444char name[FLEX_ARRAY];1445};14461447enum{1448 REMOVE_EMPTY_PARENTS_REF =0x01,1449 REMOVE_EMPTY_PARENTS_REFLOG =0x021450};14511452/*1453 * Remove empty parent directories associated with the specified1454 * reference and/or its reflog, but spare [logs/]refs/ and immediate1455 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1456 * REMOVE_EMPTY_PARENTS_REFLOG.1457 */1458static voidtry_remove_empty_parents(struct files_ref_store *refs,1459const char*refname,1460unsigned int flags)1461{1462struct strbuf buf = STRBUF_INIT;1463struct strbuf sb = STRBUF_INIT;1464char*p, *q;1465int i;14661467strbuf_addstr(&buf, refname);1468 p = buf.buf;1469for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1470while(*p && *p !='/')1471 p++;1472/* tolerate duplicate slashes; see check_refname_format() */1473while(*p =='/')1474 p++;1475}1476 q = buf.buf + buf.len;1477while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1478while(q > p && *q !='/')1479 q--;1480while(q > p && *(q-1) =='/')1481 q--;1482if(q == p)1483break;1484strbuf_setlen(&buf, q - buf.buf);14851486strbuf_reset(&sb);1487files_ref_path(refs, &sb, buf.buf);1488if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1489 flags &= ~REMOVE_EMPTY_PARENTS_REF;14901491strbuf_reset(&sb);1492files_reflog_path(refs, &sb, buf.buf);1493if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1494 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1495}1496strbuf_release(&buf);1497strbuf_release(&sb);1498}14991500/* make sure nobody touched the ref, and unlink */1501static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1502{1503struct ref_transaction *transaction;1504struct strbuf err = STRBUF_INIT;15051506if(check_refname_format(r->name,0))1507return;15081509 transaction =ref_store_transaction_begin(&refs->base, &err);1510if(!transaction ||1511ref_transaction_delete(transaction, r->name, r->sha1,1512 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1513ref_transaction_commit(transaction, &err)) {1514ref_transaction_free(transaction);1515error("%s", err.buf);1516strbuf_release(&err);1517return;1518}1519ref_transaction_free(transaction);1520strbuf_release(&err);1521}15221523static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1524{1525while(r) {1526prune_ref(refs, r);1527 r = r->next;1528}1529}15301531/*1532 * Return true if the specified reference should be packed.1533 */1534static intshould_pack_ref(const char*refname,1535const struct object_id *oid,unsigned int ref_flags,1536unsigned int pack_flags)1537{1538/* Do not pack per-worktree refs: */1539if(ref_type(refname) != REF_TYPE_NORMAL)1540return0;15411542/* Do not pack non-tags unless PACK_REFS_ALL is set: */1543if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1544return0;15451546/* Do not pack symbolic refs: */1547if(ref_flags & REF_ISSYMREF)1548return0;15491550/* Do not pack broken refs: */1551if(!ref_resolves_to_object(refname, oid, ref_flags))1552return0;15531554return1;1555}15561557static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1558{1559struct files_ref_store *refs =1560files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1561"pack_refs");1562struct ref_iterator *iter;1563int ok;1564struct ref_to_prune *refs_to_prune = NULL;15651566lock_packed_refs(refs, LOCK_DIE_ON_ERROR);15671568 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1569while((ok =ref_iterator_advance(iter)) == ITER_OK) {1570/*1571 * If the loose reference can be packed, add an entry1572 * in the packed ref cache. If the reference should be1573 * pruned, also add it to refs_to_prune.1574 */1575if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1576 flags))1577continue;15781579/*1580 * Create an entry in the packed-refs cache equivalent1581 * to the one from the loose ref cache, except that1582 * we don't copy the peeled status, because we want it1583 * to be re-peeled.1584 */1585add_packed_ref(refs, iter->refname, iter->oid);15861587/* Schedule the loose reference for pruning if requested. */1588if((flags & PACK_REFS_PRUNE)) {1589struct ref_to_prune *n;1590FLEX_ALLOC_STR(n, name, iter->refname);1591hashcpy(n->sha1, iter->oid->hash);1592 n->next = refs_to_prune;1593 refs_to_prune = n;1594}1595}1596if(ok != ITER_DONE)1597die("error while iterating over references");15981599if(commit_packed_refs(refs))1600die_errno("unable to overwrite old ref-pack file");16011602prune_refs(refs, refs_to_prune);1603return0;1604}16051606/*1607 * Rewrite the packed-refs file, omitting any refs listed in1608 * 'refnames'. On error, leave packed-refs unchanged, write an error1609 * message to 'err', and return a nonzero value.1610 *1611 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1612 */1613static intrepack_without_refs(struct files_ref_store *refs,1614struct string_list *refnames,struct strbuf *err)1615{1616struct ref_dir *packed;1617struct string_list_item *refname;1618int ret, needs_repacking =0, removed =0;16191620files_assert_main_repository(refs,"repack_without_refs");1621assert(err);16221623/* Look for a packed ref */1624for_each_string_list_item(refname, refnames) {1625if(get_packed_ref(refs, refname->string)) {1626 needs_repacking =1;1627break;1628}1629}16301631/* Avoid locking if we have nothing to do */1632if(!needs_repacking)1633return0;/* no refname exists in packed refs */16341635if(lock_packed_refs(refs,0)) {1636unable_to_lock_message(files_packed_refs_path(refs), errno, err);1637return-1;1638}1639 packed =get_packed_refs(refs);16401641/* Remove refnames from the cache */1642for_each_string_list_item(refname, refnames)1643if(remove_entry_from_dir(packed, refname->string) != -1)1644 removed =1;1645if(!removed) {1646/*1647 * All packed entries disappeared while we were1648 * acquiring the lock.1649 */1650rollback_packed_refs(refs);1651return0;1652}16531654/* Write what remains */1655 ret =commit_packed_refs(refs);1656if(ret)1657strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1658strerror(errno));1659return ret;1660}16611662static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1663struct string_list *refnames,unsigned int flags)1664{1665struct files_ref_store *refs =1666files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1667struct strbuf err = STRBUF_INIT;1668int i, result =0;16691670if(!refnames->nr)1671return0;16721673 result =repack_without_refs(refs, refnames, &err);1674if(result) {1675/*1676 * If we failed to rewrite the packed-refs file, then1677 * it is unsafe to try to remove loose refs, because1678 * doing so might expose an obsolete packed value for1679 * a reference that might even point at an object that1680 * has been garbage collected.1681 */1682if(refnames->nr ==1)1683error(_("could not delete reference%s:%s"),1684 refnames->items[0].string, err.buf);1685else1686error(_("could not delete references:%s"), err.buf);16871688goto out;1689}16901691for(i =0; i < refnames->nr; i++) {1692const char*refname = refnames->items[i].string;16931694if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1695 result |=error(_("could not remove reference%s"), refname);1696}16971698out:1699strbuf_release(&err);1700return result;1701}17021703/*1704 * People using contrib's git-new-workdir have .git/logs/refs ->1705 * /some/other/path/.git/logs/refs, and that may live on another device.1706 *1707 * IOW, to avoid cross device rename errors, the temporary renamed log must1708 * live into logs/refs.1709 */1710#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"17111712struct rename_cb {1713const char*tmp_renamed_log;1714int true_errno;1715};17161717static intrename_tmp_log_callback(const char*path,void*cb_data)1718{1719struct rename_cb *cb = cb_data;17201721if(rename(cb->tmp_renamed_log, path)) {1722/*1723 * rename(a, b) when b is an existing directory ought1724 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1725 * Sheesh. Record the true errno for error reporting,1726 * but report EISDIR to raceproof_create_file() so1727 * that it knows to retry.1728 */1729 cb->true_errno = errno;1730if(errno == ENOTDIR)1731 errno = EISDIR;1732return-1;1733}else{1734return0;1735}1736}17371738static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1739{1740struct strbuf path = STRBUF_INIT;1741struct strbuf tmp = STRBUF_INIT;1742struct rename_cb cb;1743int ret;17441745files_reflog_path(refs, &path, newrefname);1746files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1747 cb.tmp_renamed_log = tmp.buf;1748 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1749if(ret) {1750if(errno == EISDIR)1751error("directory not empty:%s", path.buf);1752else1753error("unable to move logfile%sto%s:%s",1754 tmp.buf, path.buf,1755strerror(cb.true_errno));1756}17571758strbuf_release(&path);1759strbuf_release(&tmp);1760return ret;1761}17621763static intwrite_ref_to_lockfile(struct ref_lock *lock,1764const struct object_id *oid,struct strbuf *err);1765static intcommit_ref_update(struct files_ref_store *refs,1766struct ref_lock *lock,1767const struct object_id *oid,const char*logmsg,1768struct strbuf *err);17691770static intfiles_rename_ref(struct ref_store *ref_store,1771const char*oldrefname,const char*newrefname,1772const char*logmsg)1773{1774struct files_ref_store *refs =1775files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1776struct object_id oid, orig_oid;1777int flag =0, logmoved =0;1778struct ref_lock *lock;1779struct stat loginfo;1780struct strbuf sb_oldref = STRBUF_INIT;1781struct strbuf sb_newref = STRBUF_INIT;1782struct strbuf tmp_renamed_log = STRBUF_INIT;1783int log, ret;1784struct strbuf err = STRBUF_INIT;17851786files_reflog_path(refs, &sb_oldref, oldrefname);1787files_reflog_path(refs, &sb_newref, newrefname);1788files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17891790 log = !lstat(sb_oldref.buf, &loginfo);1791if(log &&S_ISLNK(loginfo.st_mode)) {1792 ret =error("reflog for%sis a symlink", oldrefname);1793goto out;1794}17951796if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1797 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1798 orig_oid.hash, &flag)) {1799 ret =error("refname%snot found", oldrefname);1800goto out;1801}18021803if(flag & REF_ISSYMREF) {1804 ret =error("refname%sis a symbolic ref, renaming it is not supported",1805 oldrefname);1806goto out;1807}1808if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1809 ret =1;1810goto out;1811}18121813if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1814 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1815 oldrefname,strerror(errno));1816goto out;1817}18181819if(refs_delete_ref(&refs->base, logmsg, oldrefname,1820 orig_oid.hash, REF_NODEREF)) {1821error("unable to delete old%s", oldrefname);1822goto rollback;1823}18241825/*1826 * Since we are doing a shallow lookup, oid is not the1827 * correct value to pass to delete_ref as old_oid. But that1828 * doesn't matter, because an old_oid check wouldn't add to1829 * the safety anyway; we want to delete the reference whatever1830 * its current value.1831 */1832if(!refs_read_ref_full(&refs->base, newrefname,1833 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1834 oid.hash, NULL) &&1835refs_delete_ref(&refs->base, NULL, newrefname,1836 NULL, REF_NODEREF)) {1837if(errno == EISDIR) {1838struct strbuf path = STRBUF_INIT;1839int result;18401841files_ref_path(refs, &path, newrefname);1842 result =remove_empty_directories(&path);1843strbuf_release(&path);18441845if(result) {1846error("Directory not empty:%s", newrefname);1847goto rollback;1848}1849}else{1850error("unable to delete existing%s", newrefname);1851goto rollback;1852}1853}18541855if(log &&rename_tmp_log(refs, newrefname))1856goto rollback;18571858 logmoved = log;18591860 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1861 REF_NODEREF, NULL, &err);1862if(!lock) {1863error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1864strbuf_release(&err);1865goto rollback;1866}1867oidcpy(&lock->old_oid, &orig_oid);18681869if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1870commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1871error("unable to write current sha1 into%s:%s", newrefname, err.buf);1872strbuf_release(&err);1873goto rollback;1874}18751876 ret =0;1877goto out;18781879 rollback:1880 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1881 REF_NODEREF, NULL, &err);1882if(!lock) {1883error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1884strbuf_release(&err);1885goto rollbacklog;1886}18871888 flag = log_all_ref_updates;1889 log_all_ref_updates = LOG_REFS_NONE;1890if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1891commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1892error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1893strbuf_release(&err);1894}1895 log_all_ref_updates = flag;18961897 rollbacklog:1898if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1899error("unable to restore logfile%sfrom%s:%s",1900 oldrefname, newrefname,strerror(errno));1901if(!logmoved && log &&1902rename(tmp_renamed_log.buf, sb_oldref.buf))1903error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1904 oldrefname,strerror(errno));1905 ret =1;1906 out:1907strbuf_release(&sb_newref);1908strbuf_release(&sb_oldref);1909strbuf_release(&tmp_renamed_log);19101911return ret;1912}19131914static intclose_ref(struct ref_lock *lock)1915{1916if(close_lock_file(lock->lk))1917return-1;1918return0;1919}19201921static intcommit_ref(struct ref_lock *lock)1922{1923char*path =get_locked_file_path(lock->lk);1924struct stat st;19251926if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1927/*1928 * There is a directory at the path we want to rename1929 * the lockfile to. Hopefully it is empty; try to1930 * delete it.1931 */1932size_t len =strlen(path);1933struct strbuf sb_path = STRBUF_INIT;19341935strbuf_attach(&sb_path, path, len, len);19361937/*1938 * If this fails, commit_lock_file() will also fail1939 * and will report the problem.1940 */1941remove_empty_directories(&sb_path);1942strbuf_release(&sb_path);1943}else{1944free(path);1945}19461947if(commit_lock_file(lock->lk))1948return-1;1949return0;1950}19511952static intopen_or_create_logfile(const char*path,void*cb)1953{1954int*fd = cb;19551956*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1957return(*fd <0) ? -1:0;1958}19591960/*1961 * Create a reflog for a ref. If force_create = 0, only create the1962 * reflog for certain refs (those for which should_autocreate_reflog1963 * returns non-zero). Otherwise, create it regardless of the reference1964 * name. If the logfile already existed or was created, return 0 and1965 * set *logfd to the file descriptor opened for appending to the file.1966 * If no logfile exists and we decided not to create one, return 0 and1967 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1968 * return -1.1969 */1970static intlog_ref_setup(struct files_ref_store *refs,1971const char*refname,int force_create,1972int*logfd,struct strbuf *err)1973{1974struct strbuf logfile_sb = STRBUF_INIT;1975char*logfile;19761977files_reflog_path(refs, &logfile_sb, refname);1978 logfile =strbuf_detach(&logfile_sb, NULL);19791980if(force_create ||should_autocreate_reflog(refname)) {1981if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1982if(errno == ENOENT)1983strbuf_addf(err,"unable to create directory for '%s': "1984"%s", logfile,strerror(errno));1985else if(errno == EISDIR)1986strbuf_addf(err,"there are still logs under '%s'",1987 logfile);1988else1989strbuf_addf(err,"unable to append to '%s':%s",1990 logfile,strerror(errno));19911992goto error;1993}1994}else{1995*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1996if(*logfd <0) {1997if(errno == ENOENT || errno == EISDIR) {1998/*1999 * The logfile doesn't already exist,2000 * but that is not an error; it only2001 * means that we won't write log2002 * entries to it.2003 */2004;2005}else{2006strbuf_addf(err,"unable to append to '%s':%s",2007 logfile,strerror(errno));2008goto error;2009}2010}2011}20122013if(*logfd >=0)2014adjust_shared_perm(logfile);20152016free(logfile);2017return0;20182019error:2020free(logfile);2021return-1;2022}20232024static intfiles_create_reflog(struct ref_store *ref_store,2025const char*refname,int force_create,2026struct strbuf *err)2027{2028struct files_ref_store *refs =2029files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2030int fd;20312032if(log_ref_setup(refs, refname, force_create, &fd, err))2033return-1;20342035if(fd >=0)2036close(fd);20372038return0;2039}20402041static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2042const struct object_id *new_oid,2043const char*committer,const char*msg)2044{2045int msglen, written;2046unsigned maxlen, len;2047char*logrec;20482049 msglen = msg ?strlen(msg) :0;2050 maxlen =strlen(committer) + msglen +100;2051 logrec =xmalloc(maxlen);2052 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2053oid_to_hex(old_oid),2054oid_to_hex(new_oid),2055 committer);2056if(msglen)2057 len +=copy_reflog_msg(logrec + len -1, msg) -1;20582059 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2060free(logrec);2061if(written != len)2062return-1;20632064return0;2065}20662067static intfiles_log_ref_write(struct files_ref_store *refs,2068const char*refname,const struct object_id *old_oid,2069const struct object_id *new_oid,const char*msg,2070int flags,struct strbuf *err)2071{2072int logfd, result;20732074if(log_all_ref_updates == LOG_REFS_UNSET)2075 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20762077 result =log_ref_setup(refs, refname,2078 flags & REF_FORCE_CREATE_REFLOG,2079&logfd, err);20802081if(result)2082return result;20832084if(logfd <0)2085return0;2086 result =log_ref_write_fd(logfd, old_oid, new_oid,2087git_committer_info(0), msg);2088if(result) {2089struct strbuf sb = STRBUF_INIT;2090int save_errno = errno;20912092files_reflog_path(refs, &sb, refname);2093strbuf_addf(err,"unable to append to '%s':%s",2094 sb.buf,strerror(save_errno));2095strbuf_release(&sb);2096close(logfd);2097return-1;2098}2099if(close(logfd)) {2100struct strbuf sb = STRBUF_INIT;2101int save_errno = errno;21022103files_reflog_path(refs, &sb, refname);2104strbuf_addf(err,"unable to append to '%s':%s",2105 sb.buf,strerror(save_errno));2106strbuf_release(&sb);2107return-1;2108}2109return0;2110}21112112/*2113 * Write sha1 into the open lockfile, then close the lockfile. On2114 * errors, rollback the lockfile, fill in *err and2115 * return -1.2116 */2117static intwrite_ref_to_lockfile(struct ref_lock *lock,2118const struct object_id *oid,struct strbuf *err)2119{2120static char term ='\n';2121struct object *o;2122int fd;21232124 o =parse_object(oid);2125if(!o) {2126strbuf_addf(err,2127"trying to write ref '%s' with nonexistent object%s",2128 lock->ref_name,oid_to_hex(oid));2129unlock_ref(lock);2130return-1;2131}2132if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2133strbuf_addf(err,2134"trying to write non-commit object%sto branch '%s'",2135oid_to_hex(oid), lock->ref_name);2136unlock_ref(lock);2137return-1;2138}2139 fd =get_lock_file_fd(lock->lk);2140if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2141write_in_full(fd, &term,1) !=1||2142close_ref(lock) <0) {2143strbuf_addf(err,2144"couldn't write '%s'",get_lock_file_path(lock->lk));2145unlock_ref(lock);2146return-1;2147}2148return0;2149}21502151/*2152 * Commit a change to a loose reference that has already been written2153 * to the loose reference lockfile. Also update the reflogs if2154 * necessary, using the specified lockmsg (which can be NULL).2155 */2156static intcommit_ref_update(struct files_ref_store *refs,2157struct ref_lock *lock,2158const struct object_id *oid,const char*logmsg,2159struct strbuf *err)2160{2161files_assert_main_repository(refs,"commit_ref_update");21622163clear_loose_ref_cache(refs);2164if(files_log_ref_write(refs, lock->ref_name,2165&lock->old_oid, oid,2166 logmsg,0, err)) {2167char*old_msg =strbuf_detach(err, NULL);2168strbuf_addf(err,"cannot update the ref '%s':%s",2169 lock->ref_name, old_msg);2170free(old_msg);2171unlock_ref(lock);2172return-1;2173}21742175if(strcmp(lock->ref_name,"HEAD") !=0) {2176/*2177 * Special hack: If a branch is updated directly and HEAD2178 * points to it (may happen on the remote side of a push2179 * for example) then logically the HEAD reflog should be2180 * updated too.2181 * A generic solution implies reverse symref information,2182 * but finding all symrefs pointing to the given branch2183 * would be rather costly for this rare event (the direct2184 * update of a branch) to be worth it. So let's cheat and2185 * check with HEAD only which should cover 99% of all usage2186 * scenarios (even 100% of the default ones).2187 */2188struct object_id head_oid;2189int head_flag;2190const char*head_ref;21912192 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2193 RESOLVE_REF_READING,2194 head_oid.hash, &head_flag);2195if(head_ref && (head_flag & REF_ISSYMREF) &&2196!strcmp(head_ref, lock->ref_name)) {2197struct strbuf log_err = STRBUF_INIT;2198if(files_log_ref_write(refs,"HEAD",2199&lock->old_oid, oid,2200 logmsg,0, &log_err)) {2201error("%s", log_err.buf);2202strbuf_release(&log_err);2203}2204}2205}22062207if(commit_ref(lock)) {2208strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2209unlock_ref(lock);2210return-1;2211}22122213unlock_ref(lock);2214return0;2215}22162217static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2218{2219int ret = -1;2220#ifndef NO_SYMLINK_HEAD2221char*ref_path =get_locked_file_path(lock->lk);2222unlink(ref_path);2223 ret =symlink(target, ref_path);2224free(ref_path);22252226if(ret)2227fprintf(stderr,"no symlink - falling back to symbolic ref\n");2228#endif2229return ret;2230}22312232static voidupdate_symref_reflog(struct files_ref_store *refs,2233struct ref_lock *lock,const char*refname,2234const char*target,const char*logmsg)2235{2236struct strbuf err = STRBUF_INIT;2237struct object_id new_oid;2238if(logmsg &&2239!refs_read_ref_full(&refs->base, target,2240 RESOLVE_REF_READING, new_oid.hash, NULL) &&2241files_log_ref_write(refs, refname, &lock->old_oid,2242&new_oid, logmsg,0, &err)) {2243error("%s", err.buf);2244strbuf_release(&err);2245}2246}22472248static intcreate_symref_locked(struct files_ref_store *refs,2249struct ref_lock *lock,const char*refname,2250const char*target,const char*logmsg)2251{2252if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2253update_symref_reflog(refs, lock, refname, target, logmsg);2254return0;2255}22562257if(!fdopen_lock_file(lock->lk,"w"))2258returnerror("unable to fdopen%s:%s",2259 lock->lk->tempfile.filename.buf,strerror(errno));22602261update_symref_reflog(refs, lock, refname, target, logmsg);22622263/* no error check; commit_ref will check ferror */2264fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2265if(commit_ref(lock) <0)2266returnerror("unable to write symref for%s:%s", refname,2267strerror(errno));2268return0;2269}22702271static intfiles_create_symref(struct ref_store *ref_store,2272const char*refname,const char*target,2273const char*logmsg)2274{2275struct files_ref_store *refs =2276files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2277struct strbuf err = STRBUF_INIT;2278struct ref_lock *lock;2279int ret;22802281 lock =lock_ref_sha1_basic(refs, refname, NULL,2282 NULL, NULL, REF_NODEREF, NULL,2283&err);2284if(!lock) {2285error("%s", err.buf);2286strbuf_release(&err);2287return-1;2288}22892290 ret =create_symref_locked(refs, lock, refname, target, logmsg);2291unlock_ref(lock);2292return ret;2293}22942295static intfiles_reflog_exists(struct ref_store *ref_store,2296const char*refname)2297{2298struct files_ref_store *refs =2299files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2300struct strbuf sb = STRBUF_INIT;2301struct stat st;2302int ret;23032304files_reflog_path(refs, &sb, refname);2305 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2306strbuf_release(&sb);2307return ret;2308}23092310static intfiles_delete_reflog(struct ref_store *ref_store,2311const char*refname)2312{2313struct files_ref_store *refs =2314files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2315struct strbuf sb = STRBUF_INIT;2316int ret;23172318files_reflog_path(refs, &sb, refname);2319 ret =remove_path(sb.buf);2320strbuf_release(&sb);2321return ret;2322}23232324static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2325{2326struct object_id ooid, noid;2327char*email_end, *message;2328 timestamp_t timestamp;2329int tz;2330const char*p = sb->buf;23312332/* old SP new SP name <email> SP time TAB msg LF */2333if(!sb->len || sb->buf[sb->len -1] !='\n'||2334parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2335parse_oid_hex(p, &noid, &p) || *p++ !=' '||2336!(email_end =strchr(p,'>')) ||2337 email_end[1] !=' '||2338!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2339!message || message[0] !=' '||2340(message[1] !='+'&& message[1] !='-') ||2341!isdigit(message[2]) || !isdigit(message[3]) ||2342!isdigit(message[4]) || !isdigit(message[5]))2343return0;/* corrupt? */2344 email_end[1] ='\0';2345 tz =strtol(message +1, NULL,10);2346if(message[6] !='\t')2347 message +=6;2348else2349 message +=7;2350returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2351}23522353static char*find_beginning_of_line(char*bob,char*scan)2354{2355while(bob < scan && *(--scan) !='\n')2356;/* keep scanning backwards */2357/*2358 * Return either beginning of the buffer, or LF at the end of2359 * the previous line.2360 */2361return scan;2362}23632364static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2365const char*refname,2366 each_reflog_ent_fn fn,2367void*cb_data)2368{2369struct files_ref_store *refs =2370files_downcast(ref_store, REF_STORE_READ,2371"for_each_reflog_ent_reverse");2372struct strbuf sb = STRBUF_INIT;2373FILE*logfp;2374long pos;2375int ret =0, at_tail =1;23762377files_reflog_path(refs, &sb, refname);2378 logfp =fopen(sb.buf,"r");2379strbuf_release(&sb);2380if(!logfp)2381return-1;23822383/* Jump to the end */2384if(fseek(logfp,0, SEEK_END) <0)2385 ret =error("cannot seek back reflog for%s:%s",2386 refname,strerror(errno));2387 pos =ftell(logfp);2388while(!ret &&0< pos) {2389int cnt;2390size_t nread;2391char buf[BUFSIZ];2392char*endp, *scanp;23932394/* Fill next block from the end */2395 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2396if(fseek(logfp, pos - cnt, SEEK_SET)) {2397 ret =error("cannot seek back reflog for%s:%s",2398 refname,strerror(errno));2399break;2400}2401 nread =fread(buf, cnt,1, logfp);2402if(nread !=1) {2403 ret =error("cannot read%dbytes from reflog for%s:%s",2404 cnt, refname,strerror(errno));2405break;2406}2407 pos -= cnt;24082409 scanp = endp = buf + cnt;2410if(at_tail && scanp[-1] =='\n')2411/* Looking at the final LF at the end of the file */2412 scanp--;2413 at_tail =0;24142415while(buf < scanp) {2416/*2417 * terminating LF of the previous line, or the beginning2418 * of the buffer.2419 */2420char*bp;24212422 bp =find_beginning_of_line(buf, scanp);24232424if(*bp =='\n') {2425/*2426 * The newline is the end of the previous line,2427 * so we know we have complete line starting2428 * at (bp + 1). Prefix it onto any prior data2429 * we collected for the line and process it.2430 */2431strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2432 scanp = bp;2433 endp = bp +1;2434 ret =show_one_reflog_ent(&sb, fn, cb_data);2435strbuf_reset(&sb);2436if(ret)2437break;2438}else if(!pos) {2439/*2440 * We are at the start of the buffer, and the2441 * start of the file; there is no previous2442 * line, and we have everything for this one.2443 * Process it, and we can end the loop.2444 */2445strbuf_splice(&sb,0,0, buf, endp - buf);2446 ret =show_one_reflog_ent(&sb, fn, cb_data);2447strbuf_reset(&sb);2448break;2449}24502451if(bp == buf) {2452/*2453 * We are at the start of the buffer, and there2454 * is more file to read backwards. Which means2455 * we are in the middle of a line. Note that we2456 * may get here even if *bp was a newline; that2457 * just means we are at the exact end of the2458 * previous line, rather than some spot in the2459 * middle.2460 *2461 * Save away what we have to be combined with2462 * the data from the next read.2463 */2464strbuf_splice(&sb,0,0, buf, endp - buf);2465break;2466}2467}24682469}2470if(!ret && sb.len)2471die("BUG: reverse reflog parser had leftover data");24722473fclose(logfp);2474strbuf_release(&sb);2475return ret;2476}24772478static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2479const char*refname,2480 each_reflog_ent_fn fn,void*cb_data)2481{2482struct files_ref_store *refs =2483files_downcast(ref_store, REF_STORE_READ,2484"for_each_reflog_ent");2485FILE*logfp;2486struct strbuf sb = STRBUF_INIT;2487int ret =0;24882489files_reflog_path(refs, &sb, refname);2490 logfp =fopen(sb.buf,"r");2491strbuf_release(&sb);2492if(!logfp)2493return-1;24942495while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2496 ret =show_one_reflog_ent(&sb, fn, cb_data);2497fclose(logfp);2498strbuf_release(&sb);2499return ret;2500}25012502struct files_reflog_iterator {2503struct ref_iterator base;25042505struct ref_store *ref_store;2506struct dir_iterator *dir_iterator;2507struct object_id oid;2508};25092510static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2511{2512struct files_reflog_iterator *iter =2513(struct files_reflog_iterator *)ref_iterator;2514struct dir_iterator *diter = iter->dir_iterator;2515int ok;25162517while((ok =dir_iterator_advance(diter)) == ITER_OK) {2518int flags;25192520if(!S_ISREG(diter->st.st_mode))2521continue;2522if(diter->basename[0] =='.')2523continue;2524if(ends_with(diter->basename,".lock"))2525continue;25262527if(refs_read_ref_full(iter->ref_store,2528 diter->relative_path,0,2529 iter->oid.hash, &flags)) {2530error("bad ref for%s", diter->path.buf);2531continue;2532}25332534 iter->base.refname = diter->relative_path;2535 iter->base.oid = &iter->oid;2536 iter->base.flags = flags;2537return ITER_OK;2538}25392540 iter->dir_iterator = NULL;2541if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2542 ok = ITER_ERROR;2543return ok;2544}25452546static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2547struct object_id *peeled)2548{2549die("BUG: ref_iterator_peel() called for reflog_iterator");2550}25512552static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2553{2554struct files_reflog_iterator *iter =2555(struct files_reflog_iterator *)ref_iterator;2556int ok = ITER_DONE;25572558if(iter->dir_iterator)2559 ok =dir_iterator_abort(iter->dir_iterator);25602561base_ref_iterator_free(ref_iterator);2562return ok;2563}25642565static struct ref_iterator_vtable files_reflog_iterator_vtable = {2566 files_reflog_iterator_advance,2567 files_reflog_iterator_peel,2568 files_reflog_iterator_abort2569};25702571static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2572{2573struct files_ref_store *refs =2574files_downcast(ref_store, REF_STORE_READ,2575"reflog_iterator_begin");2576struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2577struct ref_iterator *ref_iterator = &iter->base;2578struct strbuf sb = STRBUF_INIT;25792580base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2581files_reflog_path(refs, &sb, NULL);2582 iter->dir_iterator =dir_iterator_begin(sb.buf);2583 iter->ref_store = ref_store;2584strbuf_release(&sb);2585return ref_iterator;2586}25872588/*2589 * If update is a direct update of head_ref (the reference pointed to2590 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2591 */2592static intsplit_head_update(struct ref_update *update,2593struct ref_transaction *transaction,2594const char*head_ref,2595struct string_list *affected_refnames,2596struct strbuf *err)2597{2598struct string_list_item *item;2599struct ref_update *new_update;26002601if((update->flags & REF_LOG_ONLY) ||2602(update->flags & REF_ISPRUNING) ||2603(update->flags & REF_UPDATE_VIA_HEAD))2604return0;26052606if(strcmp(update->refname, head_ref))2607return0;26082609/*2610 * First make sure that HEAD is not already in the2611 * transaction. This insertion is O(N) in the transaction2612 * size, but it happens at most once per transaction.2613 */2614 item =string_list_insert(affected_refnames,"HEAD");2615if(item->util) {2616/* An entry already existed */2617strbuf_addf(err,2618"multiple updates for 'HEAD' (including one "2619"via its referent '%s') are not allowed",2620 update->refname);2621return TRANSACTION_NAME_CONFLICT;2622}26232624 new_update =ref_transaction_add_update(2625 transaction,"HEAD",2626 update->flags | REF_LOG_ONLY | REF_NODEREF,2627 update->new_oid.hash, update->old_oid.hash,2628 update->msg);26292630 item->util = new_update;26312632return0;2633}26342635/*2636 * update is for a symref that points at referent and doesn't have2637 * REF_NODEREF set. Split it into two updates:2638 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2639 * - A new, separate update for the referent reference2640 * Note that the new update will itself be subject to splitting when2641 * the iteration gets to it.2642 */2643static intsplit_symref_update(struct files_ref_store *refs,2644struct ref_update *update,2645const char*referent,2646struct ref_transaction *transaction,2647struct string_list *affected_refnames,2648struct strbuf *err)2649{2650struct string_list_item *item;2651struct ref_update *new_update;2652unsigned int new_flags;26532654/*2655 * First make sure that referent is not already in the2656 * transaction. This insertion is O(N) in the transaction2657 * size, but it happens at most once per symref in a2658 * transaction.2659 */2660 item =string_list_insert(affected_refnames, referent);2661if(item->util) {2662/* An entry already existed */2663strbuf_addf(err,2664"multiple updates for '%s' (including one "2665"via symref '%s') are not allowed",2666 referent, update->refname);2667return TRANSACTION_NAME_CONFLICT;2668}26692670 new_flags = update->flags;2671if(!strcmp(update->refname,"HEAD")) {2672/*2673 * Record that the new update came via HEAD, so that2674 * when we process it, split_head_update() doesn't try2675 * to add another reflog update for HEAD. Note that2676 * this bit will be propagated if the new_update2677 * itself needs to be split.2678 */2679 new_flags |= REF_UPDATE_VIA_HEAD;2680}26812682 new_update =ref_transaction_add_update(2683 transaction, referent, new_flags,2684 update->new_oid.hash, update->old_oid.hash,2685 update->msg);26862687 new_update->parent_update = update;26882689/*2690 * Change the symbolic ref update to log only. Also, it2691 * doesn't need to check its old SHA-1 value, as that will be2692 * done when new_update is processed.2693 */2694 update->flags |= REF_LOG_ONLY | REF_NODEREF;2695 update->flags &= ~REF_HAVE_OLD;26962697 item->util = new_update;26982699return0;2700}27012702/*2703 * Return the refname under which update was originally requested.2704 */2705static const char*original_update_refname(struct ref_update *update)2706{2707while(update->parent_update)2708 update = update->parent_update;27092710return update->refname;2711}27122713/*2714 * Check whether the REF_HAVE_OLD and old_oid values stored in update2715 * are consistent with oid, which is the reference's current value. If2716 * everything is OK, return 0; otherwise, write an error message to2717 * err and return -1.2718 */2719static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2720struct strbuf *err)2721{2722if(!(update->flags & REF_HAVE_OLD) ||2723!oidcmp(oid, &update->old_oid))2724return0;27252726if(is_null_oid(&update->old_oid))2727strbuf_addf(err,"cannot lock ref '%s': "2728"reference already exists",2729original_update_refname(update));2730else if(is_null_oid(oid))2731strbuf_addf(err,"cannot lock ref '%s': "2732"reference is missing but expected%s",2733original_update_refname(update),2734oid_to_hex(&update->old_oid));2735else2736strbuf_addf(err,"cannot lock ref '%s': "2737"is at%sbut expected%s",2738original_update_refname(update),2739oid_to_hex(oid),2740oid_to_hex(&update->old_oid));27412742return-1;2743}27442745/*2746 * Prepare for carrying out update:2747 * - Lock the reference referred to by update.2748 * - Read the reference under lock.2749 * - Check that its old SHA-1 value (if specified) is correct, and in2750 * any case record it in update->lock->old_oid for later use when2751 * writing the reflog.2752 * - If it is a symref update without REF_NODEREF, split it up into a2753 * REF_LOG_ONLY update of the symref and add a separate update for2754 * the referent to transaction.2755 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2756 * update of HEAD.2757 */2758static intlock_ref_for_update(struct files_ref_store *refs,2759struct ref_update *update,2760struct ref_transaction *transaction,2761const char*head_ref,2762struct string_list *affected_refnames,2763struct strbuf *err)2764{2765struct strbuf referent = STRBUF_INIT;2766int mustexist = (update->flags & REF_HAVE_OLD) &&2767!is_null_oid(&update->old_oid);2768int ret;2769struct ref_lock *lock;27702771files_assert_main_repository(refs,"lock_ref_for_update");27722773if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2774 update->flags |= REF_DELETING;27752776if(head_ref) {2777 ret =split_head_update(update, transaction, head_ref,2778 affected_refnames, err);2779if(ret)2780return ret;2781}27822783 ret =lock_raw_ref(refs, update->refname, mustexist,2784 affected_refnames, NULL,2785&lock, &referent,2786&update->type, err);2787if(ret) {2788char*reason;27892790 reason =strbuf_detach(err, NULL);2791strbuf_addf(err,"cannot lock ref '%s':%s",2792original_update_refname(update), reason);2793free(reason);2794return ret;2795}27962797 update->backend_data = lock;27982799if(update->type & REF_ISSYMREF) {2800if(update->flags & REF_NODEREF) {2801/*2802 * We won't be reading the referent as part of2803 * the transaction, so we have to read it here2804 * to record and possibly check old_sha1:2805 */2806if(refs_read_ref_full(&refs->base,2807 referent.buf,0,2808 lock->old_oid.hash, NULL)) {2809if(update->flags & REF_HAVE_OLD) {2810strbuf_addf(err,"cannot lock ref '%s': "2811"error reading reference",2812original_update_refname(update));2813return-1;2814}2815}else if(check_old_oid(update, &lock->old_oid, err)) {2816return TRANSACTION_GENERIC_ERROR;2817}2818}else{2819/*2820 * Create a new update for the reference this2821 * symref is pointing at. Also, we will record2822 * and verify old_sha1 for this update as part2823 * of processing the split-off update, so we2824 * don't have to do it here.2825 */2826 ret =split_symref_update(refs, update,2827 referent.buf, transaction,2828 affected_refnames, err);2829if(ret)2830return ret;2831}2832}else{2833struct ref_update *parent_update;28342835if(check_old_oid(update, &lock->old_oid, err))2836return TRANSACTION_GENERIC_ERROR;28372838/*2839 * If this update is happening indirectly because of a2840 * symref update, record the old SHA-1 in the parent2841 * update:2842 */2843for(parent_update = update->parent_update;2844 parent_update;2845 parent_update = parent_update->parent_update) {2846struct ref_lock *parent_lock = parent_update->backend_data;2847oidcpy(&parent_lock->old_oid, &lock->old_oid);2848}2849}28502851if((update->flags & REF_HAVE_NEW) &&2852!(update->flags & REF_DELETING) &&2853!(update->flags & REF_LOG_ONLY)) {2854if(!(update->type & REF_ISSYMREF) &&2855!oidcmp(&lock->old_oid, &update->new_oid)) {2856/*2857 * The reference already has the desired2858 * value, so we don't need to write it.2859 */2860}else if(write_ref_to_lockfile(lock, &update->new_oid,2861 err)) {2862char*write_err =strbuf_detach(err, NULL);28632864/*2865 * The lock was freed upon failure of2866 * write_ref_to_lockfile():2867 */2868 update->backend_data = NULL;2869strbuf_addf(err,2870"cannot update ref '%s':%s",2871 update->refname, write_err);2872free(write_err);2873return TRANSACTION_GENERIC_ERROR;2874}else{2875 update->flags |= REF_NEEDS_COMMIT;2876}2877}2878if(!(update->flags & REF_NEEDS_COMMIT)) {2879/*2880 * We didn't call write_ref_to_lockfile(), so2881 * the lockfile is still open. Close it to2882 * free up the file descriptor:2883 */2884if(close_ref(lock)) {2885strbuf_addf(err,"couldn't close '%s.lock'",2886 update->refname);2887return TRANSACTION_GENERIC_ERROR;2888}2889}2890return0;2891}28922893/*2894 * Unlock any references in `transaction` that are still locked, and2895 * mark the transaction closed.2896 */2897static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2898{2899size_t i;29002901for(i =0; i < transaction->nr; i++) {2902struct ref_update *update = transaction->updates[i];2903struct ref_lock *lock = update->backend_data;29042905if(lock) {2906unlock_ref(lock);2907 update->backend_data = NULL;2908}2909}29102911 transaction->state = REF_TRANSACTION_CLOSED;2912}29132914static intfiles_transaction_prepare(struct ref_store *ref_store,2915struct ref_transaction *transaction,2916struct strbuf *err)2917{2918struct files_ref_store *refs =2919files_downcast(ref_store, REF_STORE_WRITE,2920"ref_transaction_prepare");2921size_t i;2922int ret =0;2923struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2924char*head_ref = NULL;2925int head_type;2926struct object_id head_oid;29272928assert(err);29292930if(!transaction->nr)2931goto cleanup;29322933/*2934 * Fail if a refname appears more than once in the2935 * transaction. (If we end up splitting up any updates using2936 * split_symref_update() or split_head_update(), those2937 * functions will check that the new updates don't have the2938 * same refname as any existing ones.)2939 */2940for(i =0; i < transaction->nr; i++) {2941struct ref_update *update = transaction->updates[i];2942struct string_list_item *item =2943string_list_append(&affected_refnames, update->refname);29442945/*2946 * We store a pointer to update in item->util, but at2947 * the moment we never use the value of this field2948 * except to check whether it is non-NULL.2949 */2950 item->util = update;2951}2952string_list_sort(&affected_refnames);2953if(ref_update_reject_duplicates(&affected_refnames, err)) {2954 ret = TRANSACTION_GENERIC_ERROR;2955goto cleanup;2956}29572958/*2959 * Special hack: If a branch is updated directly and HEAD2960 * points to it (may happen on the remote side of a push2961 * for example) then logically the HEAD reflog should be2962 * updated too.2963 *2964 * A generic solution would require reverse symref lookups,2965 * but finding all symrefs pointing to a given branch would be2966 * rather costly for this rare event (the direct update of a2967 * branch) to be worth it. So let's cheat and check with HEAD2968 * only, which should cover 99% of all usage scenarios (even2969 * 100% of the default ones).2970 *2971 * So if HEAD is a symbolic reference, then record the name of2972 * the reference that it points to. If we see an update of2973 * head_ref within the transaction, then split_head_update()2974 * arranges for the reflog of HEAD to be updated, too.2975 */2976 head_ref =refs_resolve_refdup(ref_store,"HEAD",2977 RESOLVE_REF_NO_RECURSE,2978 head_oid.hash, &head_type);29792980if(head_ref && !(head_type & REF_ISSYMREF)) {2981free(head_ref);2982 head_ref = NULL;2983}29842985/*2986 * Acquire all locks, verify old values if provided, check2987 * that new values are valid, and write new values to the2988 * lockfiles, ready to be activated. Only keep one lockfile2989 * open at a time to avoid running out of file descriptors.2990 * Note that lock_ref_for_update() might append more updates2991 * to the transaction.2992 */2993for(i =0; i < transaction->nr; i++) {2994struct ref_update *update = transaction->updates[i];29952996 ret =lock_ref_for_update(refs, update, transaction,2997 head_ref, &affected_refnames, err);2998if(ret)2999break;3000}30013002cleanup:3003free(head_ref);3004string_list_clear(&affected_refnames,0);30053006if(ret)3007files_transaction_cleanup(transaction);3008else3009 transaction->state = REF_TRANSACTION_PREPARED;30103011return ret;3012}30133014static intfiles_transaction_finish(struct ref_store *ref_store,3015struct ref_transaction *transaction,3016struct strbuf *err)3017{3018struct files_ref_store *refs =3019files_downcast(ref_store,0,"ref_transaction_finish");3020size_t i;3021int ret =0;3022struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3023struct string_list_item *ref_to_delete;3024struct strbuf sb = STRBUF_INIT;30253026assert(err);30273028if(!transaction->nr) {3029 transaction->state = REF_TRANSACTION_CLOSED;3030return0;3031}30323033/* Perform updates first so live commits remain referenced */3034for(i =0; i < transaction->nr; i++) {3035struct ref_update *update = transaction->updates[i];3036struct ref_lock *lock = update->backend_data;30373038if(update->flags & REF_NEEDS_COMMIT ||3039 update->flags & REF_LOG_ONLY) {3040if(files_log_ref_write(refs,3041 lock->ref_name,3042&lock->old_oid,3043&update->new_oid,3044 update->msg, update->flags,3045 err)) {3046char*old_msg =strbuf_detach(err, NULL);30473048strbuf_addf(err,"cannot update the ref '%s':%s",3049 lock->ref_name, old_msg);3050free(old_msg);3051unlock_ref(lock);3052 update->backend_data = NULL;3053 ret = TRANSACTION_GENERIC_ERROR;3054goto cleanup;3055}3056}3057if(update->flags & REF_NEEDS_COMMIT) {3058clear_loose_ref_cache(refs);3059if(commit_ref(lock)) {3060strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3061unlock_ref(lock);3062 update->backend_data = NULL;3063 ret = TRANSACTION_GENERIC_ERROR;3064goto cleanup;3065}3066}3067}3068/* Perform deletes now that updates are safely completed */3069for(i =0; i < transaction->nr; i++) {3070struct ref_update *update = transaction->updates[i];3071struct ref_lock *lock = update->backend_data;30723073if(update->flags & REF_DELETING &&3074!(update->flags & REF_LOG_ONLY)) {3075if(!(update->type & REF_ISPACKED) ||3076 update->type & REF_ISSYMREF) {3077/* It is a loose reference. */3078strbuf_reset(&sb);3079files_ref_path(refs, &sb, lock->ref_name);3080if(unlink_or_msg(sb.buf, err)) {3081 ret = TRANSACTION_GENERIC_ERROR;3082goto cleanup;3083}3084 update->flags |= REF_DELETED_LOOSE;3085}30863087if(!(update->flags & REF_ISPRUNING))3088string_list_append(&refs_to_delete,3089 lock->ref_name);3090}3091}30923093if(repack_without_refs(refs, &refs_to_delete, err)) {3094 ret = TRANSACTION_GENERIC_ERROR;3095goto cleanup;3096}30973098/* Delete the reflogs of any references that were deleted: */3099for_each_string_list_item(ref_to_delete, &refs_to_delete) {3100strbuf_reset(&sb);3101files_reflog_path(refs, &sb, ref_to_delete->string);3102if(!unlink_or_warn(sb.buf))3103try_remove_empty_parents(refs, ref_to_delete->string,3104 REMOVE_EMPTY_PARENTS_REFLOG);3105}31063107clear_loose_ref_cache(refs);31083109cleanup:3110files_transaction_cleanup(transaction);31113112for(i =0; i < transaction->nr; i++) {3113struct ref_update *update = transaction->updates[i];31143115if(update->flags & REF_DELETED_LOOSE) {3116/*3117 * The loose reference was deleted. Delete any3118 * empty parent directories. (Note that this3119 * can only work because we have already3120 * removed the lockfile.)3121 */3122try_remove_empty_parents(refs, update->refname,3123 REMOVE_EMPTY_PARENTS_REF);3124}3125}31263127strbuf_release(&sb);3128string_list_clear(&refs_to_delete,0);3129return ret;3130}31313132static intfiles_transaction_abort(struct ref_store *ref_store,3133struct ref_transaction *transaction,3134struct strbuf *err)3135{3136files_transaction_cleanup(transaction);3137return0;3138}31393140static intref_present(const char*refname,3141const struct object_id *oid,int flags,void*cb_data)3142{3143struct string_list *affected_refnames = cb_data;31443145returnstring_list_has_string(affected_refnames, refname);3146}31473148static intfiles_initial_transaction_commit(struct ref_store *ref_store,3149struct ref_transaction *transaction,3150struct strbuf *err)3151{3152struct files_ref_store *refs =3153files_downcast(ref_store, REF_STORE_WRITE,3154"initial_ref_transaction_commit");3155size_t i;3156int ret =0;3157struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31583159assert(err);31603161if(transaction->state != REF_TRANSACTION_OPEN)3162die("BUG: commit called for transaction that is not open");31633164/* Fail if a refname appears more than once in the transaction: */3165for(i =0; i < transaction->nr; i++)3166string_list_append(&affected_refnames,3167 transaction->updates[i]->refname);3168string_list_sort(&affected_refnames);3169if(ref_update_reject_duplicates(&affected_refnames, err)) {3170 ret = TRANSACTION_GENERIC_ERROR;3171goto cleanup;3172}31733174/*3175 * It's really undefined to call this function in an active3176 * repository or when there are existing references: we are3177 * only locking and changing packed-refs, so (1) any3178 * simultaneous processes might try to change a reference at3179 * the same time we do, and (2) any existing loose versions of3180 * the references that we are setting would have precedence3181 * over our values. But some remote helpers create the remote3182 * "HEAD" and "master" branches before calling this function,3183 * so here we really only check that none of the references3184 * that we are creating already exists.3185 */3186if(refs_for_each_rawref(&refs->base, ref_present,3187&affected_refnames))3188die("BUG: initial ref transaction called with existing refs");31893190for(i =0; i < transaction->nr; i++) {3191struct ref_update *update = transaction->updates[i];31923193if((update->flags & REF_HAVE_OLD) &&3194!is_null_oid(&update->old_oid))3195die("BUG: initial ref transaction with old_sha1 set");3196if(refs_verify_refname_available(&refs->base, update->refname,3197&affected_refnames, NULL,3198 err)) {3199 ret = TRANSACTION_NAME_CONFLICT;3200goto cleanup;3201}3202}32033204if(lock_packed_refs(refs,0)) {3205strbuf_addf(err,"unable to lock packed-refs file:%s",3206strerror(errno));3207 ret = TRANSACTION_GENERIC_ERROR;3208goto cleanup;3209}32103211for(i =0; i < transaction->nr; i++) {3212struct ref_update *update = transaction->updates[i];32133214if((update->flags & REF_HAVE_NEW) &&3215!is_null_oid(&update->new_oid))3216add_packed_ref(refs, update->refname,3217&update->new_oid);3218}32193220if(commit_packed_refs(refs)) {3221strbuf_addf(err,"unable to commit packed-refs file:%s",3222strerror(errno));3223 ret = TRANSACTION_GENERIC_ERROR;3224goto cleanup;3225}32263227cleanup:3228 transaction->state = REF_TRANSACTION_CLOSED;3229string_list_clear(&affected_refnames,0);3230return ret;3231}32323233struct expire_reflog_cb {3234unsigned int flags;3235 reflog_expiry_should_prune_fn *should_prune_fn;3236void*policy_cb;3237FILE*newlog;3238struct object_id last_kept_oid;3239};32403241static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3242const char*email, timestamp_t timestamp,int tz,3243const char*message,void*cb_data)3244{3245struct expire_reflog_cb *cb = cb_data;3246struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32473248if(cb->flags & EXPIRE_REFLOGS_REWRITE)3249 ooid = &cb->last_kept_oid;32503251if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3252 message, policy_cb)) {3253if(!cb->newlog)3254printf("would prune%s", message);3255else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3256printf("prune%s", message);3257}else{3258if(cb->newlog) {3259fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3260oid_to_hex(ooid),oid_to_hex(noid),3261 email, timestamp, tz, message);3262oidcpy(&cb->last_kept_oid, noid);3263}3264if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3265printf("keep%s", message);3266}3267return0;3268}32693270static intfiles_reflog_expire(struct ref_store *ref_store,3271const char*refname,const unsigned char*sha1,3272unsigned int flags,3273 reflog_expiry_prepare_fn prepare_fn,3274 reflog_expiry_should_prune_fn should_prune_fn,3275 reflog_expiry_cleanup_fn cleanup_fn,3276void*policy_cb_data)3277{3278struct files_ref_store *refs =3279files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3280static struct lock_file reflog_lock;3281struct expire_reflog_cb cb;3282struct ref_lock *lock;3283struct strbuf log_file_sb = STRBUF_INIT;3284char*log_file;3285int status =0;3286int type;3287struct strbuf err = STRBUF_INIT;3288struct object_id oid;32893290memset(&cb,0,sizeof(cb));3291 cb.flags = flags;3292 cb.policy_cb = policy_cb_data;3293 cb.should_prune_fn = should_prune_fn;32943295/*3296 * The reflog file is locked by holding the lock on the3297 * reference itself, plus we might need to update the3298 * reference if --updateref was specified:3299 */3300 lock =lock_ref_sha1_basic(refs, refname, sha1,3301 NULL, NULL, REF_NODEREF,3302&type, &err);3303if(!lock) {3304error("cannot lock ref '%s':%s", refname, err.buf);3305strbuf_release(&err);3306return-1;3307}3308if(!refs_reflog_exists(ref_store, refname)) {3309unlock_ref(lock);3310return0;3311}33123313files_reflog_path(refs, &log_file_sb, refname);3314 log_file =strbuf_detach(&log_file_sb, NULL);3315if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3316/*3317 * Even though holding $GIT_DIR/logs/$reflog.lock has3318 * no locking implications, we use the lock_file3319 * machinery here anyway because it does a lot of the3320 * work we need, including cleaning up if the program3321 * exits unexpectedly.3322 */3323if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3324struct strbuf err = STRBUF_INIT;3325unable_to_lock_message(log_file, errno, &err);3326error("%s", err.buf);3327strbuf_release(&err);3328goto failure;3329}3330 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3331if(!cb.newlog) {3332error("cannot fdopen%s(%s)",3333get_lock_file_path(&reflog_lock),strerror(errno));3334goto failure;3335}3336}33373338hashcpy(oid.hash, sha1);33393340(*prepare_fn)(refname, &oid, cb.policy_cb);3341refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3342(*cleanup_fn)(cb.policy_cb);33433344if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3345/*3346 * It doesn't make sense to adjust a reference pointed3347 * to by a symbolic ref based on expiring entries in3348 * the symbolic reference's reflog. Nor can we update3349 * a reference if there are no remaining reflog3350 * entries.3351 */3352int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3353!(type & REF_ISSYMREF) &&3354!is_null_oid(&cb.last_kept_oid);33553356if(close_lock_file(&reflog_lock)) {3357 status |=error("couldn't write%s:%s", log_file,3358strerror(errno));3359}else if(update &&3360(write_in_full(get_lock_file_fd(lock->lk),3361oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3362write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3363close_ref(lock) <0)) {3364 status |=error("couldn't write%s",3365get_lock_file_path(lock->lk));3366rollback_lock_file(&reflog_lock);3367}else if(commit_lock_file(&reflog_lock)) {3368 status |=error("unable to write reflog '%s' (%s)",3369 log_file,strerror(errno));3370}else if(update &&commit_ref(lock)) {3371 status |=error("couldn't set%s", lock->ref_name);3372}3373}3374free(log_file);3375unlock_ref(lock);3376return status;33773378 failure:3379rollback_lock_file(&reflog_lock);3380free(log_file);3381unlock_ref(lock);3382return-1;3383}33843385static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3386{3387struct files_ref_store *refs =3388files_downcast(ref_store, REF_STORE_WRITE,"init_db");3389struct strbuf sb = STRBUF_INIT;33903391/*3392 * Create .git/refs/{heads,tags}3393 */3394files_ref_path(refs, &sb,"refs/heads");3395safe_create_dir(sb.buf,1);33963397strbuf_reset(&sb);3398files_ref_path(refs, &sb,"refs/tags");3399safe_create_dir(sb.buf,1);34003401strbuf_release(&sb);3402return0;3403}34043405struct ref_storage_be refs_be_files = {3406 NULL,3407"files",3408 files_ref_store_create,3409 files_init_db,3410 files_transaction_prepare,3411 files_transaction_finish,3412 files_transaction_abort,3413 files_initial_transaction_commit,34143415 files_pack_refs,3416 files_peel_ref,3417 files_create_symref,3418 files_delete_refs,3419 files_rename_ref,34203421 files_ref_iterator_begin,3422 files_read_raw_ref,34233424 files_reflog_iterator_begin,3425 files_for_each_reflog_ent,3426 files_for_each_reflog_ent_reverse,3427 files_reflog_exists,3428 files_create_reflog,3429 files_delete_reflog,3430 files_reflog_expire3431};