1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * A container for `packed-refs`-related data. It is not (yet) a 52 * `ref_store`. 53 */ 54struct packed_ref_store { 55unsigned int store_flags; 56 57/* The path of the "packed-refs" file: */ 58char*path; 59 60/* 61 * A cache of the values read from the `packed-refs` file, if 62 * it might still be current; otherwise, NULL. 63 */ 64struct packed_ref_cache *cache; 65 66/* 67 * Lock used for the "packed-refs" file. Note that this (and 68 * thus the enclosing `packed_ref_store`) must not be freed. 69 */ 70struct lock_file lock; 71}; 72 73static struct packed_ref_store *packed_ref_store_create( 74const char*path,unsigned int store_flags) 75{ 76struct packed_ref_store *refs =xcalloc(1,sizeof(*refs)); 77 78 refs->store_flags = store_flags; 79 refs->path =xstrdup(path); 80return refs; 81} 82 83/* 84 * Future: need to be in "struct repository" 85 * when doing a full libification. 86 */ 87struct files_ref_store { 88struct ref_store base; 89unsigned int store_flags; 90 91char*gitdir; 92char*gitcommondir; 93 94struct ref_cache *loose; 95 96struct packed_ref_store *packed_ref_store; 97}; 98 99/* 100 * Increment the reference count of *packed_refs. 101 */ 102static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 103{ 104 packed_refs->referrers++; 105} 106 107/* 108 * Decrease the reference count of *packed_refs. If it goes to zero, 109 * free *packed_refs and return true; otherwise return false. 110 */ 111static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 112{ 113if(!--packed_refs->referrers) { 114free_ref_cache(packed_refs->cache); 115stat_validity_clear(&packed_refs->validity); 116free(packed_refs); 117return1; 118}else{ 119return0; 120} 121} 122 123static voidclear_packed_ref_cache(struct packed_ref_store *refs) 124{ 125if(refs->cache) { 126struct packed_ref_cache *cache = refs->cache; 127 128if(is_lock_file_locked(&refs->lock)) 129die("BUG: packed-ref cache cleared while locked"); 130 refs->cache = NULL; 131release_packed_ref_cache(cache); 132} 133} 134 135static voidclear_loose_ref_cache(struct files_ref_store *refs) 136{ 137if(refs->loose) { 138free_ref_cache(refs->loose); 139 refs->loose = NULL; 140} 141} 142 143/* 144 * Create a new submodule ref cache and add it to the internal 145 * set of caches. 146 */ 147static struct ref_store *files_ref_store_create(const char*gitdir, 148unsigned int flags) 149{ 150struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 151struct ref_store *ref_store = (struct ref_store *)refs; 152struct strbuf sb = STRBUF_INIT; 153 154base_ref_store_init(ref_store, &refs_be_files); 155 refs->store_flags = flags; 156 157 refs->gitdir =xstrdup(gitdir); 158get_common_dir_noenv(&sb, gitdir); 159 refs->gitcommondir =strbuf_detach(&sb, NULL); 160strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 161 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 162strbuf_release(&sb); 163 164return ref_store; 165} 166 167/* 168 * Die if refs is not the main ref store. caller is used in any 169 * necessary error messages. 170 */ 171static voidfiles_assert_main_repository(struct files_ref_store *refs, 172const char*caller) 173{ 174if(refs->store_flags & REF_STORE_MAIN) 175return; 176 177die("BUG: operation%sonly allowed for main ref store", caller); 178} 179 180/* 181 * Downcast ref_store to files_ref_store. Die if ref_store is not a 182 * files_ref_store. required_flags is compared with ref_store's 183 * store_flags to ensure the ref_store has all required capabilities. 184 * "caller" is used in any necessary error messages. 185 */ 186static struct files_ref_store *files_downcast(struct ref_store *ref_store, 187unsigned int required_flags, 188const char*caller) 189{ 190struct files_ref_store *refs; 191 192if(ref_store->be != &refs_be_files) 193die("BUG: ref_store is type\"%s\"not\"files\"in%s", 194 ref_store->be->name, caller); 195 196 refs = (struct files_ref_store *)ref_store; 197 198if((refs->store_flags & required_flags) != required_flags) 199die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 200 caller, required_flags, refs->store_flags); 201 202return refs; 203} 204 205/* The length of a peeled reference line in packed-refs, including EOL: */ 206#define PEELED_LINE_LENGTH 42 207 208/* 209 * The packed-refs header line that we write out. Perhaps other 210 * traits will be added later. The trailing space is required. 211 */ 212static const char PACKED_REFS_HEADER[] = 213"# pack-refs with: peeled fully-peeled\n"; 214 215/* 216 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 217 * Return a pointer to the refname within the line (null-terminated), 218 * or NULL if there was a problem. 219 */ 220static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 221{ 222const char*ref; 223 224if(parse_oid_hex(line->buf, oid, &ref) <0) 225return NULL; 226if(!isspace(*ref++)) 227return NULL; 228 229if(isspace(*ref)) 230return NULL; 231 232if(line->buf[line->len -1] !='\n') 233return NULL; 234 line->buf[--line->len] =0; 235 236return ref; 237} 238 239/* 240 * Read from `packed_refs_file` into a newly-allocated 241 * `packed_ref_cache` and return it. The return value will already 242 * have its reference count incremented. 243 * 244 * A comment line of the form "# pack-refs with: " may contain zero or 245 * more traits. We interpret the traits as follows: 246 * 247 * No traits: 248 * 249 * Probably no references are peeled. But if the file contains a 250 * peeled value for a reference, we will use it. 251 * 252 * peeled: 253 * 254 * References under "refs/tags/", if they *can* be peeled, *are* 255 * peeled in this file. References outside of "refs/tags/" are 256 * probably not peeled even if they could have been, but if we find 257 * a peeled value for such a reference we will use it. 258 * 259 * fully-peeled: 260 * 261 * All references in the file that can be peeled are peeled. 262 * Inversely (and this is more important), any references in the 263 * file for which no peeled value is recorded is not peelable. This 264 * trait should typically be written alongside "peeled" for 265 * compatibility with older clients, but we do not require it 266 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 267 */ 268static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 269{ 270FILE*f; 271struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 272struct ref_entry *last = NULL; 273struct strbuf line = STRBUF_INIT; 274enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 275struct ref_dir *dir; 276 277acquire_packed_ref_cache(packed_refs); 278 packed_refs->cache =create_ref_cache(NULL, NULL); 279 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 280 281 f =fopen(packed_refs_file,"r"); 282if(!f) { 283if(errno == ENOENT) { 284/* 285 * This is OK; it just means that no 286 * "packed-refs" file has been written yet, 287 * which is equivalent to it being empty. 288 */ 289return packed_refs; 290}else{ 291die_errno("couldn't read%s", packed_refs_file); 292} 293} 294 295stat_validity_update(&packed_refs->validity,fileno(f)); 296 297 dir =get_ref_dir(packed_refs->cache->root); 298while(strbuf_getwholeline(&line, f,'\n') != EOF) { 299struct object_id oid; 300const char*refname; 301const char*traits; 302 303if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 304if(strstr(traits," fully-peeled ")) 305 peeled = PEELED_FULLY; 306else if(strstr(traits," peeled ")) 307 peeled = PEELED_TAGS; 308/* perhaps other traits later as well */ 309continue; 310} 311 312 refname =parse_ref_line(&line, &oid); 313if(refname) { 314int flag = REF_ISPACKED; 315 316if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 317if(!refname_is_safe(refname)) 318die("packed refname is dangerous:%s", refname); 319oidclr(&oid); 320 flag |= REF_BAD_NAME | REF_ISBROKEN; 321} 322 last =create_ref_entry(refname, &oid, flag); 323if(peeled == PEELED_FULLY || 324(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 325 last->flag |= REF_KNOWS_PEELED; 326add_ref_entry(dir, last); 327continue; 328} 329if(last && 330 line.buf[0] =='^'&& 331 line.len == PEELED_LINE_LENGTH && 332 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 333!get_oid_hex(line.buf +1, &oid)) { 334oidcpy(&last->u.value.peeled, &oid); 335/* 336 * Regardless of what the file header said, 337 * we definitely know the value of *this* 338 * reference: 339 */ 340 last->flag |= REF_KNOWS_PEELED; 341} 342} 343 344fclose(f); 345strbuf_release(&line); 346 347return packed_refs; 348} 349 350static voidfiles_reflog_path(struct files_ref_store *refs, 351struct strbuf *sb, 352const char*refname) 353{ 354if(!refname) { 355/* 356 * FIXME: of course this is wrong in multi worktree 357 * setting. To be fixed real soon. 358 */ 359strbuf_addf(sb,"%s/logs", refs->gitcommondir); 360return; 361} 362 363switch(ref_type(refname)) { 364case REF_TYPE_PER_WORKTREE: 365case REF_TYPE_PSEUDOREF: 366strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 367break; 368case REF_TYPE_NORMAL: 369strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 370break; 371default: 372die("BUG: unknown ref type%dof ref%s", 373ref_type(refname), refname); 374} 375} 376 377static voidfiles_ref_path(struct files_ref_store *refs, 378struct strbuf *sb, 379const char*refname) 380{ 381switch(ref_type(refname)) { 382case REF_TYPE_PER_WORKTREE: 383case REF_TYPE_PSEUDOREF: 384strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 385break; 386case REF_TYPE_NORMAL: 387strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 388break; 389default: 390die("BUG: unknown ref type%dof ref%s", 391ref_type(refname), refname); 392} 393} 394 395/* 396 * Check that the packed refs cache (if any) still reflects the 397 * contents of the file. If not, clear the cache. 398 */ 399static voidvalidate_packed_ref_cache(struct packed_ref_store *refs) 400{ 401if(refs->cache && 402!stat_validity_check(&refs->cache->validity, refs->path)) 403clear_packed_ref_cache(refs); 404} 405 406/* 407 * Get the packed_ref_cache for the specified files_ref_store, 408 * creating and populating it if it hasn't been read before or if the 409 * file has been changed (according to its `validity` field) since it 410 * was last read. On the other hand, if we hold the lock, then assume 411 * that the file hasn't been changed out from under us, so skip the 412 * extra `stat()` call in `stat_validity_check()`. 413 */ 414static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 415{ 416const char*packed_refs_file = refs->packed_ref_store->path; 417 418if(!is_lock_file_locked(&refs->packed_ref_store->lock)) 419validate_packed_ref_cache(refs->packed_ref_store); 420 421if(!refs->packed_ref_store->cache) 422 refs->packed_ref_store->cache =read_packed_refs(packed_refs_file); 423 424return refs->packed_ref_store->cache; 425} 426 427static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 428{ 429returnget_ref_dir(packed_ref_cache->cache->root); 430} 431 432static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 433{ 434returnget_packed_ref_dir(get_packed_ref_cache(refs)); 435} 436 437/* 438 * Add or overwrite a reference in the in-memory packed reference 439 * cache. This may only be called while the packed-refs file is locked 440 * (see lock_packed_refs()). To actually write the packed-refs file, 441 * call commit_packed_refs(). 442 */ 443static voidadd_packed_ref(struct files_ref_store *refs, 444const char*refname,const struct object_id *oid) 445{ 446struct ref_dir *packed_refs; 447struct ref_entry *packed_entry; 448 449if(!is_lock_file_locked(&refs->packed_ref_store->lock)) 450die("BUG: packed refs not locked"); 451 452if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 453die("Reference has invalid format: '%s'", refname); 454 455 packed_refs =get_packed_refs(refs); 456 packed_entry =find_ref_entry(packed_refs, refname); 457if(packed_entry) { 458/* Overwrite the existing entry: */ 459oidcpy(&packed_entry->u.value.oid, oid); 460 packed_entry->flag = REF_ISPACKED; 461oidclr(&packed_entry->u.value.peeled); 462}else{ 463 packed_entry =create_ref_entry(refname, oid, REF_ISPACKED); 464add_ref_entry(packed_refs, packed_entry); 465} 466} 467 468/* 469 * Read the loose references from the namespace dirname into dir 470 * (without recursing). dirname must end with '/'. dir must be the 471 * directory entry corresponding to dirname. 472 */ 473static voidloose_fill_ref_dir(struct ref_store *ref_store, 474struct ref_dir *dir,const char*dirname) 475{ 476struct files_ref_store *refs = 477files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 478DIR*d; 479struct dirent *de; 480int dirnamelen =strlen(dirname); 481struct strbuf refname; 482struct strbuf path = STRBUF_INIT; 483size_t path_baselen; 484 485files_ref_path(refs, &path, dirname); 486 path_baselen = path.len; 487 488 d =opendir(path.buf); 489if(!d) { 490strbuf_release(&path); 491return; 492} 493 494strbuf_init(&refname, dirnamelen +257); 495strbuf_add(&refname, dirname, dirnamelen); 496 497while((de =readdir(d)) != NULL) { 498struct object_id oid; 499struct stat st; 500int flag; 501 502if(de->d_name[0] =='.') 503continue; 504if(ends_with(de->d_name,".lock")) 505continue; 506strbuf_addstr(&refname, de->d_name); 507strbuf_addstr(&path, de->d_name); 508if(stat(path.buf, &st) <0) { 509;/* silently ignore */ 510}else if(S_ISDIR(st.st_mode)) { 511strbuf_addch(&refname,'/'); 512add_entry_to_dir(dir, 513create_dir_entry(dir->cache, refname.buf, 514 refname.len,1)); 515}else{ 516if(!refs_resolve_ref_unsafe(&refs->base, 517 refname.buf, 518 RESOLVE_REF_READING, 519 oid.hash, &flag)) { 520oidclr(&oid); 521 flag |= REF_ISBROKEN; 522}else if(is_null_oid(&oid)) { 523/* 524 * It is so astronomically unlikely 525 * that NULL_SHA1 is the SHA-1 of an 526 * actual object that we consider its 527 * appearance in a loose reference 528 * file to be repo corruption 529 * (probably due to a software bug). 530 */ 531 flag |= REF_ISBROKEN; 532} 533 534if(check_refname_format(refname.buf, 535 REFNAME_ALLOW_ONELEVEL)) { 536if(!refname_is_safe(refname.buf)) 537die("loose refname is dangerous:%s", refname.buf); 538oidclr(&oid); 539 flag |= REF_BAD_NAME | REF_ISBROKEN; 540} 541add_entry_to_dir(dir, 542create_ref_entry(refname.buf, &oid, flag)); 543} 544strbuf_setlen(&refname, dirnamelen); 545strbuf_setlen(&path, path_baselen); 546} 547strbuf_release(&refname); 548strbuf_release(&path); 549closedir(d); 550 551/* 552 * Manually add refs/bisect, which, being per-worktree, might 553 * not appear in the directory listing for refs/ in the main 554 * repo. 555 */ 556if(!strcmp(dirname,"refs/")) { 557int pos =search_ref_dir(dir,"refs/bisect/",12); 558 559if(pos <0) { 560struct ref_entry *child_entry =create_dir_entry( 561 dir->cache,"refs/bisect/",12,1); 562add_entry_to_dir(dir, child_entry); 563} 564} 565} 566 567static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 568{ 569if(!refs->loose) { 570/* 571 * Mark the top-level directory complete because we 572 * are about to read the only subdirectory that can 573 * hold references: 574 */ 575 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 576 577/* We're going to fill the top level ourselves: */ 578 refs->loose->root->flag &= ~REF_INCOMPLETE; 579 580/* 581 * Add an incomplete entry for "refs/" (to be filled 582 * lazily): 583 */ 584add_entry_to_dir(get_ref_dir(refs->loose->root), 585create_dir_entry(refs->loose,"refs/",5,1)); 586} 587return refs->loose; 588} 589 590/* 591 * Return the ref_entry for the given refname from the packed 592 * references. If it does not exist, return NULL. 593 */ 594static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 595const char*refname) 596{ 597returnfind_ref_entry(get_packed_refs(refs), refname); 598} 599 600/* 601 * A loose ref file doesn't exist; check for a packed ref. 602 */ 603static intresolve_packed_ref(struct files_ref_store *refs, 604const char*refname, 605unsigned char*sha1,unsigned int*flags) 606{ 607struct ref_entry *entry; 608 609/* 610 * The loose reference file does not exist; check for a packed 611 * reference. 612 */ 613 entry =get_packed_ref(refs, refname); 614if(entry) { 615hashcpy(sha1, entry->u.value.oid.hash); 616*flags |= REF_ISPACKED; 617return0; 618} 619/* refname is not a packed reference. */ 620return-1; 621} 622 623static intfiles_read_raw_ref(struct ref_store *ref_store, 624const char*refname,unsigned char*sha1, 625struct strbuf *referent,unsigned int*type) 626{ 627struct files_ref_store *refs = 628files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 629struct strbuf sb_contents = STRBUF_INIT; 630struct strbuf sb_path = STRBUF_INIT; 631const char*path; 632const char*buf; 633struct stat st; 634int fd; 635int ret = -1; 636int save_errno; 637int remaining_retries =3; 638 639*type =0; 640strbuf_reset(&sb_path); 641 642files_ref_path(refs, &sb_path, refname); 643 644 path = sb_path.buf; 645 646stat_ref: 647/* 648 * We might have to loop back here to avoid a race 649 * condition: first we lstat() the file, then we try 650 * to read it as a link or as a file. But if somebody 651 * changes the type of the file (file <-> directory 652 * <-> symlink) between the lstat() and reading, then 653 * we don't want to report that as an error but rather 654 * try again starting with the lstat(). 655 * 656 * We'll keep a count of the retries, though, just to avoid 657 * any confusing situation sending us into an infinite loop. 658 */ 659 660if(remaining_retries-- <=0) 661goto out; 662 663if(lstat(path, &st) <0) { 664if(errno != ENOENT) 665goto out; 666if(resolve_packed_ref(refs, refname, sha1, type)) { 667 errno = ENOENT; 668goto out; 669} 670 ret =0; 671goto out; 672} 673 674/* Follow "normalized" - ie "refs/.." symlinks by hand */ 675if(S_ISLNK(st.st_mode)) { 676strbuf_reset(&sb_contents); 677if(strbuf_readlink(&sb_contents, path,0) <0) { 678if(errno == ENOENT || errno == EINVAL) 679/* inconsistent with lstat; retry */ 680goto stat_ref; 681else 682goto out; 683} 684if(starts_with(sb_contents.buf,"refs/") && 685!check_refname_format(sb_contents.buf,0)) { 686strbuf_swap(&sb_contents, referent); 687*type |= REF_ISSYMREF; 688 ret =0; 689goto out; 690} 691/* 692 * It doesn't look like a refname; fall through to just 693 * treating it like a non-symlink, and reading whatever it 694 * points to. 695 */ 696} 697 698/* Is it a directory? */ 699if(S_ISDIR(st.st_mode)) { 700/* 701 * Even though there is a directory where the loose 702 * ref is supposed to be, there could still be a 703 * packed ref: 704 */ 705if(resolve_packed_ref(refs, refname, sha1, type)) { 706 errno = EISDIR; 707goto out; 708} 709 ret =0; 710goto out; 711} 712 713/* 714 * Anything else, just open it and try to use it as 715 * a ref 716 */ 717 fd =open(path, O_RDONLY); 718if(fd <0) { 719if(errno == ENOENT && !S_ISLNK(st.st_mode)) 720/* inconsistent with lstat; retry */ 721goto stat_ref; 722else 723goto out; 724} 725strbuf_reset(&sb_contents); 726if(strbuf_read(&sb_contents, fd,256) <0) { 727int save_errno = errno; 728close(fd); 729 errno = save_errno; 730goto out; 731} 732close(fd); 733strbuf_rtrim(&sb_contents); 734 buf = sb_contents.buf; 735if(starts_with(buf,"ref:")) { 736 buf +=4; 737while(isspace(*buf)) 738 buf++; 739 740strbuf_reset(referent); 741strbuf_addstr(referent, buf); 742*type |= REF_ISSYMREF; 743 ret =0; 744goto out; 745} 746 747/* 748 * Please note that FETCH_HEAD has additional 749 * data after the sha. 750 */ 751if(get_sha1_hex(buf, sha1) || 752(buf[40] !='\0'&& !isspace(buf[40]))) { 753*type |= REF_ISBROKEN; 754 errno = EINVAL; 755goto out; 756} 757 758 ret =0; 759 760out: 761 save_errno = errno; 762strbuf_release(&sb_path); 763strbuf_release(&sb_contents); 764 errno = save_errno; 765return ret; 766} 767 768static voidunlock_ref(struct ref_lock *lock) 769{ 770/* Do not free lock->lk -- atexit() still looks at them */ 771if(lock->lk) 772rollback_lock_file(lock->lk); 773free(lock->ref_name); 774free(lock); 775} 776 777/* 778 * Lock refname, without following symrefs, and set *lock_p to point 779 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 780 * and type similarly to read_raw_ref(). 781 * 782 * The caller must verify that refname is a "safe" reference name (in 783 * the sense of refname_is_safe()) before calling this function. 784 * 785 * If the reference doesn't already exist, verify that refname doesn't 786 * have a D/F conflict with any existing references. extras and skip 787 * are passed to refs_verify_refname_available() for this check. 788 * 789 * If mustexist is not set and the reference is not found or is 790 * broken, lock the reference anyway but clear sha1. 791 * 792 * Return 0 on success. On failure, write an error message to err and 793 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 794 * 795 * Implementation note: This function is basically 796 * 797 * lock reference 798 * read_raw_ref() 799 * 800 * but it includes a lot more code to 801 * - Deal with possible races with other processes 802 * - Avoid calling refs_verify_refname_available() when it can be 803 * avoided, namely if we were successfully able to read the ref 804 * - Generate informative error messages in the case of failure 805 */ 806static intlock_raw_ref(struct files_ref_store *refs, 807const char*refname,int mustexist, 808const struct string_list *extras, 809const struct string_list *skip, 810struct ref_lock **lock_p, 811struct strbuf *referent, 812unsigned int*type, 813struct strbuf *err) 814{ 815struct ref_lock *lock; 816struct strbuf ref_file = STRBUF_INIT; 817int attempts_remaining =3; 818int ret = TRANSACTION_GENERIC_ERROR; 819 820assert(err); 821files_assert_main_repository(refs,"lock_raw_ref"); 822 823*type =0; 824 825/* First lock the file so it can't change out from under us. */ 826 827*lock_p = lock =xcalloc(1,sizeof(*lock)); 828 829 lock->ref_name =xstrdup(refname); 830files_ref_path(refs, &ref_file, refname); 831 832retry: 833switch(safe_create_leading_directories(ref_file.buf)) { 834case SCLD_OK: 835break;/* success */ 836case SCLD_EXISTS: 837/* 838 * Suppose refname is "refs/foo/bar". We just failed 839 * to create the containing directory, "refs/foo", 840 * because there was a non-directory in the way. This 841 * indicates a D/F conflict, probably because of 842 * another reference such as "refs/foo". There is no 843 * reason to expect this error to be transitory. 844 */ 845if(refs_verify_refname_available(&refs->base, refname, 846 extras, skip, err)) { 847if(mustexist) { 848/* 849 * To the user the relevant error is 850 * that the "mustexist" reference is 851 * missing: 852 */ 853strbuf_reset(err); 854strbuf_addf(err,"unable to resolve reference '%s'", 855 refname); 856}else{ 857/* 858 * The error message set by 859 * refs_verify_refname_available() is 860 * OK. 861 */ 862 ret = TRANSACTION_NAME_CONFLICT; 863} 864}else{ 865/* 866 * The file that is in the way isn't a loose 867 * reference. Report it as a low-level 868 * failure. 869 */ 870strbuf_addf(err,"unable to create lock file%s.lock; " 871"non-directory in the way", 872 ref_file.buf); 873} 874goto error_return; 875case SCLD_VANISHED: 876/* Maybe another process was tidying up. Try again. */ 877if(--attempts_remaining >0) 878goto retry; 879/* fall through */ 880default: 881strbuf_addf(err,"unable to create directory for%s", 882 ref_file.buf); 883goto error_return; 884} 885 886if(!lock->lk) 887 lock->lk =xcalloc(1,sizeof(struct lock_file)); 888 889if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 890if(errno == ENOENT && --attempts_remaining >0) { 891/* 892 * Maybe somebody just deleted one of the 893 * directories leading to ref_file. Try 894 * again: 895 */ 896goto retry; 897}else{ 898unable_to_lock_message(ref_file.buf, errno, err); 899goto error_return; 900} 901} 902 903/* 904 * Now we hold the lock and can read the reference without 905 * fear that its value will change. 906 */ 907 908if(files_read_raw_ref(&refs->base, refname, 909 lock->old_oid.hash, referent, type)) { 910if(errno == ENOENT) { 911if(mustexist) { 912/* Garden variety missing reference. */ 913strbuf_addf(err,"unable to resolve reference '%s'", 914 refname); 915goto error_return; 916}else{ 917/* 918 * Reference is missing, but that's OK. We 919 * know that there is not a conflict with 920 * another loose reference because 921 * (supposing that we are trying to lock 922 * reference "refs/foo/bar"): 923 * 924 * - We were successfully able to create 925 * the lockfile refs/foo/bar.lock, so we 926 * know there cannot be a loose reference 927 * named "refs/foo". 928 * 929 * - We got ENOENT and not EISDIR, so we 930 * know that there cannot be a loose 931 * reference named "refs/foo/bar/baz". 932 */ 933} 934}else if(errno == EISDIR) { 935/* 936 * There is a directory in the way. It might have 937 * contained references that have been deleted. If 938 * we don't require that the reference already 939 * exists, try to remove the directory so that it 940 * doesn't cause trouble when we want to rename the 941 * lockfile into place later. 942 */ 943if(mustexist) { 944/* Garden variety missing reference. */ 945strbuf_addf(err,"unable to resolve reference '%s'", 946 refname); 947goto error_return; 948}else if(remove_dir_recursively(&ref_file, 949 REMOVE_DIR_EMPTY_ONLY)) { 950if(refs_verify_refname_available( 951&refs->base, refname, 952 extras, skip, err)) { 953/* 954 * The error message set by 955 * verify_refname_available() is OK. 956 */ 957 ret = TRANSACTION_NAME_CONFLICT; 958goto error_return; 959}else{ 960/* 961 * We can't delete the directory, 962 * but we also don't know of any 963 * references that it should 964 * contain. 965 */ 966strbuf_addf(err,"there is a non-empty directory '%s' " 967"blocking reference '%s'", 968 ref_file.buf, refname); 969goto error_return; 970} 971} 972}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 973strbuf_addf(err,"unable to resolve reference '%s': " 974"reference broken", refname); 975goto error_return; 976}else{ 977strbuf_addf(err,"unable to resolve reference '%s':%s", 978 refname,strerror(errno)); 979goto error_return; 980} 981 982/* 983 * If the ref did not exist and we are creating it, 984 * make sure there is no existing ref that conflicts 985 * with refname: 986 */ 987if(refs_verify_refname_available( 988&refs->base, refname, 989 extras, skip, err)) 990goto error_return; 991} 992 993 ret =0; 994goto out; 995 996error_return: 997unlock_ref(lock); 998*lock_p = NULL; 9991000out:1001strbuf_release(&ref_file);1002return ret;1003}10041005static intfiles_peel_ref(struct ref_store *ref_store,1006const char*refname,unsigned char*sha1)1007{1008struct files_ref_store *refs =1009files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,1010"peel_ref");1011int flag;1012unsigned char base[20];10131014if(current_ref_iter && current_ref_iter->refname == refname) {1015struct object_id peeled;10161017if(ref_iterator_peel(current_ref_iter, &peeled))1018return-1;1019hashcpy(sha1, peeled.hash);1020return0;1021}10221023if(refs_read_ref_full(ref_store, refname,1024 RESOLVE_REF_READING, base, &flag))1025return-1;10261027/*1028 * If the reference is packed, read its ref_entry from the1029 * cache in the hope that we already know its peeled value.1030 * We only try this optimization on packed references because1031 * (a) forcing the filling of the loose reference cache could1032 * be expensive and (b) loose references anyway usually do not1033 * have REF_KNOWS_PEELED.1034 */1035if(flag & REF_ISPACKED) {1036struct ref_entry *r =get_packed_ref(refs, refname);1037if(r) {1038if(peel_entry(r,0))1039return-1;1040hashcpy(sha1, r->u.value.peeled.hash);1041return0;1042}1043}10441045returnpeel_object(base, sha1);1046}10471048struct files_ref_iterator {1049struct ref_iterator base;10501051struct packed_ref_cache *packed_ref_cache;1052struct ref_iterator *iter0;1053unsigned int flags;1054};10551056static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1057{1058struct files_ref_iterator *iter =1059(struct files_ref_iterator *)ref_iterator;1060int ok;10611062while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1063if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1064ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1065continue;10661067if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1068!ref_resolves_to_object(iter->iter0->refname,1069 iter->iter0->oid,1070 iter->iter0->flags))1071continue;10721073 iter->base.refname = iter->iter0->refname;1074 iter->base.oid = iter->iter0->oid;1075 iter->base.flags = iter->iter0->flags;1076return ITER_OK;1077}10781079 iter->iter0 = NULL;1080if(ref_iterator_abort(ref_iterator) != ITER_DONE)1081 ok = ITER_ERROR;10821083return ok;1084}10851086static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1087struct object_id *peeled)1088{1089struct files_ref_iterator *iter =1090(struct files_ref_iterator *)ref_iterator;10911092returnref_iterator_peel(iter->iter0, peeled);1093}10941095static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1096{1097struct files_ref_iterator *iter =1098(struct files_ref_iterator *)ref_iterator;1099int ok = ITER_DONE;11001101if(iter->iter0)1102 ok =ref_iterator_abort(iter->iter0);11031104release_packed_ref_cache(iter->packed_ref_cache);1105base_ref_iterator_free(ref_iterator);1106return ok;1107}11081109static struct ref_iterator_vtable files_ref_iterator_vtable = {1110 files_ref_iterator_advance,1111 files_ref_iterator_peel,1112 files_ref_iterator_abort1113};11141115static struct ref_iterator *files_ref_iterator_begin(1116struct ref_store *ref_store,1117const char*prefix,unsigned int flags)1118{1119struct files_ref_store *refs;1120struct ref_iterator *loose_iter, *packed_iter;1121struct files_ref_iterator *iter;1122struct ref_iterator *ref_iterator;1123unsigned int required_flags = REF_STORE_READ;11241125if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1126 required_flags |= REF_STORE_ODB;11271128 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11291130 iter =xcalloc(1,sizeof(*iter));1131 ref_iterator = &iter->base;1132base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11331134/*1135 * We must make sure that all loose refs are read before1136 * accessing the packed-refs file; this avoids a race1137 * condition if loose refs are migrated to the packed-refs1138 * file by a simultaneous process, but our in-memory view is1139 * from before the migration. We ensure this as follows:1140 * First, we call start the loose refs iteration with its1141 * `prime_ref` argument set to true. This causes the loose1142 * references in the subtree to be pre-read into the cache.1143 * (If they've already been read, that's OK; we only need to1144 * guarantee that they're read before the packed refs, not1145 * *how much* before.) After that, we call1146 * get_packed_ref_cache(), which internally checks whether the1147 * packed-ref cache is up to date with what is on disk, and1148 * re-reads it if not.1149 */11501151 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1152 prefix,1);11531154 iter->packed_ref_cache =get_packed_ref_cache(refs);1155acquire_packed_ref_cache(iter->packed_ref_cache);1156 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1157 prefix,0);11581159 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1160 iter->flags = flags;11611162return ref_iterator;1163}11641165/*1166 * Verify that the reference locked by lock has the value old_sha1.1167 * Fail if the reference doesn't exist and mustexist is set. Return 01168 * on success. On error, write an error message to err, set errno, and1169 * return a negative value.1170 */1171static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1172const unsigned char*old_sha1,int mustexist,1173struct strbuf *err)1174{1175assert(err);11761177if(refs_read_ref_full(ref_store, lock->ref_name,1178 mustexist ? RESOLVE_REF_READING :0,1179 lock->old_oid.hash, NULL)) {1180if(old_sha1) {1181int save_errno = errno;1182strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1183 errno = save_errno;1184return-1;1185}else{1186oidclr(&lock->old_oid);1187return0;1188}1189}1190if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1191strbuf_addf(err,"ref '%s' is at%sbut expected%s",1192 lock->ref_name,1193oid_to_hex(&lock->old_oid),1194sha1_to_hex(old_sha1));1195 errno = EBUSY;1196return-1;1197}1198return0;1199}12001201static intremove_empty_directories(struct strbuf *path)1202{1203/*1204 * we want to create a file but there is a directory there;1205 * if that is an empty directory (or a directory that contains1206 * only empty directories), remove them.1207 */1208returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1209}12101211static intcreate_reflock(const char*path,void*cb)1212{1213struct lock_file *lk = cb;12141215returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1216}12171218/*1219 * Locks a ref returning the lock on success and NULL on failure.1220 * On failure errno is set to something meaningful.1221 */1222static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1223const char*refname,1224const unsigned char*old_sha1,1225const struct string_list *extras,1226const struct string_list *skip,1227unsigned int flags,int*type,1228struct strbuf *err)1229{1230struct strbuf ref_file = STRBUF_INIT;1231struct ref_lock *lock;1232int last_errno =0;1233int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1234int resolve_flags = RESOLVE_REF_NO_RECURSE;1235int resolved;12361237files_assert_main_repository(refs,"lock_ref_sha1_basic");1238assert(err);12391240 lock =xcalloc(1,sizeof(struct ref_lock));12411242if(mustexist)1243 resolve_flags |= RESOLVE_REF_READING;1244if(flags & REF_DELETING)1245 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12461247files_ref_path(refs, &ref_file, refname);1248 resolved = !!refs_resolve_ref_unsafe(&refs->base,1249 refname, resolve_flags,1250 lock->old_oid.hash, type);1251if(!resolved && errno == EISDIR) {1252/*1253 * we are trying to lock foo but we used to1254 * have foo/bar which now does not exist;1255 * it is normal for the empty directory 'foo'1256 * to remain.1257 */1258if(remove_empty_directories(&ref_file)) {1259 last_errno = errno;1260if(!refs_verify_refname_available(1261&refs->base,1262 refname, extras, skip, err))1263strbuf_addf(err,"there are still refs under '%s'",1264 refname);1265goto error_return;1266}1267 resolved = !!refs_resolve_ref_unsafe(&refs->base,1268 refname, resolve_flags,1269 lock->old_oid.hash, type);1270}1271if(!resolved) {1272 last_errno = errno;1273if(last_errno != ENOTDIR ||1274!refs_verify_refname_available(&refs->base, refname,1275 extras, skip, err))1276strbuf_addf(err,"unable to resolve reference '%s':%s",1277 refname,strerror(last_errno));12781279goto error_return;1280}12811282/*1283 * If the ref did not exist and we are creating it, make sure1284 * there is no existing packed ref whose name begins with our1285 * refname, nor a packed ref whose name is a proper prefix of1286 * our refname.1287 */1288if(is_null_oid(&lock->old_oid) &&1289refs_verify_refname_available(&refs->base, refname,1290 extras, skip, err)) {1291 last_errno = ENOTDIR;1292goto error_return;1293}12941295 lock->lk =xcalloc(1,sizeof(struct lock_file));12961297 lock->ref_name =xstrdup(refname);12981299if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1300 last_errno = errno;1301unable_to_lock_message(ref_file.buf, errno, err);1302goto error_return;1303}13041305if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1306 last_errno = errno;1307goto error_return;1308}1309goto out;13101311 error_return:1312unlock_ref(lock);1313 lock = NULL;13141315 out:1316strbuf_release(&ref_file);1317 errno = last_errno;1318return lock;1319}13201321/*1322 * Write an entry to the packed-refs file for the specified refname.1323 * If peeled is non-NULL, write it as the entry's peeled value.1324 */1325static voidwrite_packed_entry(FILE*fh,const char*refname,1326const unsigned char*sha1,1327const unsigned char*peeled)1328{1329fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1330if(peeled)1331fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1332}13331334/*1335 * Lock the packed-refs file for writing. Flags is passed to1336 * hold_lock_file_for_update(). Return 0 on success. On errors, set1337 * errno appropriately and return a nonzero value.1338 */1339static intlock_packed_refs(struct files_ref_store *refs,int flags)1340{1341static int timeout_configured =0;1342static int timeout_value =1000;1343struct packed_ref_cache *packed_ref_cache;13441345files_assert_main_repository(refs,"lock_packed_refs");13461347if(!timeout_configured) {1348git_config_get_int("core.packedrefstimeout", &timeout_value);1349 timeout_configured =1;1350}13511352if(hold_lock_file_for_update_timeout(1353&refs->packed_ref_store->lock,1354 refs->packed_ref_store->path,1355 flags, timeout_value) <0)1356return-1;13571358/*1359 * Now that we hold the `packed-refs` lock, make sure that our1360 * cache matches the current version of the file. Normally1361 * `get_packed_ref_cache()` does that for us, but that1362 * function assumes that when the file is locked, any existing1363 * cache is still valid. We've just locked the file, but it1364 * might have changed the moment *before* we locked it.1365 */1366validate_packed_ref_cache(refs->packed_ref_store);13671368 packed_ref_cache =get_packed_ref_cache(refs);1369/* Increment the reference count to prevent it from being freed: */1370acquire_packed_ref_cache(packed_ref_cache);1371return0;1372}13731374/*1375 * Write the current version of the packed refs cache from memory to1376 * disk. The packed-refs file must already be locked for writing (see1377 * lock_packed_refs()). Return zero on success. On errors, set errno1378 * and return a nonzero value1379 */1380static intcommit_packed_refs(struct files_ref_store *refs)1381{1382struct packed_ref_cache *packed_ref_cache =1383get_packed_ref_cache(refs);1384int ok, error =0;1385int save_errno =0;1386FILE*out;1387struct ref_iterator *iter;13881389files_assert_main_repository(refs,"commit_packed_refs");13901391if(!is_lock_file_locked(&refs->packed_ref_store->lock))1392die("BUG: packed-refs not locked");13931394 out =fdopen_lock_file(&refs->packed_ref_store->lock,"w");1395if(!out)1396die_errno("unable to fdopen packed-refs descriptor");13971398fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13991400 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1401while((ok =ref_iterator_advance(iter)) == ITER_OK) {1402struct object_id peeled;1403int peel_error =ref_iterator_peel(iter, &peeled);14041405write_packed_entry(out, iter->refname, iter->oid->hash,1406 peel_error ? NULL : peeled.hash);1407}14081409if(ok != ITER_DONE)1410die("error while iterating over references");14111412if(commit_lock_file(&refs->packed_ref_store->lock)) {1413 save_errno = errno;1414 error = -1;1415}1416release_packed_ref_cache(packed_ref_cache);1417 errno = save_errno;1418return error;1419}14201421/*1422 * Rollback the lockfile for the packed-refs file, and discard the1423 * in-memory packed reference cache. (The packed-refs file will be1424 * read anew if it is needed again after this function is called.)1425 */1426static voidrollback_packed_refs(struct files_ref_store *refs)1427{1428struct packed_ref_cache *packed_ref_cache =1429get_packed_ref_cache(refs);14301431files_assert_main_repository(refs,"rollback_packed_refs");14321433if(!is_lock_file_locked(&refs->packed_ref_store->lock))1434die("BUG: packed-refs not locked");1435rollback_lock_file(&refs->packed_ref_store->lock);1436release_packed_ref_cache(packed_ref_cache);1437clear_packed_ref_cache(refs->packed_ref_store);1438}14391440struct ref_to_prune {1441struct ref_to_prune *next;1442unsigned char sha1[20];1443char name[FLEX_ARRAY];1444};14451446enum{1447 REMOVE_EMPTY_PARENTS_REF =0x01,1448 REMOVE_EMPTY_PARENTS_REFLOG =0x021449};14501451/*1452 * Remove empty parent directories associated with the specified1453 * reference and/or its reflog, but spare [logs/]refs/ and immediate1454 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1455 * REMOVE_EMPTY_PARENTS_REFLOG.1456 */1457static voidtry_remove_empty_parents(struct files_ref_store *refs,1458const char*refname,1459unsigned int flags)1460{1461struct strbuf buf = STRBUF_INIT;1462struct strbuf sb = STRBUF_INIT;1463char*p, *q;1464int i;14651466strbuf_addstr(&buf, refname);1467 p = buf.buf;1468for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1469while(*p && *p !='/')1470 p++;1471/* tolerate duplicate slashes; see check_refname_format() */1472while(*p =='/')1473 p++;1474}1475 q = buf.buf + buf.len;1476while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1477while(q > p && *q !='/')1478 q--;1479while(q > p && *(q-1) =='/')1480 q--;1481if(q == p)1482break;1483strbuf_setlen(&buf, q - buf.buf);14841485strbuf_reset(&sb);1486files_ref_path(refs, &sb, buf.buf);1487if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1488 flags &= ~REMOVE_EMPTY_PARENTS_REF;14891490strbuf_reset(&sb);1491files_reflog_path(refs, &sb, buf.buf);1492if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1493 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1494}1495strbuf_release(&buf);1496strbuf_release(&sb);1497}14981499/* make sure nobody touched the ref, and unlink */1500static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1501{1502struct ref_transaction *transaction;1503struct strbuf err = STRBUF_INIT;15041505if(check_refname_format(r->name,0))1506return;15071508 transaction =ref_store_transaction_begin(&refs->base, &err);1509if(!transaction ||1510ref_transaction_delete(transaction, r->name, r->sha1,1511 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1512ref_transaction_commit(transaction, &err)) {1513ref_transaction_free(transaction);1514error("%s", err.buf);1515strbuf_release(&err);1516return;1517}1518ref_transaction_free(transaction);1519strbuf_release(&err);1520}15211522static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1523{1524while(r) {1525prune_ref(refs, r);1526 r = r->next;1527}1528}15291530/*1531 * Return true if the specified reference should be packed.1532 */1533static intshould_pack_ref(const char*refname,1534const struct object_id *oid,unsigned int ref_flags,1535unsigned int pack_flags)1536{1537/* Do not pack per-worktree refs: */1538if(ref_type(refname) != REF_TYPE_NORMAL)1539return0;15401541/* Do not pack non-tags unless PACK_REFS_ALL is set: */1542if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1543return0;15441545/* Do not pack symbolic refs: */1546if(ref_flags & REF_ISSYMREF)1547return0;15481549/* Do not pack broken refs: */1550if(!ref_resolves_to_object(refname, oid, ref_flags))1551return0;15521553return1;1554}15551556static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1557{1558struct files_ref_store *refs =1559files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1560"pack_refs");1561struct ref_iterator *iter;1562int ok;1563struct ref_to_prune *refs_to_prune = NULL;15641565lock_packed_refs(refs, LOCK_DIE_ON_ERROR);15661567 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1568while((ok =ref_iterator_advance(iter)) == ITER_OK) {1569/*1570 * If the loose reference can be packed, add an entry1571 * in the packed ref cache. If the reference should be1572 * pruned, also add it to refs_to_prune.1573 */1574if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1575 flags))1576continue;15771578/*1579 * Create an entry in the packed-refs cache equivalent1580 * to the one from the loose ref cache, except that1581 * we don't copy the peeled status, because we want it1582 * to be re-peeled.1583 */1584add_packed_ref(refs, iter->refname, iter->oid);15851586/* Schedule the loose reference for pruning if requested. */1587if((flags & PACK_REFS_PRUNE)) {1588struct ref_to_prune *n;1589FLEX_ALLOC_STR(n, name, iter->refname);1590hashcpy(n->sha1, iter->oid->hash);1591 n->next = refs_to_prune;1592 refs_to_prune = n;1593}1594}1595if(ok != ITER_DONE)1596die("error while iterating over references");15971598if(commit_packed_refs(refs))1599die_errno("unable to overwrite old ref-pack file");16001601prune_refs(refs, refs_to_prune);1602return0;1603}16041605/*1606 * Rewrite the packed-refs file, omitting any refs listed in1607 * 'refnames'. On error, leave packed-refs unchanged, write an error1608 * message to 'err', and return a nonzero value.1609 *1610 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1611 */1612static intrepack_without_refs(struct files_ref_store *refs,1613struct string_list *refnames,struct strbuf *err)1614{1615struct ref_dir *packed;1616struct string_list_item *refname;1617int ret, needs_repacking =0, removed =0;16181619files_assert_main_repository(refs,"repack_without_refs");1620assert(err);16211622/* Look for a packed ref */1623for_each_string_list_item(refname, refnames) {1624if(get_packed_ref(refs, refname->string)) {1625 needs_repacking =1;1626break;1627}1628}16291630/* Avoid locking if we have nothing to do */1631if(!needs_repacking)1632return0;/* no refname exists in packed refs */16331634if(lock_packed_refs(refs,0)) {1635unable_to_lock_message(refs->packed_ref_store->path, errno, err);1636return-1;1637}1638 packed =get_packed_refs(refs);16391640/* Remove refnames from the cache */1641for_each_string_list_item(refname, refnames)1642if(remove_entry_from_dir(packed, refname->string) != -1)1643 removed =1;1644if(!removed) {1645/*1646 * All packed entries disappeared while we were1647 * acquiring the lock.1648 */1649rollback_packed_refs(refs);1650return0;1651}16521653/* Write what remains */1654 ret =commit_packed_refs(refs);1655if(ret)1656strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1657strerror(errno));1658return ret;1659}16601661static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1662struct string_list *refnames,unsigned int flags)1663{1664struct files_ref_store *refs =1665files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1666struct strbuf err = STRBUF_INIT;1667int i, result =0;16681669if(!refnames->nr)1670return0;16711672 result =repack_without_refs(refs, refnames, &err);1673if(result) {1674/*1675 * If we failed to rewrite the packed-refs file, then1676 * it is unsafe to try to remove loose refs, because1677 * doing so might expose an obsolete packed value for1678 * a reference that might even point at an object that1679 * has been garbage collected.1680 */1681if(refnames->nr ==1)1682error(_("could not delete reference%s:%s"),1683 refnames->items[0].string, err.buf);1684else1685error(_("could not delete references:%s"), err.buf);16861687goto out;1688}16891690for(i =0; i < refnames->nr; i++) {1691const char*refname = refnames->items[i].string;16921693if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1694 result |=error(_("could not remove reference%s"), refname);1695}16961697out:1698strbuf_release(&err);1699return result;1700}17011702/*1703 * People using contrib's git-new-workdir have .git/logs/refs ->1704 * /some/other/path/.git/logs/refs, and that may live on another device.1705 *1706 * IOW, to avoid cross device rename errors, the temporary renamed log must1707 * live into logs/refs.1708 */1709#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"17101711struct rename_cb {1712const char*tmp_renamed_log;1713int true_errno;1714};17151716static intrename_tmp_log_callback(const char*path,void*cb_data)1717{1718struct rename_cb *cb = cb_data;17191720if(rename(cb->tmp_renamed_log, path)) {1721/*1722 * rename(a, b) when b is an existing directory ought1723 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1724 * Sheesh. Record the true errno for error reporting,1725 * but report EISDIR to raceproof_create_file() so1726 * that it knows to retry.1727 */1728 cb->true_errno = errno;1729if(errno == ENOTDIR)1730 errno = EISDIR;1731return-1;1732}else{1733return0;1734}1735}17361737static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1738{1739struct strbuf path = STRBUF_INIT;1740struct strbuf tmp = STRBUF_INIT;1741struct rename_cb cb;1742int ret;17431744files_reflog_path(refs, &path, newrefname);1745files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1746 cb.tmp_renamed_log = tmp.buf;1747 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1748if(ret) {1749if(errno == EISDIR)1750error("directory not empty:%s", path.buf);1751else1752error("unable to move logfile%sto%s:%s",1753 tmp.buf, path.buf,1754strerror(cb.true_errno));1755}17561757strbuf_release(&path);1758strbuf_release(&tmp);1759return ret;1760}17611762static intwrite_ref_to_lockfile(struct ref_lock *lock,1763const struct object_id *oid,struct strbuf *err);1764static intcommit_ref_update(struct files_ref_store *refs,1765struct ref_lock *lock,1766const struct object_id *oid,const char*logmsg,1767struct strbuf *err);17681769static intfiles_rename_ref(struct ref_store *ref_store,1770const char*oldrefname,const char*newrefname,1771const char*logmsg)1772{1773struct files_ref_store *refs =1774files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1775struct object_id oid, orig_oid;1776int flag =0, logmoved =0;1777struct ref_lock *lock;1778struct stat loginfo;1779struct strbuf sb_oldref = STRBUF_INIT;1780struct strbuf sb_newref = STRBUF_INIT;1781struct strbuf tmp_renamed_log = STRBUF_INIT;1782int log, ret;1783struct strbuf err = STRBUF_INIT;17841785files_reflog_path(refs, &sb_oldref, oldrefname);1786files_reflog_path(refs, &sb_newref, newrefname);1787files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17881789 log = !lstat(sb_oldref.buf, &loginfo);1790if(log &&S_ISLNK(loginfo.st_mode)) {1791 ret =error("reflog for%sis a symlink", oldrefname);1792goto out;1793}17941795if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1796 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1797 orig_oid.hash, &flag)) {1798 ret =error("refname%snot found", oldrefname);1799goto out;1800}18011802if(flag & REF_ISSYMREF) {1803 ret =error("refname%sis a symbolic ref, renaming it is not supported",1804 oldrefname);1805goto out;1806}1807if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1808 ret =1;1809goto out;1810}18111812if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1813 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1814 oldrefname,strerror(errno));1815goto out;1816}18171818if(refs_delete_ref(&refs->base, logmsg, oldrefname,1819 orig_oid.hash, REF_NODEREF)) {1820error("unable to delete old%s", oldrefname);1821goto rollback;1822}18231824/*1825 * Since we are doing a shallow lookup, oid is not the1826 * correct value to pass to delete_ref as old_oid. But that1827 * doesn't matter, because an old_oid check wouldn't add to1828 * the safety anyway; we want to delete the reference whatever1829 * its current value.1830 */1831if(!refs_read_ref_full(&refs->base, newrefname,1832 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1833 oid.hash, NULL) &&1834refs_delete_ref(&refs->base, NULL, newrefname,1835 NULL, REF_NODEREF)) {1836if(errno == EISDIR) {1837struct strbuf path = STRBUF_INIT;1838int result;18391840files_ref_path(refs, &path, newrefname);1841 result =remove_empty_directories(&path);1842strbuf_release(&path);18431844if(result) {1845error("Directory not empty:%s", newrefname);1846goto rollback;1847}1848}else{1849error("unable to delete existing%s", newrefname);1850goto rollback;1851}1852}18531854if(log &&rename_tmp_log(refs, newrefname))1855goto rollback;18561857 logmoved = log;18581859 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1860 REF_NODEREF, NULL, &err);1861if(!lock) {1862error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1863strbuf_release(&err);1864goto rollback;1865}1866oidcpy(&lock->old_oid, &orig_oid);18671868if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1869commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1870error("unable to write current sha1 into%s:%s", newrefname, err.buf);1871strbuf_release(&err);1872goto rollback;1873}18741875 ret =0;1876goto out;18771878 rollback:1879 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1880 REF_NODEREF, NULL, &err);1881if(!lock) {1882error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1883strbuf_release(&err);1884goto rollbacklog;1885}18861887 flag = log_all_ref_updates;1888 log_all_ref_updates = LOG_REFS_NONE;1889if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1890commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1891error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1892strbuf_release(&err);1893}1894 log_all_ref_updates = flag;18951896 rollbacklog:1897if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1898error("unable to restore logfile%sfrom%s:%s",1899 oldrefname, newrefname,strerror(errno));1900if(!logmoved && log &&1901rename(tmp_renamed_log.buf, sb_oldref.buf))1902error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1903 oldrefname,strerror(errno));1904 ret =1;1905 out:1906strbuf_release(&sb_newref);1907strbuf_release(&sb_oldref);1908strbuf_release(&tmp_renamed_log);19091910return ret;1911}19121913static intclose_ref(struct ref_lock *lock)1914{1915if(close_lock_file(lock->lk))1916return-1;1917return0;1918}19191920static intcommit_ref(struct ref_lock *lock)1921{1922char*path =get_locked_file_path(lock->lk);1923struct stat st;19241925if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1926/*1927 * There is a directory at the path we want to rename1928 * the lockfile to. Hopefully it is empty; try to1929 * delete it.1930 */1931size_t len =strlen(path);1932struct strbuf sb_path = STRBUF_INIT;19331934strbuf_attach(&sb_path, path, len, len);19351936/*1937 * If this fails, commit_lock_file() will also fail1938 * and will report the problem.1939 */1940remove_empty_directories(&sb_path);1941strbuf_release(&sb_path);1942}else{1943free(path);1944}19451946if(commit_lock_file(lock->lk))1947return-1;1948return0;1949}19501951static intopen_or_create_logfile(const char*path,void*cb)1952{1953int*fd = cb;19541955*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1956return(*fd <0) ? -1:0;1957}19581959/*1960 * Create a reflog for a ref. If force_create = 0, only create the1961 * reflog for certain refs (those for which should_autocreate_reflog1962 * returns non-zero). Otherwise, create it regardless of the reference1963 * name. If the logfile already existed or was created, return 0 and1964 * set *logfd to the file descriptor opened for appending to the file.1965 * If no logfile exists and we decided not to create one, return 0 and1966 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1967 * return -1.1968 */1969static intlog_ref_setup(struct files_ref_store *refs,1970const char*refname,int force_create,1971int*logfd,struct strbuf *err)1972{1973struct strbuf logfile_sb = STRBUF_INIT;1974char*logfile;19751976files_reflog_path(refs, &logfile_sb, refname);1977 logfile =strbuf_detach(&logfile_sb, NULL);19781979if(force_create ||should_autocreate_reflog(refname)) {1980if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1981if(errno == ENOENT)1982strbuf_addf(err,"unable to create directory for '%s': "1983"%s", logfile,strerror(errno));1984else if(errno == EISDIR)1985strbuf_addf(err,"there are still logs under '%s'",1986 logfile);1987else1988strbuf_addf(err,"unable to append to '%s':%s",1989 logfile,strerror(errno));19901991goto error;1992}1993}else{1994*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1995if(*logfd <0) {1996if(errno == ENOENT || errno == EISDIR) {1997/*1998 * The logfile doesn't already exist,1999 * but that is not an error; it only2000 * means that we won't write log2001 * entries to it.2002 */2003;2004}else{2005strbuf_addf(err,"unable to append to '%s':%s",2006 logfile,strerror(errno));2007goto error;2008}2009}2010}20112012if(*logfd >=0)2013adjust_shared_perm(logfile);20142015free(logfile);2016return0;20172018error:2019free(logfile);2020return-1;2021}20222023static intfiles_create_reflog(struct ref_store *ref_store,2024const char*refname,int force_create,2025struct strbuf *err)2026{2027struct files_ref_store *refs =2028files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2029int fd;20302031if(log_ref_setup(refs, refname, force_create, &fd, err))2032return-1;20332034if(fd >=0)2035close(fd);20362037return0;2038}20392040static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2041const struct object_id *new_oid,2042const char*committer,const char*msg)2043{2044int msglen, written;2045unsigned maxlen, len;2046char*logrec;20472048 msglen = msg ?strlen(msg) :0;2049 maxlen =strlen(committer) + msglen +100;2050 logrec =xmalloc(maxlen);2051 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2052oid_to_hex(old_oid),2053oid_to_hex(new_oid),2054 committer);2055if(msglen)2056 len +=copy_reflog_msg(logrec + len -1, msg) -1;20572058 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2059free(logrec);2060if(written != len)2061return-1;20622063return0;2064}20652066static intfiles_log_ref_write(struct files_ref_store *refs,2067const char*refname,const struct object_id *old_oid,2068const struct object_id *new_oid,const char*msg,2069int flags,struct strbuf *err)2070{2071int logfd, result;20722073if(log_all_ref_updates == LOG_REFS_UNSET)2074 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20752076 result =log_ref_setup(refs, refname,2077 flags & REF_FORCE_CREATE_REFLOG,2078&logfd, err);20792080if(result)2081return result;20822083if(logfd <0)2084return0;2085 result =log_ref_write_fd(logfd, old_oid, new_oid,2086git_committer_info(0), msg);2087if(result) {2088struct strbuf sb = STRBUF_INIT;2089int save_errno = errno;20902091files_reflog_path(refs, &sb, refname);2092strbuf_addf(err,"unable to append to '%s':%s",2093 sb.buf,strerror(save_errno));2094strbuf_release(&sb);2095close(logfd);2096return-1;2097}2098if(close(logfd)) {2099struct strbuf sb = STRBUF_INIT;2100int save_errno = errno;21012102files_reflog_path(refs, &sb, refname);2103strbuf_addf(err,"unable to append to '%s':%s",2104 sb.buf,strerror(save_errno));2105strbuf_release(&sb);2106return-1;2107}2108return0;2109}21102111/*2112 * Write sha1 into the open lockfile, then close the lockfile. On2113 * errors, rollback the lockfile, fill in *err and2114 * return -1.2115 */2116static intwrite_ref_to_lockfile(struct ref_lock *lock,2117const struct object_id *oid,struct strbuf *err)2118{2119static char term ='\n';2120struct object *o;2121int fd;21222123 o =parse_object(oid);2124if(!o) {2125strbuf_addf(err,2126"trying to write ref '%s' with nonexistent object%s",2127 lock->ref_name,oid_to_hex(oid));2128unlock_ref(lock);2129return-1;2130}2131if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2132strbuf_addf(err,2133"trying to write non-commit object%sto branch '%s'",2134oid_to_hex(oid), lock->ref_name);2135unlock_ref(lock);2136return-1;2137}2138 fd =get_lock_file_fd(lock->lk);2139if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2140write_in_full(fd, &term,1) !=1||2141close_ref(lock) <0) {2142strbuf_addf(err,2143"couldn't write '%s'",get_lock_file_path(lock->lk));2144unlock_ref(lock);2145return-1;2146}2147return0;2148}21492150/*2151 * Commit a change to a loose reference that has already been written2152 * to the loose reference lockfile. Also update the reflogs if2153 * necessary, using the specified lockmsg (which can be NULL).2154 */2155static intcommit_ref_update(struct files_ref_store *refs,2156struct ref_lock *lock,2157const struct object_id *oid,const char*logmsg,2158struct strbuf *err)2159{2160files_assert_main_repository(refs,"commit_ref_update");21612162clear_loose_ref_cache(refs);2163if(files_log_ref_write(refs, lock->ref_name,2164&lock->old_oid, oid,2165 logmsg,0, err)) {2166char*old_msg =strbuf_detach(err, NULL);2167strbuf_addf(err,"cannot update the ref '%s':%s",2168 lock->ref_name, old_msg);2169free(old_msg);2170unlock_ref(lock);2171return-1;2172}21732174if(strcmp(lock->ref_name,"HEAD") !=0) {2175/*2176 * Special hack: If a branch is updated directly and HEAD2177 * points to it (may happen on the remote side of a push2178 * for example) then logically the HEAD reflog should be2179 * updated too.2180 * A generic solution implies reverse symref information,2181 * but finding all symrefs pointing to the given branch2182 * would be rather costly for this rare event (the direct2183 * update of a branch) to be worth it. So let's cheat and2184 * check with HEAD only which should cover 99% of all usage2185 * scenarios (even 100% of the default ones).2186 */2187struct object_id head_oid;2188int head_flag;2189const char*head_ref;21902191 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2192 RESOLVE_REF_READING,2193 head_oid.hash, &head_flag);2194if(head_ref && (head_flag & REF_ISSYMREF) &&2195!strcmp(head_ref, lock->ref_name)) {2196struct strbuf log_err = STRBUF_INIT;2197if(files_log_ref_write(refs,"HEAD",2198&lock->old_oid, oid,2199 logmsg,0, &log_err)) {2200error("%s", log_err.buf);2201strbuf_release(&log_err);2202}2203}2204}22052206if(commit_ref(lock)) {2207strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2208unlock_ref(lock);2209return-1;2210}22112212unlock_ref(lock);2213return0;2214}22152216static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2217{2218int ret = -1;2219#ifndef NO_SYMLINK_HEAD2220char*ref_path =get_locked_file_path(lock->lk);2221unlink(ref_path);2222 ret =symlink(target, ref_path);2223free(ref_path);22242225if(ret)2226fprintf(stderr,"no symlink - falling back to symbolic ref\n");2227#endif2228return ret;2229}22302231static voidupdate_symref_reflog(struct files_ref_store *refs,2232struct ref_lock *lock,const char*refname,2233const char*target,const char*logmsg)2234{2235struct strbuf err = STRBUF_INIT;2236struct object_id new_oid;2237if(logmsg &&2238!refs_read_ref_full(&refs->base, target,2239 RESOLVE_REF_READING, new_oid.hash, NULL) &&2240files_log_ref_write(refs, refname, &lock->old_oid,2241&new_oid, logmsg,0, &err)) {2242error("%s", err.buf);2243strbuf_release(&err);2244}2245}22462247static intcreate_symref_locked(struct files_ref_store *refs,2248struct ref_lock *lock,const char*refname,2249const char*target,const char*logmsg)2250{2251if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2252update_symref_reflog(refs, lock, refname, target, logmsg);2253return0;2254}22552256if(!fdopen_lock_file(lock->lk,"w"))2257returnerror("unable to fdopen%s:%s",2258 lock->lk->tempfile.filename.buf,strerror(errno));22592260update_symref_reflog(refs, lock, refname, target, logmsg);22612262/* no error check; commit_ref will check ferror */2263fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2264if(commit_ref(lock) <0)2265returnerror("unable to write symref for%s:%s", refname,2266strerror(errno));2267return0;2268}22692270static intfiles_create_symref(struct ref_store *ref_store,2271const char*refname,const char*target,2272const char*logmsg)2273{2274struct files_ref_store *refs =2275files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2276struct strbuf err = STRBUF_INIT;2277struct ref_lock *lock;2278int ret;22792280 lock =lock_ref_sha1_basic(refs, refname, NULL,2281 NULL, NULL, REF_NODEREF, NULL,2282&err);2283if(!lock) {2284error("%s", err.buf);2285strbuf_release(&err);2286return-1;2287}22882289 ret =create_symref_locked(refs, lock, refname, target, logmsg);2290unlock_ref(lock);2291return ret;2292}22932294static intfiles_reflog_exists(struct ref_store *ref_store,2295const char*refname)2296{2297struct files_ref_store *refs =2298files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2299struct strbuf sb = STRBUF_INIT;2300struct stat st;2301int ret;23022303files_reflog_path(refs, &sb, refname);2304 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2305strbuf_release(&sb);2306return ret;2307}23082309static intfiles_delete_reflog(struct ref_store *ref_store,2310const char*refname)2311{2312struct files_ref_store *refs =2313files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2314struct strbuf sb = STRBUF_INIT;2315int ret;23162317files_reflog_path(refs, &sb, refname);2318 ret =remove_path(sb.buf);2319strbuf_release(&sb);2320return ret;2321}23222323static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2324{2325struct object_id ooid, noid;2326char*email_end, *message;2327 timestamp_t timestamp;2328int tz;2329const char*p = sb->buf;23302331/* old SP new SP name <email> SP time TAB msg LF */2332if(!sb->len || sb->buf[sb->len -1] !='\n'||2333parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2334parse_oid_hex(p, &noid, &p) || *p++ !=' '||2335!(email_end =strchr(p,'>')) ||2336 email_end[1] !=' '||2337!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2338!message || message[0] !=' '||2339(message[1] !='+'&& message[1] !='-') ||2340!isdigit(message[2]) || !isdigit(message[3]) ||2341!isdigit(message[4]) || !isdigit(message[5]))2342return0;/* corrupt? */2343 email_end[1] ='\0';2344 tz =strtol(message +1, NULL,10);2345if(message[6] !='\t')2346 message +=6;2347else2348 message +=7;2349returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2350}23512352static char*find_beginning_of_line(char*bob,char*scan)2353{2354while(bob < scan && *(--scan) !='\n')2355;/* keep scanning backwards */2356/*2357 * Return either beginning of the buffer, or LF at the end of2358 * the previous line.2359 */2360return scan;2361}23622363static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2364const char*refname,2365 each_reflog_ent_fn fn,2366void*cb_data)2367{2368struct files_ref_store *refs =2369files_downcast(ref_store, REF_STORE_READ,2370"for_each_reflog_ent_reverse");2371struct strbuf sb = STRBUF_INIT;2372FILE*logfp;2373long pos;2374int ret =0, at_tail =1;23752376files_reflog_path(refs, &sb, refname);2377 logfp =fopen(sb.buf,"r");2378strbuf_release(&sb);2379if(!logfp)2380return-1;23812382/* Jump to the end */2383if(fseek(logfp,0, SEEK_END) <0)2384 ret =error("cannot seek back reflog for%s:%s",2385 refname,strerror(errno));2386 pos =ftell(logfp);2387while(!ret &&0< pos) {2388int cnt;2389size_t nread;2390char buf[BUFSIZ];2391char*endp, *scanp;23922393/* Fill next block from the end */2394 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2395if(fseek(logfp, pos - cnt, SEEK_SET)) {2396 ret =error("cannot seek back reflog for%s:%s",2397 refname,strerror(errno));2398break;2399}2400 nread =fread(buf, cnt,1, logfp);2401if(nread !=1) {2402 ret =error("cannot read%dbytes from reflog for%s:%s",2403 cnt, refname,strerror(errno));2404break;2405}2406 pos -= cnt;24072408 scanp = endp = buf + cnt;2409if(at_tail && scanp[-1] =='\n')2410/* Looking at the final LF at the end of the file */2411 scanp--;2412 at_tail =0;24132414while(buf < scanp) {2415/*2416 * terminating LF of the previous line, or the beginning2417 * of the buffer.2418 */2419char*bp;24202421 bp =find_beginning_of_line(buf, scanp);24222423if(*bp =='\n') {2424/*2425 * The newline is the end of the previous line,2426 * so we know we have complete line starting2427 * at (bp + 1). Prefix it onto any prior data2428 * we collected for the line and process it.2429 */2430strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2431 scanp = bp;2432 endp = bp +1;2433 ret =show_one_reflog_ent(&sb, fn, cb_data);2434strbuf_reset(&sb);2435if(ret)2436break;2437}else if(!pos) {2438/*2439 * We are at the start of the buffer, and the2440 * start of the file; there is no previous2441 * line, and we have everything for this one.2442 * Process it, and we can end the loop.2443 */2444strbuf_splice(&sb,0,0, buf, endp - buf);2445 ret =show_one_reflog_ent(&sb, fn, cb_data);2446strbuf_reset(&sb);2447break;2448}24492450if(bp == buf) {2451/*2452 * We are at the start of the buffer, and there2453 * is more file to read backwards. Which means2454 * we are in the middle of a line. Note that we2455 * may get here even if *bp was a newline; that2456 * just means we are at the exact end of the2457 * previous line, rather than some spot in the2458 * middle.2459 *2460 * Save away what we have to be combined with2461 * the data from the next read.2462 */2463strbuf_splice(&sb,0,0, buf, endp - buf);2464break;2465}2466}24672468}2469if(!ret && sb.len)2470die("BUG: reverse reflog parser had leftover data");24712472fclose(logfp);2473strbuf_release(&sb);2474return ret;2475}24762477static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2478const char*refname,2479 each_reflog_ent_fn fn,void*cb_data)2480{2481struct files_ref_store *refs =2482files_downcast(ref_store, REF_STORE_READ,2483"for_each_reflog_ent");2484FILE*logfp;2485struct strbuf sb = STRBUF_INIT;2486int ret =0;24872488files_reflog_path(refs, &sb, refname);2489 logfp =fopen(sb.buf,"r");2490strbuf_release(&sb);2491if(!logfp)2492return-1;24932494while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2495 ret =show_one_reflog_ent(&sb, fn, cb_data);2496fclose(logfp);2497strbuf_release(&sb);2498return ret;2499}25002501struct files_reflog_iterator {2502struct ref_iterator base;25032504struct ref_store *ref_store;2505struct dir_iterator *dir_iterator;2506struct object_id oid;2507};25082509static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2510{2511struct files_reflog_iterator *iter =2512(struct files_reflog_iterator *)ref_iterator;2513struct dir_iterator *diter = iter->dir_iterator;2514int ok;25152516while((ok =dir_iterator_advance(diter)) == ITER_OK) {2517int flags;25182519if(!S_ISREG(diter->st.st_mode))2520continue;2521if(diter->basename[0] =='.')2522continue;2523if(ends_with(diter->basename,".lock"))2524continue;25252526if(refs_read_ref_full(iter->ref_store,2527 diter->relative_path,0,2528 iter->oid.hash, &flags)) {2529error("bad ref for%s", diter->path.buf);2530continue;2531}25322533 iter->base.refname = diter->relative_path;2534 iter->base.oid = &iter->oid;2535 iter->base.flags = flags;2536return ITER_OK;2537}25382539 iter->dir_iterator = NULL;2540if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2541 ok = ITER_ERROR;2542return ok;2543}25442545static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2546struct object_id *peeled)2547{2548die("BUG: ref_iterator_peel() called for reflog_iterator");2549}25502551static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2552{2553struct files_reflog_iterator *iter =2554(struct files_reflog_iterator *)ref_iterator;2555int ok = ITER_DONE;25562557if(iter->dir_iterator)2558 ok =dir_iterator_abort(iter->dir_iterator);25592560base_ref_iterator_free(ref_iterator);2561return ok;2562}25632564static struct ref_iterator_vtable files_reflog_iterator_vtable = {2565 files_reflog_iterator_advance,2566 files_reflog_iterator_peel,2567 files_reflog_iterator_abort2568};25692570static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2571{2572struct files_ref_store *refs =2573files_downcast(ref_store, REF_STORE_READ,2574"reflog_iterator_begin");2575struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2576struct ref_iterator *ref_iterator = &iter->base;2577struct strbuf sb = STRBUF_INIT;25782579base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2580files_reflog_path(refs, &sb, NULL);2581 iter->dir_iterator =dir_iterator_begin(sb.buf);2582 iter->ref_store = ref_store;2583strbuf_release(&sb);2584return ref_iterator;2585}25862587/*2588 * If update is a direct update of head_ref (the reference pointed to2589 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2590 */2591static intsplit_head_update(struct ref_update *update,2592struct ref_transaction *transaction,2593const char*head_ref,2594struct string_list *affected_refnames,2595struct strbuf *err)2596{2597struct string_list_item *item;2598struct ref_update *new_update;25992600if((update->flags & REF_LOG_ONLY) ||2601(update->flags & REF_ISPRUNING) ||2602(update->flags & REF_UPDATE_VIA_HEAD))2603return0;26042605if(strcmp(update->refname, head_ref))2606return0;26072608/*2609 * First make sure that HEAD is not already in the2610 * transaction. This insertion is O(N) in the transaction2611 * size, but it happens at most once per transaction.2612 */2613 item =string_list_insert(affected_refnames,"HEAD");2614if(item->util) {2615/* An entry already existed */2616strbuf_addf(err,2617"multiple updates for 'HEAD' (including one "2618"via its referent '%s') are not allowed",2619 update->refname);2620return TRANSACTION_NAME_CONFLICT;2621}26222623 new_update =ref_transaction_add_update(2624 transaction,"HEAD",2625 update->flags | REF_LOG_ONLY | REF_NODEREF,2626 update->new_oid.hash, update->old_oid.hash,2627 update->msg);26282629 item->util = new_update;26302631return0;2632}26332634/*2635 * update is for a symref that points at referent and doesn't have2636 * REF_NODEREF set. Split it into two updates:2637 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2638 * - A new, separate update for the referent reference2639 * Note that the new update will itself be subject to splitting when2640 * the iteration gets to it.2641 */2642static intsplit_symref_update(struct files_ref_store *refs,2643struct ref_update *update,2644const char*referent,2645struct ref_transaction *transaction,2646struct string_list *affected_refnames,2647struct strbuf *err)2648{2649struct string_list_item *item;2650struct ref_update *new_update;2651unsigned int new_flags;26522653/*2654 * First make sure that referent is not already in the2655 * transaction. This insertion is O(N) in the transaction2656 * size, but it happens at most once per symref in a2657 * transaction.2658 */2659 item =string_list_insert(affected_refnames, referent);2660if(item->util) {2661/* An entry already existed */2662strbuf_addf(err,2663"multiple updates for '%s' (including one "2664"via symref '%s') are not allowed",2665 referent, update->refname);2666return TRANSACTION_NAME_CONFLICT;2667}26682669 new_flags = update->flags;2670if(!strcmp(update->refname,"HEAD")) {2671/*2672 * Record that the new update came via HEAD, so that2673 * when we process it, split_head_update() doesn't try2674 * to add another reflog update for HEAD. Note that2675 * this bit will be propagated if the new_update2676 * itself needs to be split.2677 */2678 new_flags |= REF_UPDATE_VIA_HEAD;2679}26802681 new_update =ref_transaction_add_update(2682 transaction, referent, new_flags,2683 update->new_oid.hash, update->old_oid.hash,2684 update->msg);26852686 new_update->parent_update = update;26872688/*2689 * Change the symbolic ref update to log only. Also, it2690 * doesn't need to check its old SHA-1 value, as that will be2691 * done when new_update is processed.2692 */2693 update->flags |= REF_LOG_ONLY | REF_NODEREF;2694 update->flags &= ~REF_HAVE_OLD;26952696 item->util = new_update;26972698return0;2699}27002701/*2702 * Return the refname under which update was originally requested.2703 */2704static const char*original_update_refname(struct ref_update *update)2705{2706while(update->parent_update)2707 update = update->parent_update;27082709return update->refname;2710}27112712/*2713 * Check whether the REF_HAVE_OLD and old_oid values stored in update2714 * are consistent with oid, which is the reference's current value. If2715 * everything is OK, return 0; otherwise, write an error message to2716 * err and return -1.2717 */2718static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2719struct strbuf *err)2720{2721if(!(update->flags & REF_HAVE_OLD) ||2722!oidcmp(oid, &update->old_oid))2723return0;27242725if(is_null_oid(&update->old_oid))2726strbuf_addf(err,"cannot lock ref '%s': "2727"reference already exists",2728original_update_refname(update));2729else if(is_null_oid(oid))2730strbuf_addf(err,"cannot lock ref '%s': "2731"reference is missing but expected%s",2732original_update_refname(update),2733oid_to_hex(&update->old_oid));2734else2735strbuf_addf(err,"cannot lock ref '%s': "2736"is at%sbut expected%s",2737original_update_refname(update),2738oid_to_hex(oid),2739oid_to_hex(&update->old_oid));27402741return-1;2742}27432744/*2745 * Prepare for carrying out update:2746 * - Lock the reference referred to by update.2747 * - Read the reference under lock.2748 * - Check that its old SHA-1 value (if specified) is correct, and in2749 * any case record it in update->lock->old_oid for later use when2750 * writing the reflog.2751 * - If it is a symref update without REF_NODEREF, split it up into a2752 * REF_LOG_ONLY update of the symref and add a separate update for2753 * the referent to transaction.2754 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2755 * update of HEAD.2756 */2757static intlock_ref_for_update(struct files_ref_store *refs,2758struct ref_update *update,2759struct ref_transaction *transaction,2760const char*head_ref,2761struct string_list *affected_refnames,2762struct strbuf *err)2763{2764struct strbuf referent = STRBUF_INIT;2765int mustexist = (update->flags & REF_HAVE_OLD) &&2766!is_null_oid(&update->old_oid);2767int ret;2768struct ref_lock *lock;27692770files_assert_main_repository(refs,"lock_ref_for_update");27712772if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2773 update->flags |= REF_DELETING;27742775if(head_ref) {2776 ret =split_head_update(update, transaction, head_ref,2777 affected_refnames, err);2778if(ret)2779return ret;2780}27812782 ret =lock_raw_ref(refs, update->refname, mustexist,2783 affected_refnames, NULL,2784&lock, &referent,2785&update->type, err);2786if(ret) {2787char*reason;27882789 reason =strbuf_detach(err, NULL);2790strbuf_addf(err,"cannot lock ref '%s':%s",2791original_update_refname(update), reason);2792free(reason);2793return ret;2794}27952796 update->backend_data = lock;27972798if(update->type & REF_ISSYMREF) {2799if(update->flags & REF_NODEREF) {2800/*2801 * We won't be reading the referent as part of2802 * the transaction, so we have to read it here2803 * to record and possibly check old_sha1:2804 */2805if(refs_read_ref_full(&refs->base,2806 referent.buf,0,2807 lock->old_oid.hash, NULL)) {2808if(update->flags & REF_HAVE_OLD) {2809strbuf_addf(err,"cannot lock ref '%s': "2810"error reading reference",2811original_update_refname(update));2812return-1;2813}2814}else if(check_old_oid(update, &lock->old_oid, err)) {2815return TRANSACTION_GENERIC_ERROR;2816}2817}else{2818/*2819 * Create a new update for the reference this2820 * symref is pointing at. Also, we will record2821 * and verify old_sha1 for this update as part2822 * of processing the split-off update, so we2823 * don't have to do it here.2824 */2825 ret =split_symref_update(refs, update,2826 referent.buf, transaction,2827 affected_refnames, err);2828if(ret)2829return ret;2830}2831}else{2832struct ref_update *parent_update;28332834if(check_old_oid(update, &lock->old_oid, err))2835return TRANSACTION_GENERIC_ERROR;28362837/*2838 * If this update is happening indirectly because of a2839 * symref update, record the old SHA-1 in the parent2840 * update:2841 */2842for(parent_update = update->parent_update;2843 parent_update;2844 parent_update = parent_update->parent_update) {2845struct ref_lock *parent_lock = parent_update->backend_data;2846oidcpy(&parent_lock->old_oid, &lock->old_oid);2847}2848}28492850if((update->flags & REF_HAVE_NEW) &&2851!(update->flags & REF_DELETING) &&2852!(update->flags & REF_LOG_ONLY)) {2853if(!(update->type & REF_ISSYMREF) &&2854!oidcmp(&lock->old_oid, &update->new_oid)) {2855/*2856 * The reference already has the desired2857 * value, so we don't need to write it.2858 */2859}else if(write_ref_to_lockfile(lock, &update->new_oid,2860 err)) {2861char*write_err =strbuf_detach(err, NULL);28622863/*2864 * The lock was freed upon failure of2865 * write_ref_to_lockfile():2866 */2867 update->backend_data = NULL;2868strbuf_addf(err,2869"cannot update ref '%s':%s",2870 update->refname, write_err);2871free(write_err);2872return TRANSACTION_GENERIC_ERROR;2873}else{2874 update->flags |= REF_NEEDS_COMMIT;2875}2876}2877if(!(update->flags & REF_NEEDS_COMMIT)) {2878/*2879 * We didn't call write_ref_to_lockfile(), so2880 * the lockfile is still open. Close it to2881 * free up the file descriptor:2882 */2883if(close_ref(lock)) {2884strbuf_addf(err,"couldn't close '%s.lock'",2885 update->refname);2886return TRANSACTION_GENERIC_ERROR;2887}2888}2889return0;2890}28912892/*2893 * Unlock any references in `transaction` that are still locked, and2894 * mark the transaction closed.2895 */2896static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2897{2898size_t i;28992900for(i =0; i < transaction->nr; i++) {2901struct ref_update *update = transaction->updates[i];2902struct ref_lock *lock = update->backend_data;29032904if(lock) {2905unlock_ref(lock);2906 update->backend_data = NULL;2907}2908}29092910 transaction->state = REF_TRANSACTION_CLOSED;2911}29122913static intfiles_transaction_prepare(struct ref_store *ref_store,2914struct ref_transaction *transaction,2915struct strbuf *err)2916{2917struct files_ref_store *refs =2918files_downcast(ref_store, REF_STORE_WRITE,2919"ref_transaction_prepare");2920size_t i;2921int ret =0;2922struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2923char*head_ref = NULL;2924int head_type;2925struct object_id head_oid;29262927assert(err);29282929if(!transaction->nr)2930goto cleanup;29312932/*2933 * Fail if a refname appears more than once in the2934 * transaction. (If we end up splitting up any updates using2935 * split_symref_update() or split_head_update(), those2936 * functions will check that the new updates don't have the2937 * same refname as any existing ones.)2938 */2939for(i =0; i < transaction->nr; i++) {2940struct ref_update *update = transaction->updates[i];2941struct string_list_item *item =2942string_list_append(&affected_refnames, update->refname);29432944/*2945 * We store a pointer to update in item->util, but at2946 * the moment we never use the value of this field2947 * except to check whether it is non-NULL.2948 */2949 item->util = update;2950}2951string_list_sort(&affected_refnames);2952if(ref_update_reject_duplicates(&affected_refnames, err)) {2953 ret = TRANSACTION_GENERIC_ERROR;2954goto cleanup;2955}29562957/*2958 * Special hack: If a branch is updated directly and HEAD2959 * points to it (may happen on the remote side of a push2960 * for example) then logically the HEAD reflog should be2961 * updated too.2962 *2963 * A generic solution would require reverse symref lookups,2964 * but finding all symrefs pointing to a given branch would be2965 * rather costly for this rare event (the direct update of a2966 * branch) to be worth it. So let's cheat and check with HEAD2967 * only, which should cover 99% of all usage scenarios (even2968 * 100% of the default ones).2969 *2970 * So if HEAD is a symbolic reference, then record the name of2971 * the reference that it points to. If we see an update of2972 * head_ref within the transaction, then split_head_update()2973 * arranges for the reflog of HEAD to be updated, too.2974 */2975 head_ref =refs_resolve_refdup(ref_store,"HEAD",2976 RESOLVE_REF_NO_RECURSE,2977 head_oid.hash, &head_type);29782979if(head_ref && !(head_type & REF_ISSYMREF)) {2980free(head_ref);2981 head_ref = NULL;2982}29832984/*2985 * Acquire all locks, verify old values if provided, check2986 * that new values are valid, and write new values to the2987 * lockfiles, ready to be activated. Only keep one lockfile2988 * open at a time to avoid running out of file descriptors.2989 * Note that lock_ref_for_update() might append more updates2990 * to the transaction.2991 */2992for(i =0; i < transaction->nr; i++) {2993struct ref_update *update = transaction->updates[i];29942995 ret =lock_ref_for_update(refs, update, transaction,2996 head_ref, &affected_refnames, err);2997if(ret)2998break;2999}30003001cleanup:3002free(head_ref);3003string_list_clear(&affected_refnames,0);30043005if(ret)3006files_transaction_cleanup(transaction);3007else3008 transaction->state = REF_TRANSACTION_PREPARED;30093010return ret;3011}30123013static intfiles_transaction_finish(struct ref_store *ref_store,3014struct ref_transaction *transaction,3015struct strbuf *err)3016{3017struct files_ref_store *refs =3018files_downcast(ref_store,0,"ref_transaction_finish");3019size_t i;3020int ret =0;3021struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3022struct string_list_item *ref_to_delete;3023struct strbuf sb = STRBUF_INIT;30243025assert(err);30263027if(!transaction->nr) {3028 transaction->state = REF_TRANSACTION_CLOSED;3029return0;3030}30313032/* Perform updates first so live commits remain referenced */3033for(i =0; i < transaction->nr; i++) {3034struct ref_update *update = transaction->updates[i];3035struct ref_lock *lock = update->backend_data;30363037if(update->flags & REF_NEEDS_COMMIT ||3038 update->flags & REF_LOG_ONLY) {3039if(files_log_ref_write(refs,3040 lock->ref_name,3041&lock->old_oid,3042&update->new_oid,3043 update->msg, update->flags,3044 err)) {3045char*old_msg =strbuf_detach(err, NULL);30463047strbuf_addf(err,"cannot update the ref '%s':%s",3048 lock->ref_name, old_msg);3049free(old_msg);3050unlock_ref(lock);3051 update->backend_data = NULL;3052 ret = TRANSACTION_GENERIC_ERROR;3053goto cleanup;3054}3055}3056if(update->flags & REF_NEEDS_COMMIT) {3057clear_loose_ref_cache(refs);3058if(commit_ref(lock)) {3059strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3060unlock_ref(lock);3061 update->backend_data = NULL;3062 ret = TRANSACTION_GENERIC_ERROR;3063goto cleanup;3064}3065}3066}3067/* Perform deletes now that updates are safely completed */3068for(i =0; i < transaction->nr; i++) {3069struct ref_update *update = transaction->updates[i];3070struct ref_lock *lock = update->backend_data;30713072if(update->flags & REF_DELETING &&3073!(update->flags & REF_LOG_ONLY)) {3074if(!(update->type & REF_ISPACKED) ||3075 update->type & REF_ISSYMREF) {3076/* It is a loose reference. */3077strbuf_reset(&sb);3078files_ref_path(refs, &sb, lock->ref_name);3079if(unlink_or_msg(sb.buf, err)) {3080 ret = TRANSACTION_GENERIC_ERROR;3081goto cleanup;3082}3083 update->flags |= REF_DELETED_LOOSE;3084}30853086if(!(update->flags & REF_ISPRUNING))3087string_list_append(&refs_to_delete,3088 lock->ref_name);3089}3090}30913092if(repack_without_refs(refs, &refs_to_delete, err)) {3093 ret = TRANSACTION_GENERIC_ERROR;3094goto cleanup;3095}30963097/* Delete the reflogs of any references that were deleted: */3098for_each_string_list_item(ref_to_delete, &refs_to_delete) {3099strbuf_reset(&sb);3100files_reflog_path(refs, &sb, ref_to_delete->string);3101if(!unlink_or_warn(sb.buf))3102try_remove_empty_parents(refs, ref_to_delete->string,3103 REMOVE_EMPTY_PARENTS_REFLOG);3104}31053106clear_loose_ref_cache(refs);31073108cleanup:3109files_transaction_cleanup(transaction);31103111for(i =0; i < transaction->nr; i++) {3112struct ref_update *update = transaction->updates[i];31133114if(update->flags & REF_DELETED_LOOSE) {3115/*3116 * The loose reference was deleted. Delete any3117 * empty parent directories. (Note that this3118 * can only work because we have already3119 * removed the lockfile.)3120 */3121try_remove_empty_parents(refs, update->refname,3122 REMOVE_EMPTY_PARENTS_REF);3123}3124}31253126strbuf_release(&sb);3127string_list_clear(&refs_to_delete,0);3128return ret;3129}31303131static intfiles_transaction_abort(struct ref_store *ref_store,3132struct ref_transaction *transaction,3133struct strbuf *err)3134{3135files_transaction_cleanup(transaction);3136return0;3137}31383139static intref_present(const char*refname,3140const struct object_id *oid,int flags,void*cb_data)3141{3142struct string_list *affected_refnames = cb_data;31433144returnstring_list_has_string(affected_refnames, refname);3145}31463147static intfiles_initial_transaction_commit(struct ref_store *ref_store,3148struct ref_transaction *transaction,3149struct strbuf *err)3150{3151struct files_ref_store *refs =3152files_downcast(ref_store, REF_STORE_WRITE,3153"initial_ref_transaction_commit");3154size_t i;3155int ret =0;3156struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31573158assert(err);31593160if(transaction->state != REF_TRANSACTION_OPEN)3161die("BUG: commit called for transaction that is not open");31623163/* Fail if a refname appears more than once in the transaction: */3164for(i =0; i < transaction->nr; i++)3165string_list_append(&affected_refnames,3166 transaction->updates[i]->refname);3167string_list_sort(&affected_refnames);3168if(ref_update_reject_duplicates(&affected_refnames, err)) {3169 ret = TRANSACTION_GENERIC_ERROR;3170goto cleanup;3171}31723173/*3174 * It's really undefined to call this function in an active3175 * repository or when there are existing references: we are3176 * only locking and changing packed-refs, so (1) any3177 * simultaneous processes might try to change a reference at3178 * the same time we do, and (2) any existing loose versions of3179 * the references that we are setting would have precedence3180 * over our values. But some remote helpers create the remote3181 * "HEAD" and "master" branches before calling this function,3182 * so here we really only check that none of the references3183 * that we are creating already exists.3184 */3185if(refs_for_each_rawref(&refs->base, ref_present,3186&affected_refnames))3187die("BUG: initial ref transaction called with existing refs");31883189for(i =0; i < transaction->nr; i++) {3190struct ref_update *update = transaction->updates[i];31913192if((update->flags & REF_HAVE_OLD) &&3193!is_null_oid(&update->old_oid))3194die("BUG: initial ref transaction with old_sha1 set");3195if(refs_verify_refname_available(&refs->base, update->refname,3196&affected_refnames, NULL,3197 err)) {3198 ret = TRANSACTION_NAME_CONFLICT;3199goto cleanup;3200}3201}32023203if(lock_packed_refs(refs,0)) {3204strbuf_addf(err,"unable to lock packed-refs file:%s",3205strerror(errno));3206 ret = TRANSACTION_GENERIC_ERROR;3207goto cleanup;3208}32093210for(i =0; i < transaction->nr; i++) {3211struct ref_update *update = transaction->updates[i];32123213if((update->flags & REF_HAVE_NEW) &&3214!is_null_oid(&update->new_oid))3215add_packed_ref(refs, update->refname,3216&update->new_oid);3217}32183219if(commit_packed_refs(refs)) {3220strbuf_addf(err,"unable to commit packed-refs file:%s",3221strerror(errno));3222 ret = TRANSACTION_GENERIC_ERROR;3223goto cleanup;3224}32253226cleanup:3227 transaction->state = REF_TRANSACTION_CLOSED;3228string_list_clear(&affected_refnames,0);3229return ret;3230}32313232struct expire_reflog_cb {3233unsigned int flags;3234 reflog_expiry_should_prune_fn *should_prune_fn;3235void*policy_cb;3236FILE*newlog;3237struct object_id last_kept_oid;3238};32393240static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3241const char*email, timestamp_t timestamp,int tz,3242const char*message,void*cb_data)3243{3244struct expire_reflog_cb *cb = cb_data;3245struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32463247if(cb->flags & EXPIRE_REFLOGS_REWRITE)3248 ooid = &cb->last_kept_oid;32493250if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3251 message, policy_cb)) {3252if(!cb->newlog)3253printf("would prune%s", message);3254else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3255printf("prune%s", message);3256}else{3257if(cb->newlog) {3258fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3259oid_to_hex(ooid),oid_to_hex(noid),3260 email, timestamp, tz, message);3261oidcpy(&cb->last_kept_oid, noid);3262}3263if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3264printf("keep%s", message);3265}3266return0;3267}32683269static intfiles_reflog_expire(struct ref_store *ref_store,3270const char*refname,const unsigned char*sha1,3271unsigned int flags,3272 reflog_expiry_prepare_fn prepare_fn,3273 reflog_expiry_should_prune_fn should_prune_fn,3274 reflog_expiry_cleanup_fn cleanup_fn,3275void*policy_cb_data)3276{3277struct files_ref_store *refs =3278files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3279static struct lock_file reflog_lock;3280struct expire_reflog_cb cb;3281struct ref_lock *lock;3282struct strbuf log_file_sb = STRBUF_INIT;3283char*log_file;3284int status =0;3285int type;3286struct strbuf err = STRBUF_INIT;3287struct object_id oid;32883289memset(&cb,0,sizeof(cb));3290 cb.flags = flags;3291 cb.policy_cb = policy_cb_data;3292 cb.should_prune_fn = should_prune_fn;32933294/*3295 * The reflog file is locked by holding the lock on the3296 * reference itself, plus we might need to update the3297 * reference if --updateref was specified:3298 */3299 lock =lock_ref_sha1_basic(refs, refname, sha1,3300 NULL, NULL, REF_NODEREF,3301&type, &err);3302if(!lock) {3303error("cannot lock ref '%s':%s", refname, err.buf);3304strbuf_release(&err);3305return-1;3306}3307if(!refs_reflog_exists(ref_store, refname)) {3308unlock_ref(lock);3309return0;3310}33113312files_reflog_path(refs, &log_file_sb, refname);3313 log_file =strbuf_detach(&log_file_sb, NULL);3314if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3315/*3316 * Even though holding $GIT_DIR/logs/$reflog.lock has3317 * no locking implications, we use the lock_file3318 * machinery here anyway because it does a lot of the3319 * work we need, including cleaning up if the program3320 * exits unexpectedly.3321 */3322if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3323struct strbuf err = STRBUF_INIT;3324unable_to_lock_message(log_file, errno, &err);3325error("%s", err.buf);3326strbuf_release(&err);3327goto failure;3328}3329 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3330if(!cb.newlog) {3331error("cannot fdopen%s(%s)",3332get_lock_file_path(&reflog_lock),strerror(errno));3333goto failure;3334}3335}33363337hashcpy(oid.hash, sha1);33383339(*prepare_fn)(refname, &oid, cb.policy_cb);3340refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3341(*cleanup_fn)(cb.policy_cb);33423343if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3344/*3345 * It doesn't make sense to adjust a reference pointed3346 * to by a symbolic ref based on expiring entries in3347 * the symbolic reference's reflog. Nor can we update3348 * a reference if there are no remaining reflog3349 * entries.3350 */3351int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3352!(type & REF_ISSYMREF) &&3353!is_null_oid(&cb.last_kept_oid);33543355if(close_lock_file(&reflog_lock)) {3356 status |=error("couldn't write%s:%s", log_file,3357strerror(errno));3358}else if(update &&3359(write_in_full(get_lock_file_fd(lock->lk),3360oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3361write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3362close_ref(lock) <0)) {3363 status |=error("couldn't write%s",3364get_lock_file_path(lock->lk));3365rollback_lock_file(&reflog_lock);3366}else if(commit_lock_file(&reflog_lock)) {3367 status |=error("unable to write reflog '%s' (%s)",3368 log_file,strerror(errno));3369}else if(update &&commit_ref(lock)) {3370 status |=error("couldn't set%s", lock->ref_name);3371}3372}3373free(log_file);3374unlock_ref(lock);3375return status;33763377 failure:3378rollback_lock_file(&reflog_lock);3379free(log_file);3380unlock_ref(lock);3381return-1;3382}33833384static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3385{3386struct files_ref_store *refs =3387files_downcast(ref_store, REF_STORE_WRITE,"init_db");3388struct strbuf sb = STRBUF_INIT;33893390/*3391 * Create .git/refs/{heads,tags}3392 */3393files_ref_path(refs, &sb,"refs/heads");3394safe_create_dir(sb.buf,1);33953396strbuf_reset(&sb);3397files_ref_path(refs, &sb,"refs/tags");3398safe_create_dir(sb.buf,1);33993400strbuf_release(&sb);3401return0;3402}34033404struct ref_storage_be refs_be_files = {3405 NULL,3406"files",3407 files_ref_store_create,3408 files_init_db,3409 files_transaction_prepare,3410 files_transaction_finish,3411 files_transaction_abort,3412 files_initial_transaction_commit,34133414 files_pack_refs,3415 files_peel_ref,3416 files_create_symref,3417 files_delete_refs,3418 files_rename_ref,34193420 files_ref_iterator_begin,3421 files_read_raw_ref,34223423 files_reflog_iterator_begin,3424 files_for_each_reflog_ent,3425 files_for_each_reflog_ent_reverse,3426 files_reflog_exists,3427 files_create_reflog,3428 files_delete_reflog,3429 files_reflog_expire3430};