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 * Future: need to be in "struct repository" 52 * when doing a full libification. 53 */ 54struct files_ref_store { 55struct ref_store base; 56unsigned int store_flags; 57 58char*gitdir; 59char*gitcommondir; 60char*packed_refs_path; 61 62struct ref_cache *loose; 63struct packed_ref_cache *packed; 64 65/* 66 * Lock used for the "packed-refs" file. Note that this (and 67 * thus the enclosing `files_ref_store`) must not be freed. 68 */ 69struct lock_file packed_refs_lock; 70}; 71 72/* 73 * Increment the reference count of *packed_refs. 74 */ 75static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 76{ 77 packed_refs->referrers++; 78} 79 80/* 81 * Decrease the reference count of *packed_refs. If it goes to zero, 82 * free *packed_refs and return true; otherwise return false. 83 */ 84static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 85{ 86if(!--packed_refs->referrers) { 87free_ref_cache(packed_refs->cache); 88stat_validity_clear(&packed_refs->validity); 89free(packed_refs); 90return1; 91}else{ 92return0; 93} 94} 95 96static voidclear_packed_ref_cache(struct files_ref_store *refs) 97{ 98if(refs->packed) { 99struct packed_ref_cache *packed_refs = refs->packed; 100 101if(is_lock_file_locked(&refs->packed_refs_lock)) 102die("BUG: packed-ref cache cleared while locked"); 103 refs->packed = NULL; 104release_packed_ref_cache(packed_refs); 105} 106} 107 108static voidclear_loose_ref_cache(struct files_ref_store *refs) 109{ 110if(refs->loose) { 111free_ref_cache(refs->loose); 112 refs->loose = NULL; 113} 114} 115 116/* 117 * Create a new submodule ref cache and add it to the internal 118 * set of caches. 119 */ 120static struct ref_store *files_ref_store_create(const char*gitdir, 121unsigned int flags) 122{ 123struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 124struct ref_store *ref_store = (struct ref_store *)refs; 125struct strbuf sb = STRBUF_INIT; 126 127base_ref_store_init(ref_store, &refs_be_files); 128 refs->store_flags = flags; 129 130 refs->gitdir =xstrdup(gitdir); 131get_common_dir_noenv(&sb, gitdir); 132 refs->gitcommondir =strbuf_detach(&sb, NULL); 133strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 134 refs->packed_refs_path =strbuf_detach(&sb, NULL); 135 136return ref_store; 137} 138 139/* 140 * Die if refs is not the main ref store. caller is used in any 141 * necessary error messages. 142 */ 143static voidfiles_assert_main_repository(struct files_ref_store *refs, 144const char*caller) 145{ 146if(refs->store_flags & REF_STORE_MAIN) 147return; 148 149die("BUG: operation%sonly allowed for main ref store", caller); 150} 151 152/* 153 * Downcast ref_store to files_ref_store. Die if ref_store is not a 154 * files_ref_store. required_flags is compared with ref_store's 155 * store_flags to ensure the ref_store has all required capabilities. 156 * "caller" is used in any necessary error messages. 157 */ 158static struct files_ref_store *files_downcast(struct ref_store *ref_store, 159unsigned int required_flags, 160const char*caller) 161{ 162struct files_ref_store *refs; 163 164if(ref_store->be != &refs_be_files) 165die("BUG: ref_store is type\"%s\"not\"files\"in%s", 166 ref_store->be->name, caller); 167 168 refs = (struct files_ref_store *)ref_store; 169 170if((refs->store_flags & required_flags) != required_flags) 171die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 172 caller, required_flags, refs->store_flags); 173 174return refs; 175} 176 177/* The length of a peeled reference line in packed-refs, including EOL: */ 178#define PEELED_LINE_LENGTH 42 179 180/* 181 * The packed-refs header line that we write out. Perhaps other 182 * traits will be added later. The trailing space is required. 183 */ 184static const char PACKED_REFS_HEADER[] = 185"# pack-refs with: peeled fully-peeled\n"; 186 187/* 188 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 189 * Return a pointer to the refname within the line (null-terminated), 190 * or NULL if there was a problem. 191 */ 192static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 193{ 194const char*ref; 195 196if(parse_oid_hex(line->buf, oid, &ref) <0) 197return NULL; 198if(!isspace(*ref++)) 199return NULL; 200 201if(isspace(*ref)) 202return NULL; 203 204if(line->buf[line->len -1] !='\n') 205return NULL; 206 line->buf[--line->len] =0; 207 208return ref; 209} 210 211/* 212 * Read from `packed_refs_file` into a newly-allocated 213 * `packed_ref_cache` and return it. The return value will already 214 * have its reference count incremented. 215 * 216 * A comment line of the form "# pack-refs with: " may contain zero or 217 * more traits. We interpret the traits as follows: 218 * 219 * No traits: 220 * 221 * Probably no references are peeled. But if the file contains a 222 * peeled value for a reference, we will use it. 223 * 224 * peeled: 225 * 226 * References under "refs/tags/", if they *can* be peeled, *are* 227 * peeled in this file. References outside of "refs/tags/" are 228 * probably not peeled even if they could have been, but if we find 229 * a peeled value for such a reference we will use it. 230 * 231 * fully-peeled: 232 * 233 * All references in the file that can be peeled are peeled. 234 * Inversely (and this is more important), any references in the 235 * file for which no peeled value is recorded is not peelable. This 236 * trait should typically be written alongside "peeled" for 237 * compatibility with older clients, but we do not require it 238 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 239 */ 240static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 241{ 242FILE*f; 243struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 244struct ref_entry *last = NULL; 245struct strbuf line = STRBUF_INIT; 246enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 247struct ref_dir *dir; 248 249acquire_packed_ref_cache(packed_refs); 250 packed_refs->cache =create_ref_cache(NULL, NULL); 251 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 252 253 f =fopen(packed_refs_file,"r"); 254if(!f) { 255if(errno == ENOENT) { 256/* 257 * This is OK; it just means that no 258 * "packed-refs" file has been written yet, 259 * which is equivalent to it being empty. 260 */ 261return packed_refs; 262}else{ 263die_errno("couldn't read%s", packed_refs_file); 264} 265} 266 267stat_validity_update(&packed_refs->validity,fileno(f)); 268 269 dir =get_ref_dir(packed_refs->cache->root); 270while(strbuf_getwholeline(&line, f,'\n') != EOF) { 271struct object_id oid; 272const char*refname; 273const char*traits; 274 275if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 276if(strstr(traits," fully-peeled ")) 277 peeled = PEELED_FULLY; 278else if(strstr(traits," peeled ")) 279 peeled = PEELED_TAGS; 280/* perhaps other traits later as well */ 281continue; 282} 283 284 refname =parse_ref_line(&line, &oid); 285if(refname) { 286int flag = REF_ISPACKED; 287 288if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 289if(!refname_is_safe(refname)) 290die("packed refname is dangerous:%s", refname); 291oidclr(&oid); 292 flag |= REF_BAD_NAME | REF_ISBROKEN; 293} 294 last =create_ref_entry(refname, &oid, flag); 295if(peeled == PEELED_FULLY || 296(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 297 last->flag |= REF_KNOWS_PEELED; 298add_ref_entry(dir, last); 299continue; 300} 301if(last && 302 line.buf[0] =='^'&& 303 line.len == PEELED_LINE_LENGTH && 304 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 305!get_oid_hex(line.buf +1, &oid)) { 306oidcpy(&last->u.value.peeled, &oid); 307/* 308 * Regardless of what the file header said, 309 * we definitely know the value of *this* 310 * reference: 311 */ 312 last->flag |= REF_KNOWS_PEELED; 313} 314} 315 316fclose(f); 317strbuf_release(&line); 318 319return packed_refs; 320} 321 322static const char*files_packed_refs_path(struct files_ref_store *refs) 323{ 324return refs->packed_refs_path; 325} 326 327static voidfiles_reflog_path(struct files_ref_store *refs, 328struct strbuf *sb, 329const char*refname) 330{ 331if(!refname) { 332/* 333 * FIXME: of course this is wrong in multi worktree 334 * setting. To be fixed real soon. 335 */ 336strbuf_addf(sb,"%s/logs", refs->gitcommondir); 337return; 338} 339 340switch(ref_type(refname)) { 341case REF_TYPE_PER_WORKTREE: 342case REF_TYPE_PSEUDOREF: 343strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 344break; 345case REF_TYPE_NORMAL: 346strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 347break; 348default: 349die("BUG: unknown ref type%dof ref%s", 350ref_type(refname), refname); 351} 352} 353 354static voidfiles_ref_path(struct files_ref_store *refs, 355struct strbuf *sb, 356const char*refname) 357{ 358switch(ref_type(refname)) { 359case REF_TYPE_PER_WORKTREE: 360case REF_TYPE_PSEUDOREF: 361strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 362break; 363case REF_TYPE_NORMAL: 364strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 365break; 366default: 367die("BUG: unknown ref type%dof ref%s", 368ref_type(refname), refname); 369} 370} 371 372/* 373 * Check that the packed refs cache (if any) still reflects the 374 * contents of the file. If not, clear the cache. 375 */ 376static voidvalidate_packed_ref_cache(struct files_ref_store *refs) 377{ 378if(refs->packed && 379!stat_validity_check(&refs->packed->validity, 380files_packed_refs_path(refs))) 381clear_packed_ref_cache(refs); 382} 383 384/* 385 * Get the packed_ref_cache for the specified files_ref_store, 386 * creating and populating it if it hasn't been read before or if the 387 * file has been changed (according to its `validity` field) since it 388 * was last read. On the other hand, if we hold the lock, then assume 389 * that the file hasn't been changed out from under us, so skip the 390 * extra `stat()` call in `stat_validity_check()`. 391 */ 392static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 393{ 394const char*packed_refs_file =files_packed_refs_path(refs); 395 396if(!is_lock_file_locked(&refs->packed_refs_lock)) 397validate_packed_ref_cache(refs); 398 399if(!refs->packed) 400 refs->packed =read_packed_refs(packed_refs_file); 401 402return refs->packed; 403} 404 405static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 406{ 407returnget_ref_dir(packed_ref_cache->cache->root); 408} 409 410static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 411{ 412returnget_packed_ref_dir(get_packed_ref_cache(refs)); 413} 414 415/* 416 * Add a reference to the in-memory packed reference cache. This may 417 * only be called while the packed-refs file is locked (see 418 * lock_packed_refs()). To actually write the packed-refs file, call 419 * commit_packed_refs(). 420 */ 421static voidadd_packed_ref(struct files_ref_store *refs, 422const char*refname,const struct object_id *oid) 423{ 424struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 425 426if(!is_lock_file_locked(&refs->packed_refs_lock)) 427die("BUG: packed refs not locked"); 428 429if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 430die("Reference has invalid format: '%s'", refname); 431 432add_ref_entry(get_packed_ref_dir(packed_ref_cache), 433create_ref_entry(refname, oid, REF_ISPACKED)); 434} 435 436/* 437 * Read the loose references from the namespace dirname into dir 438 * (without recursing). dirname must end with '/'. dir must be the 439 * directory entry corresponding to dirname. 440 */ 441static voidloose_fill_ref_dir(struct ref_store *ref_store, 442struct ref_dir *dir,const char*dirname) 443{ 444struct files_ref_store *refs = 445files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 446DIR*d; 447struct dirent *de; 448int dirnamelen =strlen(dirname); 449struct strbuf refname; 450struct strbuf path = STRBUF_INIT; 451size_t path_baselen; 452 453files_ref_path(refs, &path, dirname); 454 path_baselen = path.len; 455 456 d =opendir(path.buf); 457if(!d) { 458strbuf_release(&path); 459return; 460} 461 462strbuf_init(&refname, dirnamelen +257); 463strbuf_add(&refname, dirname, dirnamelen); 464 465while((de =readdir(d)) != NULL) { 466struct object_id oid; 467struct stat st; 468int flag; 469 470if(de->d_name[0] =='.') 471continue; 472if(ends_with(de->d_name,".lock")) 473continue; 474strbuf_addstr(&refname, de->d_name); 475strbuf_addstr(&path, de->d_name); 476if(stat(path.buf, &st) <0) { 477;/* silently ignore */ 478}else if(S_ISDIR(st.st_mode)) { 479strbuf_addch(&refname,'/'); 480add_entry_to_dir(dir, 481create_dir_entry(dir->cache, refname.buf, 482 refname.len,1)); 483}else{ 484if(!refs_resolve_ref_unsafe(&refs->base, 485 refname.buf, 486 RESOLVE_REF_READING, 487 oid.hash, &flag)) { 488oidclr(&oid); 489 flag |= REF_ISBROKEN; 490}else if(is_null_oid(&oid)) { 491/* 492 * It is so astronomically unlikely 493 * that NULL_SHA1 is the SHA-1 of an 494 * actual object that we consider its 495 * appearance in a loose reference 496 * file to be repo corruption 497 * (probably due to a software bug). 498 */ 499 flag |= REF_ISBROKEN; 500} 501 502if(check_refname_format(refname.buf, 503 REFNAME_ALLOW_ONELEVEL)) { 504if(!refname_is_safe(refname.buf)) 505die("loose refname is dangerous:%s", refname.buf); 506oidclr(&oid); 507 flag |= REF_BAD_NAME | REF_ISBROKEN; 508} 509add_entry_to_dir(dir, 510create_ref_entry(refname.buf, &oid, flag)); 511} 512strbuf_setlen(&refname, dirnamelen); 513strbuf_setlen(&path, path_baselen); 514} 515strbuf_release(&refname); 516strbuf_release(&path); 517closedir(d); 518 519/* 520 * Manually add refs/bisect, which, being per-worktree, might 521 * not appear in the directory listing for refs/ in the main 522 * repo. 523 */ 524if(!strcmp(dirname,"refs/")) { 525int pos =search_ref_dir(dir,"refs/bisect/",12); 526 527if(pos <0) { 528struct ref_entry *child_entry =create_dir_entry( 529 dir->cache,"refs/bisect/",12,1); 530add_entry_to_dir(dir, child_entry); 531} 532} 533} 534 535static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 536{ 537if(!refs->loose) { 538/* 539 * Mark the top-level directory complete because we 540 * are about to read the only subdirectory that can 541 * hold references: 542 */ 543 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 544 545/* We're going to fill the top level ourselves: */ 546 refs->loose->root->flag &= ~REF_INCOMPLETE; 547 548/* 549 * Add an incomplete entry for "refs/" (to be filled 550 * lazily): 551 */ 552add_entry_to_dir(get_ref_dir(refs->loose->root), 553create_dir_entry(refs->loose,"refs/",5,1)); 554} 555return refs->loose; 556} 557 558/* 559 * Return the ref_entry for the given refname from the packed 560 * references. If it does not exist, return NULL. 561 */ 562static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 563const char*refname) 564{ 565returnfind_ref_entry(get_packed_refs(refs), refname); 566} 567 568/* 569 * A loose ref file doesn't exist; check for a packed ref. 570 */ 571static intresolve_packed_ref(struct files_ref_store *refs, 572const char*refname, 573unsigned char*sha1,unsigned int*flags) 574{ 575struct ref_entry *entry; 576 577/* 578 * The loose reference file does not exist; check for a packed 579 * reference. 580 */ 581 entry =get_packed_ref(refs, refname); 582if(entry) { 583hashcpy(sha1, entry->u.value.oid.hash); 584*flags |= REF_ISPACKED; 585return0; 586} 587/* refname is not a packed reference. */ 588return-1; 589} 590 591static intfiles_read_raw_ref(struct ref_store *ref_store, 592const char*refname,unsigned char*sha1, 593struct strbuf *referent,unsigned int*type) 594{ 595struct files_ref_store *refs = 596files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 597struct strbuf sb_contents = STRBUF_INIT; 598struct strbuf sb_path = STRBUF_INIT; 599const char*path; 600const char*buf; 601struct stat st; 602int fd; 603int ret = -1; 604int save_errno; 605int remaining_retries =3; 606 607*type =0; 608strbuf_reset(&sb_path); 609 610files_ref_path(refs, &sb_path, refname); 611 612 path = sb_path.buf; 613 614stat_ref: 615/* 616 * We might have to loop back here to avoid a race 617 * condition: first we lstat() the file, then we try 618 * to read it as a link or as a file. But if somebody 619 * changes the type of the file (file <-> directory 620 * <-> symlink) between the lstat() and reading, then 621 * we don't want to report that as an error but rather 622 * try again starting with the lstat(). 623 * 624 * We'll keep a count of the retries, though, just to avoid 625 * any confusing situation sending us into an infinite loop. 626 */ 627 628if(remaining_retries-- <=0) 629goto out; 630 631if(lstat(path, &st) <0) { 632if(errno != ENOENT) 633goto out; 634if(resolve_packed_ref(refs, refname, sha1, type)) { 635 errno = ENOENT; 636goto out; 637} 638 ret =0; 639goto out; 640} 641 642/* Follow "normalized" - ie "refs/.." symlinks by hand */ 643if(S_ISLNK(st.st_mode)) { 644strbuf_reset(&sb_contents); 645if(strbuf_readlink(&sb_contents, path,0) <0) { 646if(errno == ENOENT || errno == EINVAL) 647/* inconsistent with lstat; retry */ 648goto stat_ref; 649else 650goto out; 651} 652if(starts_with(sb_contents.buf,"refs/") && 653!check_refname_format(sb_contents.buf,0)) { 654strbuf_swap(&sb_contents, referent); 655*type |= REF_ISSYMREF; 656 ret =0; 657goto out; 658} 659/* 660 * It doesn't look like a refname; fall through to just 661 * treating it like a non-symlink, and reading whatever it 662 * points to. 663 */ 664} 665 666/* Is it a directory? */ 667if(S_ISDIR(st.st_mode)) { 668/* 669 * Even though there is a directory where the loose 670 * ref is supposed to be, there could still be a 671 * packed ref: 672 */ 673if(resolve_packed_ref(refs, refname, sha1, type)) { 674 errno = EISDIR; 675goto out; 676} 677 ret =0; 678goto out; 679} 680 681/* 682 * Anything else, just open it and try to use it as 683 * a ref 684 */ 685 fd =open(path, O_RDONLY); 686if(fd <0) { 687if(errno == ENOENT && !S_ISLNK(st.st_mode)) 688/* inconsistent with lstat; retry */ 689goto stat_ref; 690else 691goto out; 692} 693strbuf_reset(&sb_contents); 694if(strbuf_read(&sb_contents, fd,256) <0) { 695int save_errno = errno; 696close(fd); 697 errno = save_errno; 698goto out; 699} 700close(fd); 701strbuf_rtrim(&sb_contents); 702 buf = sb_contents.buf; 703if(starts_with(buf,"ref:")) { 704 buf +=4; 705while(isspace(*buf)) 706 buf++; 707 708strbuf_reset(referent); 709strbuf_addstr(referent, buf); 710*type |= REF_ISSYMREF; 711 ret =0; 712goto out; 713} 714 715/* 716 * Please note that FETCH_HEAD has additional 717 * data after the sha. 718 */ 719if(get_sha1_hex(buf, sha1) || 720(buf[40] !='\0'&& !isspace(buf[40]))) { 721*type |= REF_ISBROKEN; 722 errno = EINVAL; 723goto out; 724} 725 726 ret =0; 727 728out: 729 save_errno = errno; 730strbuf_release(&sb_path); 731strbuf_release(&sb_contents); 732 errno = save_errno; 733return ret; 734} 735 736static voidunlock_ref(struct ref_lock *lock) 737{ 738/* Do not free lock->lk -- atexit() still looks at them */ 739if(lock->lk) 740rollback_lock_file(lock->lk); 741free(lock->ref_name); 742free(lock); 743} 744 745/* 746 * Lock refname, without following symrefs, and set *lock_p to point 747 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 748 * and type similarly to read_raw_ref(). 749 * 750 * The caller must verify that refname is a "safe" reference name (in 751 * the sense of refname_is_safe()) before calling this function. 752 * 753 * If the reference doesn't already exist, verify that refname doesn't 754 * have a D/F conflict with any existing references. extras and skip 755 * are passed to refs_verify_refname_available() for this check. 756 * 757 * If mustexist is not set and the reference is not found or is 758 * broken, lock the reference anyway but clear sha1. 759 * 760 * Return 0 on success. On failure, write an error message to err and 761 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 762 * 763 * Implementation note: This function is basically 764 * 765 * lock reference 766 * read_raw_ref() 767 * 768 * but it includes a lot more code to 769 * - Deal with possible races with other processes 770 * - Avoid calling refs_verify_refname_available() when it can be 771 * avoided, namely if we were successfully able to read the ref 772 * - Generate informative error messages in the case of failure 773 */ 774static intlock_raw_ref(struct files_ref_store *refs, 775const char*refname,int mustexist, 776const struct string_list *extras, 777const struct string_list *skip, 778struct ref_lock **lock_p, 779struct strbuf *referent, 780unsigned int*type, 781struct strbuf *err) 782{ 783struct ref_lock *lock; 784struct strbuf ref_file = STRBUF_INIT; 785int attempts_remaining =3; 786int ret = TRANSACTION_GENERIC_ERROR; 787 788assert(err); 789files_assert_main_repository(refs,"lock_raw_ref"); 790 791*type =0; 792 793/* First lock the file so it can't change out from under us. */ 794 795*lock_p = lock =xcalloc(1,sizeof(*lock)); 796 797 lock->ref_name =xstrdup(refname); 798files_ref_path(refs, &ref_file, refname); 799 800retry: 801switch(safe_create_leading_directories(ref_file.buf)) { 802case SCLD_OK: 803break;/* success */ 804case SCLD_EXISTS: 805/* 806 * Suppose refname is "refs/foo/bar". We just failed 807 * to create the containing directory, "refs/foo", 808 * because there was a non-directory in the way. This 809 * indicates a D/F conflict, probably because of 810 * another reference such as "refs/foo". There is no 811 * reason to expect this error to be transitory. 812 */ 813if(refs_verify_refname_available(&refs->base, refname, 814 extras, skip, err)) { 815if(mustexist) { 816/* 817 * To the user the relevant error is 818 * that the "mustexist" reference is 819 * missing: 820 */ 821strbuf_reset(err); 822strbuf_addf(err,"unable to resolve reference '%s'", 823 refname); 824}else{ 825/* 826 * The error message set by 827 * refs_verify_refname_available() is 828 * OK. 829 */ 830 ret = TRANSACTION_NAME_CONFLICT; 831} 832}else{ 833/* 834 * The file that is in the way isn't a loose 835 * reference. Report it as a low-level 836 * failure. 837 */ 838strbuf_addf(err,"unable to create lock file%s.lock; " 839"non-directory in the way", 840 ref_file.buf); 841} 842goto error_return; 843case SCLD_VANISHED: 844/* Maybe another process was tidying up. Try again. */ 845if(--attempts_remaining >0) 846goto retry; 847/* fall through */ 848default: 849strbuf_addf(err,"unable to create directory for%s", 850 ref_file.buf); 851goto error_return; 852} 853 854if(!lock->lk) 855 lock->lk =xcalloc(1,sizeof(struct lock_file)); 856 857if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 858if(errno == ENOENT && --attempts_remaining >0) { 859/* 860 * Maybe somebody just deleted one of the 861 * directories leading to ref_file. Try 862 * again: 863 */ 864goto retry; 865}else{ 866unable_to_lock_message(ref_file.buf, errno, err); 867goto error_return; 868} 869} 870 871/* 872 * Now we hold the lock and can read the reference without 873 * fear that its value will change. 874 */ 875 876if(files_read_raw_ref(&refs->base, refname, 877 lock->old_oid.hash, referent, type)) { 878if(errno == ENOENT) { 879if(mustexist) { 880/* Garden variety missing reference. */ 881strbuf_addf(err,"unable to resolve reference '%s'", 882 refname); 883goto error_return; 884}else{ 885/* 886 * Reference is missing, but that's OK. We 887 * know that there is not a conflict with 888 * another loose reference because 889 * (supposing that we are trying to lock 890 * reference "refs/foo/bar"): 891 * 892 * - We were successfully able to create 893 * the lockfile refs/foo/bar.lock, so we 894 * know there cannot be a loose reference 895 * named "refs/foo". 896 * 897 * - We got ENOENT and not EISDIR, so we 898 * know that there cannot be a loose 899 * reference named "refs/foo/bar/baz". 900 */ 901} 902}else if(errno == EISDIR) { 903/* 904 * There is a directory in the way. It might have 905 * contained references that have been deleted. If 906 * we don't require that the reference already 907 * exists, try to remove the directory so that it 908 * doesn't cause trouble when we want to rename the 909 * lockfile into place later. 910 */ 911if(mustexist) { 912/* Garden variety missing reference. */ 913strbuf_addf(err,"unable to resolve reference '%s'", 914 refname); 915goto error_return; 916}else if(remove_dir_recursively(&ref_file, 917 REMOVE_DIR_EMPTY_ONLY)) { 918if(refs_verify_refname_available( 919&refs->base, refname, 920 extras, skip, err)) { 921/* 922 * The error message set by 923 * verify_refname_available() is OK. 924 */ 925 ret = TRANSACTION_NAME_CONFLICT; 926goto error_return; 927}else{ 928/* 929 * We can't delete the directory, 930 * but we also don't know of any 931 * references that it should 932 * contain. 933 */ 934strbuf_addf(err,"there is a non-empty directory '%s' " 935"blocking reference '%s'", 936 ref_file.buf, refname); 937goto error_return; 938} 939} 940}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 941strbuf_addf(err,"unable to resolve reference '%s': " 942"reference broken", refname); 943goto error_return; 944}else{ 945strbuf_addf(err,"unable to resolve reference '%s':%s", 946 refname,strerror(errno)); 947goto error_return; 948} 949 950/* 951 * If the ref did not exist and we are creating it, 952 * make sure there is no existing ref that conflicts 953 * with refname: 954 */ 955if(refs_verify_refname_available( 956&refs->base, refname, 957 extras, skip, err)) 958goto error_return; 959} 960 961 ret =0; 962goto out; 963 964error_return: 965unlock_ref(lock); 966*lock_p = NULL; 967 968out: 969strbuf_release(&ref_file); 970return ret; 971} 972 973static intfiles_peel_ref(struct ref_store *ref_store, 974const char*refname,unsigned char*sha1) 975{ 976struct files_ref_store *refs = 977files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 978"peel_ref"); 979int flag; 980unsigned char base[20]; 981 982if(current_ref_iter && current_ref_iter->refname == refname) { 983struct object_id peeled; 984 985if(ref_iterator_peel(current_ref_iter, &peeled)) 986return-1; 987hashcpy(sha1, peeled.hash); 988return0; 989} 990 991if(refs_read_ref_full(ref_store, refname, 992 RESOLVE_REF_READING, base, &flag)) 993return-1; 994 995/* 996 * If the reference is packed, read its ref_entry from the 997 * cache in the hope that we already know its peeled value. 998 * We only try this optimization on packed references because 999 * (a) forcing the filling of the loose reference cache could1000 * be expensive and (b) loose references anyway usually do not1001 * have REF_KNOWS_PEELED.1002 */1003if(flag & REF_ISPACKED) {1004struct ref_entry *r =get_packed_ref(refs, refname);1005if(r) {1006if(peel_entry(r,0))1007return-1;1008hashcpy(sha1, r->u.value.peeled.hash);1009return0;1010}1011}10121013returnpeel_object(base, sha1);1014}10151016struct files_ref_iterator {1017struct ref_iterator base;10181019struct packed_ref_cache *packed_ref_cache;1020struct ref_iterator *iter0;1021unsigned int flags;1022};10231024static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1025{1026struct files_ref_iterator *iter =1027(struct files_ref_iterator *)ref_iterator;1028int ok;10291030while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1031if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1032ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1033continue;10341035if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1036!ref_resolves_to_object(iter->iter0->refname,1037 iter->iter0->oid,1038 iter->iter0->flags))1039continue;10401041 iter->base.refname = iter->iter0->refname;1042 iter->base.oid = iter->iter0->oid;1043 iter->base.flags = iter->iter0->flags;1044return ITER_OK;1045}10461047 iter->iter0 = NULL;1048if(ref_iterator_abort(ref_iterator) != ITER_DONE)1049 ok = ITER_ERROR;10501051return ok;1052}10531054static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1055struct object_id *peeled)1056{1057struct files_ref_iterator *iter =1058(struct files_ref_iterator *)ref_iterator;10591060returnref_iterator_peel(iter->iter0, peeled);1061}10621063static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1064{1065struct files_ref_iterator *iter =1066(struct files_ref_iterator *)ref_iterator;1067int ok = ITER_DONE;10681069if(iter->iter0)1070 ok =ref_iterator_abort(iter->iter0);10711072release_packed_ref_cache(iter->packed_ref_cache);1073base_ref_iterator_free(ref_iterator);1074return ok;1075}10761077static struct ref_iterator_vtable files_ref_iterator_vtable = {1078 files_ref_iterator_advance,1079 files_ref_iterator_peel,1080 files_ref_iterator_abort1081};10821083static struct ref_iterator *files_ref_iterator_begin(1084struct ref_store *ref_store,1085const char*prefix,unsigned int flags)1086{1087struct files_ref_store *refs;1088struct ref_iterator *loose_iter, *packed_iter;1089struct files_ref_iterator *iter;1090struct ref_iterator *ref_iterator;1091unsigned int required_flags = REF_STORE_READ;10921093if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1094 required_flags |= REF_STORE_ODB;10951096 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");10971098 iter =xcalloc(1,sizeof(*iter));1099 ref_iterator = &iter->base;1100base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11011102/*1103 * We must make sure that all loose refs are read before1104 * accessing the packed-refs file; this avoids a race1105 * condition if loose refs are migrated to the packed-refs1106 * file by a simultaneous process, but our in-memory view is1107 * from before the migration. We ensure this as follows:1108 * First, we call start the loose refs iteration with its1109 * `prime_ref` argument set to true. This causes the loose1110 * references in the subtree to be pre-read into the cache.1111 * (If they've already been read, that's OK; we only need to1112 * guarantee that they're read before the packed refs, not1113 * *how much* before.) After that, we call1114 * get_packed_ref_cache(), which internally checks whether the1115 * packed-ref cache is up to date with what is on disk, and1116 * re-reads it if not.1117 */11181119 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1120 prefix,1);11211122 iter->packed_ref_cache =get_packed_ref_cache(refs);1123acquire_packed_ref_cache(iter->packed_ref_cache);1124 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1125 prefix,0);11261127 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1128 iter->flags = flags;11291130return ref_iterator;1131}11321133/*1134 * Verify that the reference locked by lock has the value old_sha1.1135 * Fail if the reference doesn't exist and mustexist is set. Return 01136 * on success. On error, write an error message to err, set errno, and1137 * return a negative value.1138 */1139static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1140const unsigned char*old_sha1,int mustexist,1141struct strbuf *err)1142{1143assert(err);11441145if(refs_read_ref_full(ref_store, lock->ref_name,1146 mustexist ? RESOLVE_REF_READING :0,1147 lock->old_oid.hash, NULL)) {1148if(old_sha1) {1149int save_errno = errno;1150strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1151 errno = save_errno;1152return-1;1153}else{1154oidclr(&lock->old_oid);1155return0;1156}1157}1158if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1159strbuf_addf(err,"ref '%s' is at%sbut expected%s",1160 lock->ref_name,1161oid_to_hex(&lock->old_oid),1162sha1_to_hex(old_sha1));1163 errno = EBUSY;1164return-1;1165}1166return0;1167}11681169static intremove_empty_directories(struct strbuf *path)1170{1171/*1172 * we want to create a file but there is a directory there;1173 * if that is an empty directory (or a directory that contains1174 * only empty directories), remove them.1175 */1176returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1177}11781179static intcreate_reflock(const char*path,void*cb)1180{1181struct lock_file *lk = cb;11821183returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1184}11851186/*1187 * Locks a ref returning the lock on success and NULL on failure.1188 * On failure errno is set to something meaningful.1189 */1190static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1191const char*refname,1192const unsigned char*old_sha1,1193const struct string_list *extras,1194const struct string_list *skip,1195unsigned int flags,int*type,1196struct strbuf *err)1197{1198struct strbuf ref_file = STRBUF_INIT;1199struct ref_lock *lock;1200int last_errno =0;1201int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1202int resolve_flags = RESOLVE_REF_NO_RECURSE;1203int resolved;12041205files_assert_main_repository(refs,"lock_ref_sha1_basic");1206assert(err);12071208 lock =xcalloc(1,sizeof(struct ref_lock));12091210if(mustexist)1211 resolve_flags |= RESOLVE_REF_READING;1212if(flags & REF_DELETING)1213 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12141215files_ref_path(refs, &ref_file, refname);1216 resolved = !!refs_resolve_ref_unsafe(&refs->base,1217 refname, resolve_flags,1218 lock->old_oid.hash, type);1219if(!resolved && errno == EISDIR) {1220/*1221 * we are trying to lock foo but we used to1222 * have foo/bar which now does not exist;1223 * it is normal for the empty directory 'foo'1224 * to remain.1225 */1226if(remove_empty_directories(&ref_file)) {1227 last_errno = errno;1228if(!refs_verify_refname_available(1229&refs->base,1230 refname, extras, skip, err))1231strbuf_addf(err,"there are still refs under '%s'",1232 refname);1233goto error_return;1234}1235 resolved = !!refs_resolve_ref_unsafe(&refs->base,1236 refname, resolve_flags,1237 lock->old_oid.hash, type);1238}1239if(!resolved) {1240 last_errno = errno;1241if(last_errno != ENOTDIR ||1242!refs_verify_refname_available(&refs->base, refname,1243 extras, skip, err))1244strbuf_addf(err,"unable to resolve reference '%s':%s",1245 refname,strerror(last_errno));12461247goto error_return;1248}12491250/*1251 * If the ref did not exist and we are creating it, make sure1252 * there is no existing packed ref whose name begins with our1253 * refname, nor a packed ref whose name is a proper prefix of1254 * our refname.1255 */1256if(is_null_oid(&lock->old_oid) &&1257refs_verify_refname_available(&refs->base, refname,1258 extras, skip, err)) {1259 last_errno = ENOTDIR;1260goto error_return;1261}12621263 lock->lk =xcalloc(1,sizeof(struct lock_file));12641265 lock->ref_name =xstrdup(refname);12661267if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1268 last_errno = errno;1269unable_to_lock_message(ref_file.buf, errno, err);1270goto error_return;1271}12721273if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1274 last_errno = errno;1275goto error_return;1276}1277goto out;12781279 error_return:1280unlock_ref(lock);1281 lock = NULL;12821283 out:1284strbuf_release(&ref_file);1285 errno = last_errno;1286return lock;1287}12881289/*1290 * Write an entry to the packed-refs file for the specified refname.1291 * If peeled is non-NULL, write it as the entry's peeled value.1292 */1293static voidwrite_packed_entry(FILE*fh,const char*refname,1294const unsigned char*sha1,1295const unsigned char*peeled)1296{1297fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1298if(peeled)1299fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1300}13011302/*1303 * Lock the packed-refs file for writing. Flags is passed to1304 * hold_lock_file_for_update(). Return 0 on success. On errors, set1305 * errno appropriately and return a nonzero value.1306 */1307static intlock_packed_refs(struct files_ref_store *refs,int flags)1308{1309static int timeout_configured =0;1310static int timeout_value =1000;1311struct packed_ref_cache *packed_ref_cache;13121313files_assert_main_repository(refs,"lock_packed_refs");13141315if(!timeout_configured) {1316git_config_get_int("core.packedrefstimeout", &timeout_value);1317 timeout_configured =1;1318}13191320if(hold_lock_file_for_update_timeout(1321&refs->packed_refs_lock,files_packed_refs_path(refs),1322 flags, timeout_value) <0)1323return-1;13241325/*1326 * Now that we hold the `packed-refs` lock, make sure that our1327 * cache matches the current version of the file. Normally1328 * `get_packed_ref_cache()` does that for us, but that1329 * function assumes that when the file is locked, any existing1330 * cache is still valid. We've just locked the file, but it1331 * might have changed the moment *before* we locked it.1332 */1333validate_packed_ref_cache(refs);13341335 packed_ref_cache =get_packed_ref_cache(refs);1336/* Increment the reference count to prevent it from being freed: */1337acquire_packed_ref_cache(packed_ref_cache);1338return0;1339}13401341/*1342 * Write the current version of the packed refs cache from memory to1343 * disk. The packed-refs file must already be locked for writing (see1344 * lock_packed_refs()). Return zero on success. On errors, set errno1345 * and return a nonzero value1346 */1347static intcommit_packed_refs(struct files_ref_store *refs)1348{1349struct packed_ref_cache *packed_ref_cache =1350get_packed_ref_cache(refs);1351int ok, error =0;1352int save_errno =0;1353FILE*out;1354struct ref_iterator *iter;13551356files_assert_main_repository(refs,"commit_packed_refs");13571358if(!is_lock_file_locked(&refs->packed_refs_lock))1359die("BUG: packed-refs not locked");13601361 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1362if(!out)1363die_errno("unable to fdopen packed-refs descriptor");13641365fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13661367 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1368while((ok =ref_iterator_advance(iter)) == ITER_OK) {1369struct object_id peeled;1370int peel_error =ref_iterator_peel(iter, &peeled);13711372write_packed_entry(out, iter->refname, iter->oid->hash,1373 peel_error ? NULL : peeled.hash);1374}13751376if(ok != ITER_DONE)1377die("error while iterating over references");13781379if(commit_lock_file(&refs->packed_refs_lock)) {1380 save_errno = errno;1381 error = -1;1382}1383release_packed_ref_cache(packed_ref_cache);1384 errno = save_errno;1385return error;1386}13871388/*1389 * Rollback the lockfile for the packed-refs file, and discard the1390 * in-memory packed reference cache. (The packed-refs file will be1391 * read anew if it is needed again after this function is called.)1392 */1393static voidrollback_packed_refs(struct files_ref_store *refs)1394{1395struct packed_ref_cache *packed_ref_cache =1396get_packed_ref_cache(refs);13971398files_assert_main_repository(refs,"rollback_packed_refs");13991400if(!is_lock_file_locked(&refs->packed_refs_lock))1401die("BUG: packed-refs not locked");1402rollback_lock_file(&refs->packed_refs_lock);1403release_packed_ref_cache(packed_ref_cache);1404clear_packed_ref_cache(refs);1405}14061407struct ref_to_prune {1408struct ref_to_prune *next;1409unsigned char sha1[20];1410char name[FLEX_ARRAY];1411};14121413enum{1414 REMOVE_EMPTY_PARENTS_REF =0x01,1415 REMOVE_EMPTY_PARENTS_REFLOG =0x021416};14171418/*1419 * Remove empty parent directories associated with the specified1420 * reference and/or its reflog, but spare [logs/]refs/ and immediate1421 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1422 * REMOVE_EMPTY_PARENTS_REFLOG.1423 */1424static voidtry_remove_empty_parents(struct files_ref_store *refs,1425const char*refname,1426unsigned int flags)1427{1428struct strbuf buf = STRBUF_INIT;1429struct strbuf sb = STRBUF_INIT;1430char*p, *q;1431int i;14321433strbuf_addstr(&buf, refname);1434 p = buf.buf;1435for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1436while(*p && *p !='/')1437 p++;1438/* tolerate duplicate slashes; see check_refname_format() */1439while(*p =='/')1440 p++;1441}1442 q = buf.buf + buf.len;1443while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1444while(q > p && *q !='/')1445 q--;1446while(q > p && *(q-1) =='/')1447 q--;1448if(q == p)1449break;1450strbuf_setlen(&buf, q - buf.buf);14511452strbuf_reset(&sb);1453files_ref_path(refs, &sb, buf.buf);1454if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1455 flags &= ~REMOVE_EMPTY_PARENTS_REF;14561457strbuf_reset(&sb);1458files_reflog_path(refs, &sb, buf.buf);1459if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1460 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1461}1462strbuf_release(&buf);1463strbuf_release(&sb);1464}14651466/* make sure nobody touched the ref, and unlink */1467static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1468{1469struct ref_transaction *transaction;1470struct strbuf err = STRBUF_INIT;14711472if(check_refname_format(r->name,0))1473return;14741475 transaction =ref_store_transaction_begin(&refs->base, &err);1476if(!transaction ||1477ref_transaction_delete(transaction, r->name, r->sha1,1478 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1479ref_transaction_commit(transaction, &err)) {1480ref_transaction_free(transaction);1481error("%s", err.buf);1482strbuf_release(&err);1483return;1484}1485ref_transaction_free(transaction);1486strbuf_release(&err);1487}14881489static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1490{1491while(r) {1492prune_ref(refs, r);1493 r = r->next;1494}1495}14961497/*1498 * Return true if the specified reference should be packed.1499 */1500static intshould_pack_ref(const char*refname,1501const struct object_id *oid,unsigned int ref_flags,1502unsigned int pack_flags)1503{1504/* Do not pack per-worktree refs: */1505if(ref_type(refname) != REF_TYPE_NORMAL)1506return0;15071508/* Do not pack non-tags unless PACK_REFS_ALL is set: */1509if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1510return0;15111512/* Do not pack symbolic refs: */1513if(ref_flags & REF_ISSYMREF)1514return0;15151516/* Do not pack broken refs: */1517if(!ref_resolves_to_object(refname, oid, ref_flags))1518return0;15191520return1;1521}15221523static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1524{1525struct files_ref_store *refs =1526files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1527"pack_refs");1528struct ref_iterator *iter;1529struct ref_dir *packed_refs;1530int ok;1531struct ref_to_prune *refs_to_prune = NULL;15321533lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1534 packed_refs =get_packed_refs(refs);15351536 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1537while((ok =ref_iterator_advance(iter)) == ITER_OK) {1538/*1539 * If the loose reference can be packed, add an entry1540 * in the packed ref cache. If the reference should be1541 * pruned, also add it to refs_to_prune.1542 */1543struct ref_entry *packed_entry;15441545if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1546 flags))1547continue;15481549/*1550 * Create an entry in the packed-refs cache equivalent1551 * to the one from the loose ref cache, except that1552 * we don't copy the peeled status, because we want it1553 * to be re-peeled.1554 */1555 packed_entry =find_ref_entry(packed_refs, iter->refname);1556if(packed_entry) {1557/* Overwrite existing packed entry with info from loose entry */1558 packed_entry->flag = REF_ISPACKED;1559oidcpy(&packed_entry->u.value.oid, iter->oid);1560}else{1561 packed_entry =create_ref_entry(iter->refname, iter->oid,1562 REF_ISPACKED);1563add_ref_entry(packed_refs, packed_entry);1564}1565oidclr(&packed_entry->u.value.peeled);15661567/* Schedule the loose reference for pruning if requested. */1568if((flags & PACK_REFS_PRUNE)) {1569struct ref_to_prune *n;1570FLEX_ALLOC_STR(n, name, iter->refname);1571hashcpy(n->sha1, iter->oid->hash);1572 n->next = refs_to_prune;1573 refs_to_prune = n;1574}1575}1576if(ok != ITER_DONE)1577die("error while iterating over references");15781579if(commit_packed_refs(refs))1580die_errno("unable to overwrite old ref-pack file");15811582prune_refs(refs, refs_to_prune);1583return0;1584}15851586/*1587 * Rewrite the packed-refs file, omitting any refs listed in1588 * 'refnames'. On error, leave packed-refs unchanged, write an error1589 * message to 'err', and return a nonzero value.1590 *1591 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1592 */1593static intrepack_without_refs(struct files_ref_store *refs,1594struct string_list *refnames,struct strbuf *err)1595{1596struct ref_dir *packed;1597struct string_list_item *refname;1598int ret, needs_repacking =0, removed =0;15991600files_assert_main_repository(refs,"repack_without_refs");1601assert(err);16021603/* Look for a packed ref */1604for_each_string_list_item(refname, refnames) {1605if(get_packed_ref(refs, refname->string)) {1606 needs_repacking =1;1607break;1608}1609}16101611/* Avoid locking if we have nothing to do */1612if(!needs_repacking)1613return0;/* no refname exists in packed refs */16141615if(lock_packed_refs(refs,0)) {1616unable_to_lock_message(files_packed_refs_path(refs), errno, err);1617return-1;1618}1619 packed =get_packed_refs(refs);16201621/* Remove refnames from the cache */1622for_each_string_list_item(refname, refnames)1623if(remove_entry_from_dir(packed, refname->string) != -1)1624 removed =1;1625if(!removed) {1626/*1627 * All packed entries disappeared while we were1628 * acquiring the lock.1629 */1630rollback_packed_refs(refs);1631return0;1632}16331634/* Write what remains */1635 ret =commit_packed_refs(refs);1636if(ret)1637strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1638strerror(errno));1639return ret;1640}16411642static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1643struct string_list *refnames,unsigned int flags)1644{1645struct files_ref_store *refs =1646files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1647struct strbuf err = STRBUF_INIT;1648int i, result =0;16491650if(!refnames->nr)1651return0;16521653 result =repack_without_refs(refs, refnames, &err);1654if(result) {1655/*1656 * If we failed to rewrite the packed-refs file, then1657 * it is unsafe to try to remove loose refs, because1658 * doing so might expose an obsolete packed value for1659 * a reference that might even point at an object that1660 * has been garbage collected.1661 */1662if(refnames->nr ==1)1663error(_("could not delete reference%s:%s"),1664 refnames->items[0].string, err.buf);1665else1666error(_("could not delete references:%s"), err.buf);16671668goto out;1669}16701671for(i =0; i < refnames->nr; i++) {1672const char*refname = refnames->items[i].string;16731674if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1675 result |=error(_("could not remove reference%s"), refname);1676}16771678out:1679strbuf_release(&err);1680return result;1681}16821683/*1684 * People using contrib's git-new-workdir have .git/logs/refs ->1685 * /some/other/path/.git/logs/refs, and that may live on another device.1686 *1687 * IOW, to avoid cross device rename errors, the temporary renamed log must1688 * live into logs/refs.1689 */1690#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16911692struct rename_cb {1693const char*tmp_renamed_log;1694int true_errno;1695};16961697static intrename_tmp_log_callback(const char*path,void*cb_data)1698{1699struct rename_cb *cb = cb_data;17001701if(rename(cb->tmp_renamed_log, path)) {1702/*1703 * rename(a, b) when b is an existing directory ought1704 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1705 * Sheesh. Record the true errno for error reporting,1706 * but report EISDIR to raceproof_create_file() so1707 * that it knows to retry.1708 */1709 cb->true_errno = errno;1710if(errno == ENOTDIR)1711 errno = EISDIR;1712return-1;1713}else{1714return0;1715}1716}17171718static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1719{1720struct strbuf path = STRBUF_INIT;1721struct strbuf tmp = STRBUF_INIT;1722struct rename_cb cb;1723int ret;17241725files_reflog_path(refs, &path, newrefname);1726files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1727 cb.tmp_renamed_log = tmp.buf;1728 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1729if(ret) {1730if(errno == EISDIR)1731error("directory not empty:%s", path.buf);1732else1733error("unable to move logfile%sto%s:%s",1734 tmp.buf, path.buf,1735strerror(cb.true_errno));1736}17371738strbuf_release(&path);1739strbuf_release(&tmp);1740return ret;1741}17421743static intwrite_ref_to_lockfile(struct ref_lock *lock,1744const struct object_id *oid,struct strbuf *err);1745static intcommit_ref_update(struct files_ref_store *refs,1746struct ref_lock *lock,1747const struct object_id *oid,const char*logmsg,1748struct strbuf *err);17491750static intfiles_rename_ref(struct ref_store *ref_store,1751const char*oldrefname,const char*newrefname,1752const char*logmsg)1753{1754struct files_ref_store *refs =1755files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1756struct object_id oid, orig_oid;1757int flag =0, logmoved =0;1758struct ref_lock *lock;1759struct stat loginfo;1760struct strbuf sb_oldref = STRBUF_INIT;1761struct strbuf sb_newref = STRBUF_INIT;1762struct strbuf tmp_renamed_log = STRBUF_INIT;1763int log, ret;1764struct strbuf err = STRBUF_INIT;17651766files_reflog_path(refs, &sb_oldref, oldrefname);1767files_reflog_path(refs, &sb_newref, newrefname);1768files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17691770 log = !lstat(sb_oldref.buf, &loginfo);1771if(log &&S_ISLNK(loginfo.st_mode)) {1772 ret =error("reflog for%sis a symlink", oldrefname);1773goto out;1774}17751776if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1777 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1778 orig_oid.hash, &flag)) {1779 ret =error("refname%snot found", oldrefname);1780goto out;1781}17821783if(flag & REF_ISSYMREF) {1784 ret =error("refname%sis a symbolic ref, renaming it is not supported",1785 oldrefname);1786goto out;1787}1788if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1789 ret =1;1790goto out;1791}17921793if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1794 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1795 oldrefname,strerror(errno));1796goto out;1797}17981799if(refs_delete_ref(&refs->base, logmsg, oldrefname,1800 orig_oid.hash, REF_NODEREF)) {1801error("unable to delete old%s", oldrefname);1802goto rollback;1803}18041805/*1806 * Since we are doing a shallow lookup, oid is not the1807 * correct value to pass to delete_ref as old_oid. But that1808 * doesn't matter, because an old_oid check wouldn't add to1809 * the safety anyway; we want to delete the reference whatever1810 * its current value.1811 */1812if(!refs_read_ref_full(&refs->base, newrefname,1813 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1814 oid.hash, NULL) &&1815refs_delete_ref(&refs->base, NULL, newrefname,1816 NULL, REF_NODEREF)) {1817if(errno == EISDIR) {1818struct strbuf path = STRBUF_INIT;1819int result;18201821files_ref_path(refs, &path, newrefname);1822 result =remove_empty_directories(&path);1823strbuf_release(&path);18241825if(result) {1826error("Directory not empty:%s", newrefname);1827goto rollback;1828}1829}else{1830error("unable to delete existing%s", newrefname);1831goto rollback;1832}1833}18341835if(log &&rename_tmp_log(refs, newrefname))1836goto rollback;18371838 logmoved = log;18391840 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1841 REF_NODEREF, NULL, &err);1842if(!lock) {1843error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1844strbuf_release(&err);1845goto rollback;1846}1847oidcpy(&lock->old_oid, &orig_oid);18481849if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1850commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1851error("unable to write current sha1 into%s:%s", newrefname, err.buf);1852strbuf_release(&err);1853goto rollback;1854}18551856 ret =0;1857goto out;18581859 rollback:1860 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1861 REF_NODEREF, NULL, &err);1862if(!lock) {1863error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1864strbuf_release(&err);1865goto rollbacklog;1866}18671868 flag = log_all_ref_updates;1869 log_all_ref_updates = LOG_REFS_NONE;1870if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1871commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1872error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1873strbuf_release(&err);1874}1875 log_all_ref_updates = flag;18761877 rollbacklog:1878if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1879error("unable to restore logfile%sfrom%s:%s",1880 oldrefname, newrefname,strerror(errno));1881if(!logmoved && log &&1882rename(tmp_renamed_log.buf, sb_oldref.buf))1883error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1884 oldrefname,strerror(errno));1885 ret =1;1886 out:1887strbuf_release(&sb_newref);1888strbuf_release(&sb_oldref);1889strbuf_release(&tmp_renamed_log);18901891return ret;1892}18931894static intclose_ref(struct ref_lock *lock)1895{1896if(close_lock_file(lock->lk))1897return-1;1898return0;1899}19001901static intcommit_ref(struct ref_lock *lock)1902{1903char*path =get_locked_file_path(lock->lk);1904struct stat st;19051906if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1907/*1908 * There is a directory at the path we want to rename1909 * the lockfile to. Hopefully it is empty; try to1910 * delete it.1911 */1912size_t len =strlen(path);1913struct strbuf sb_path = STRBUF_INIT;19141915strbuf_attach(&sb_path, path, len, len);19161917/*1918 * If this fails, commit_lock_file() will also fail1919 * and will report the problem.1920 */1921remove_empty_directories(&sb_path);1922strbuf_release(&sb_path);1923}else{1924free(path);1925}19261927if(commit_lock_file(lock->lk))1928return-1;1929return0;1930}19311932static intopen_or_create_logfile(const char*path,void*cb)1933{1934int*fd = cb;19351936*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1937return(*fd <0) ? -1:0;1938}19391940/*1941 * Create a reflog for a ref. If force_create = 0, only create the1942 * reflog for certain refs (those for which should_autocreate_reflog1943 * returns non-zero). Otherwise, create it regardless of the reference1944 * name. If the logfile already existed or was created, return 0 and1945 * set *logfd to the file descriptor opened for appending to the file.1946 * If no logfile exists and we decided not to create one, return 0 and1947 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1948 * return -1.1949 */1950static intlog_ref_setup(struct files_ref_store *refs,1951const char*refname,int force_create,1952int*logfd,struct strbuf *err)1953{1954struct strbuf logfile_sb = STRBUF_INIT;1955char*logfile;19561957files_reflog_path(refs, &logfile_sb, refname);1958 logfile =strbuf_detach(&logfile_sb, NULL);19591960if(force_create ||should_autocreate_reflog(refname)) {1961if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1962if(errno == ENOENT)1963strbuf_addf(err,"unable to create directory for '%s': "1964"%s", logfile,strerror(errno));1965else if(errno == EISDIR)1966strbuf_addf(err,"there are still logs under '%s'",1967 logfile);1968else1969strbuf_addf(err,"unable to append to '%s':%s",1970 logfile,strerror(errno));19711972goto error;1973}1974}else{1975*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1976if(*logfd <0) {1977if(errno == ENOENT || errno == EISDIR) {1978/*1979 * The logfile doesn't already exist,1980 * but that is not an error; it only1981 * means that we won't write log1982 * entries to it.1983 */1984;1985}else{1986strbuf_addf(err,"unable to append to '%s':%s",1987 logfile,strerror(errno));1988goto error;1989}1990}1991}19921993if(*logfd >=0)1994adjust_shared_perm(logfile);19951996free(logfile);1997return0;19981999error:2000free(logfile);2001return-1;2002}20032004static intfiles_create_reflog(struct ref_store *ref_store,2005const char*refname,int force_create,2006struct strbuf *err)2007{2008struct files_ref_store *refs =2009files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2010int fd;20112012if(log_ref_setup(refs, refname, force_create, &fd, err))2013return-1;20142015if(fd >=0)2016close(fd);20172018return0;2019}20202021static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2022const struct object_id *new_oid,2023const char*committer,const char*msg)2024{2025int msglen, written;2026unsigned maxlen, len;2027char*logrec;20282029 msglen = msg ?strlen(msg) :0;2030 maxlen =strlen(committer) + msglen +100;2031 logrec =xmalloc(maxlen);2032 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2033oid_to_hex(old_oid),2034oid_to_hex(new_oid),2035 committer);2036if(msglen)2037 len +=copy_reflog_msg(logrec + len -1, msg) -1;20382039 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2040free(logrec);2041if(written != len)2042return-1;20432044return0;2045}20462047static intfiles_log_ref_write(struct files_ref_store *refs,2048const char*refname,const struct object_id *old_oid,2049const struct object_id *new_oid,const char*msg,2050int flags,struct strbuf *err)2051{2052int logfd, result;20532054if(log_all_ref_updates == LOG_REFS_UNSET)2055 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20562057 result =log_ref_setup(refs, refname,2058 flags & REF_FORCE_CREATE_REFLOG,2059&logfd, err);20602061if(result)2062return result;20632064if(logfd <0)2065return0;2066 result =log_ref_write_fd(logfd, old_oid, new_oid,2067git_committer_info(0), msg);2068if(result) {2069struct strbuf sb = STRBUF_INIT;2070int save_errno = errno;20712072files_reflog_path(refs, &sb, refname);2073strbuf_addf(err,"unable to append to '%s':%s",2074 sb.buf,strerror(save_errno));2075strbuf_release(&sb);2076close(logfd);2077return-1;2078}2079if(close(logfd)) {2080struct strbuf sb = STRBUF_INIT;2081int save_errno = errno;20822083files_reflog_path(refs, &sb, refname);2084strbuf_addf(err,"unable to append to '%s':%s",2085 sb.buf,strerror(save_errno));2086strbuf_release(&sb);2087return-1;2088}2089return0;2090}20912092/*2093 * Write sha1 into the open lockfile, then close the lockfile. On2094 * errors, rollback the lockfile, fill in *err and2095 * return -1.2096 */2097static intwrite_ref_to_lockfile(struct ref_lock *lock,2098const struct object_id *oid,struct strbuf *err)2099{2100static char term ='\n';2101struct object *o;2102int fd;21032104 o =parse_object(oid);2105if(!o) {2106strbuf_addf(err,2107"trying to write ref '%s' with nonexistent object%s",2108 lock->ref_name,oid_to_hex(oid));2109unlock_ref(lock);2110return-1;2111}2112if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2113strbuf_addf(err,2114"trying to write non-commit object%sto branch '%s'",2115oid_to_hex(oid), lock->ref_name);2116unlock_ref(lock);2117return-1;2118}2119 fd =get_lock_file_fd(lock->lk);2120if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2121write_in_full(fd, &term,1) !=1||2122close_ref(lock) <0) {2123strbuf_addf(err,2124"couldn't write '%s'",get_lock_file_path(lock->lk));2125unlock_ref(lock);2126return-1;2127}2128return0;2129}21302131/*2132 * Commit a change to a loose reference that has already been written2133 * to the loose reference lockfile. Also update the reflogs if2134 * necessary, using the specified lockmsg (which can be NULL).2135 */2136static intcommit_ref_update(struct files_ref_store *refs,2137struct ref_lock *lock,2138const struct object_id *oid,const char*logmsg,2139struct strbuf *err)2140{2141files_assert_main_repository(refs,"commit_ref_update");21422143clear_loose_ref_cache(refs);2144if(files_log_ref_write(refs, lock->ref_name,2145&lock->old_oid, oid,2146 logmsg,0, err)) {2147char*old_msg =strbuf_detach(err, NULL);2148strbuf_addf(err,"cannot update the ref '%s':%s",2149 lock->ref_name, old_msg);2150free(old_msg);2151unlock_ref(lock);2152return-1;2153}21542155if(strcmp(lock->ref_name,"HEAD") !=0) {2156/*2157 * Special hack: If a branch is updated directly and HEAD2158 * points to it (may happen on the remote side of a push2159 * for example) then logically the HEAD reflog should be2160 * updated too.2161 * A generic solution implies reverse symref information,2162 * but finding all symrefs pointing to the given branch2163 * would be rather costly for this rare event (the direct2164 * update of a branch) to be worth it. So let's cheat and2165 * check with HEAD only which should cover 99% of all usage2166 * scenarios (even 100% of the default ones).2167 */2168struct object_id head_oid;2169int head_flag;2170const char*head_ref;21712172 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2173 RESOLVE_REF_READING,2174 head_oid.hash, &head_flag);2175if(head_ref && (head_flag & REF_ISSYMREF) &&2176!strcmp(head_ref, lock->ref_name)) {2177struct strbuf log_err = STRBUF_INIT;2178if(files_log_ref_write(refs,"HEAD",2179&lock->old_oid, oid,2180 logmsg,0, &log_err)) {2181error("%s", log_err.buf);2182strbuf_release(&log_err);2183}2184}2185}21862187if(commit_ref(lock)) {2188strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2189unlock_ref(lock);2190return-1;2191}21922193unlock_ref(lock);2194return0;2195}21962197static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2198{2199int ret = -1;2200#ifndef NO_SYMLINK_HEAD2201char*ref_path =get_locked_file_path(lock->lk);2202unlink(ref_path);2203 ret =symlink(target, ref_path);2204free(ref_path);22052206if(ret)2207fprintf(stderr,"no symlink - falling back to symbolic ref\n");2208#endif2209return ret;2210}22112212static voidupdate_symref_reflog(struct files_ref_store *refs,2213struct ref_lock *lock,const char*refname,2214const char*target,const char*logmsg)2215{2216struct strbuf err = STRBUF_INIT;2217struct object_id new_oid;2218if(logmsg &&2219!refs_read_ref_full(&refs->base, target,2220 RESOLVE_REF_READING, new_oid.hash, NULL) &&2221files_log_ref_write(refs, refname, &lock->old_oid,2222&new_oid, logmsg,0, &err)) {2223error("%s", err.buf);2224strbuf_release(&err);2225}2226}22272228static intcreate_symref_locked(struct files_ref_store *refs,2229struct ref_lock *lock,const char*refname,2230const char*target,const char*logmsg)2231{2232if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2233update_symref_reflog(refs, lock, refname, target, logmsg);2234return0;2235}22362237if(!fdopen_lock_file(lock->lk,"w"))2238returnerror("unable to fdopen%s:%s",2239 lock->lk->tempfile.filename.buf,strerror(errno));22402241update_symref_reflog(refs, lock, refname, target, logmsg);22422243/* no error check; commit_ref will check ferror */2244fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2245if(commit_ref(lock) <0)2246returnerror("unable to write symref for%s:%s", refname,2247strerror(errno));2248return0;2249}22502251static intfiles_create_symref(struct ref_store *ref_store,2252const char*refname,const char*target,2253const char*logmsg)2254{2255struct files_ref_store *refs =2256files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2257struct strbuf err = STRBUF_INIT;2258struct ref_lock *lock;2259int ret;22602261 lock =lock_ref_sha1_basic(refs, refname, NULL,2262 NULL, NULL, REF_NODEREF, NULL,2263&err);2264if(!lock) {2265error("%s", err.buf);2266strbuf_release(&err);2267return-1;2268}22692270 ret =create_symref_locked(refs, lock, refname, target, logmsg);2271unlock_ref(lock);2272return ret;2273}22742275static intfiles_reflog_exists(struct ref_store *ref_store,2276const char*refname)2277{2278struct files_ref_store *refs =2279files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2280struct strbuf sb = STRBUF_INIT;2281struct stat st;2282int ret;22832284files_reflog_path(refs, &sb, refname);2285 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2286strbuf_release(&sb);2287return ret;2288}22892290static intfiles_delete_reflog(struct ref_store *ref_store,2291const char*refname)2292{2293struct files_ref_store *refs =2294files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2295struct strbuf sb = STRBUF_INIT;2296int ret;22972298files_reflog_path(refs, &sb, refname);2299 ret =remove_path(sb.buf);2300strbuf_release(&sb);2301return ret;2302}23032304static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2305{2306struct object_id ooid, noid;2307char*email_end, *message;2308 timestamp_t timestamp;2309int tz;2310const char*p = sb->buf;23112312/* old SP new SP name <email> SP time TAB msg LF */2313if(!sb->len || sb->buf[sb->len -1] !='\n'||2314parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2315parse_oid_hex(p, &noid, &p) || *p++ !=' '||2316!(email_end =strchr(p,'>')) ||2317 email_end[1] !=' '||2318!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2319!message || message[0] !=' '||2320(message[1] !='+'&& message[1] !='-') ||2321!isdigit(message[2]) || !isdigit(message[3]) ||2322!isdigit(message[4]) || !isdigit(message[5]))2323return0;/* corrupt? */2324 email_end[1] ='\0';2325 tz =strtol(message +1, NULL,10);2326if(message[6] !='\t')2327 message +=6;2328else2329 message +=7;2330returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2331}23322333static char*find_beginning_of_line(char*bob,char*scan)2334{2335while(bob < scan && *(--scan) !='\n')2336;/* keep scanning backwards */2337/*2338 * Return either beginning of the buffer, or LF at the end of2339 * the previous line.2340 */2341return scan;2342}23432344static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2345const char*refname,2346 each_reflog_ent_fn fn,2347void*cb_data)2348{2349struct files_ref_store *refs =2350files_downcast(ref_store, REF_STORE_READ,2351"for_each_reflog_ent_reverse");2352struct strbuf sb = STRBUF_INIT;2353FILE*logfp;2354long pos;2355int ret =0, at_tail =1;23562357files_reflog_path(refs, &sb, refname);2358 logfp =fopen(sb.buf,"r");2359strbuf_release(&sb);2360if(!logfp)2361return-1;23622363/* Jump to the end */2364if(fseek(logfp,0, SEEK_END) <0)2365 ret =error("cannot seek back reflog for%s:%s",2366 refname,strerror(errno));2367 pos =ftell(logfp);2368while(!ret &&0< pos) {2369int cnt;2370size_t nread;2371char buf[BUFSIZ];2372char*endp, *scanp;23732374/* Fill next block from the end */2375 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2376if(fseek(logfp, pos - cnt, SEEK_SET)) {2377 ret =error("cannot seek back reflog for%s:%s",2378 refname,strerror(errno));2379break;2380}2381 nread =fread(buf, cnt,1, logfp);2382if(nread !=1) {2383 ret =error("cannot read%dbytes from reflog for%s:%s",2384 cnt, refname,strerror(errno));2385break;2386}2387 pos -= cnt;23882389 scanp = endp = buf + cnt;2390if(at_tail && scanp[-1] =='\n')2391/* Looking at the final LF at the end of the file */2392 scanp--;2393 at_tail =0;23942395while(buf < scanp) {2396/*2397 * terminating LF of the previous line, or the beginning2398 * of the buffer.2399 */2400char*bp;24012402 bp =find_beginning_of_line(buf, scanp);24032404if(*bp =='\n') {2405/*2406 * The newline is the end of the previous line,2407 * so we know we have complete line starting2408 * at (bp + 1). Prefix it onto any prior data2409 * we collected for the line and process it.2410 */2411strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2412 scanp = bp;2413 endp = bp +1;2414 ret =show_one_reflog_ent(&sb, fn, cb_data);2415strbuf_reset(&sb);2416if(ret)2417break;2418}else if(!pos) {2419/*2420 * We are at the start of the buffer, and the2421 * start of the file; there is no previous2422 * line, and we have everything for this one.2423 * Process it, and we can end the loop.2424 */2425strbuf_splice(&sb,0,0, buf, endp - buf);2426 ret =show_one_reflog_ent(&sb, fn, cb_data);2427strbuf_reset(&sb);2428break;2429}24302431if(bp == buf) {2432/*2433 * We are at the start of the buffer, and there2434 * is more file to read backwards. Which means2435 * we are in the middle of a line. Note that we2436 * may get here even if *bp was a newline; that2437 * just means we are at the exact end of the2438 * previous line, rather than some spot in the2439 * middle.2440 *2441 * Save away what we have to be combined with2442 * the data from the next read.2443 */2444strbuf_splice(&sb,0,0, buf, endp - buf);2445break;2446}2447}24482449}2450if(!ret && sb.len)2451die("BUG: reverse reflog parser had leftover data");24522453fclose(logfp);2454strbuf_release(&sb);2455return ret;2456}24572458static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2459const char*refname,2460 each_reflog_ent_fn fn,void*cb_data)2461{2462struct files_ref_store *refs =2463files_downcast(ref_store, REF_STORE_READ,2464"for_each_reflog_ent");2465FILE*logfp;2466struct strbuf sb = STRBUF_INIT;2467int ret =0;24682469files_reflog_path(refs, &sb, refname);2470 logfp =fopen(sb.buf,"r");2471strbuf_release(&sb);2472if(!logfp)2473return-1;24742475while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2476 ret =show_one_reflog_ent(&sb, fn, cb_data);2477fclose(logfp);2478strbuf_release(&sb);2479return ret;2480}24812482struct files_reflog_iterator {2483struct ref_iterator base;24842485struct ref_store *ref_store;2486struct dir_iterator *dir_iterator;2487struct object_id oid;2488};24892490static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2491{2492struct files_reflog_iterator *iter =2493(struct files_reflog_iterator *)ref_iterator;2494struct dir_iterator *diter = iter->dir_iterator;2495int ok;24962497while((ok =dir_iterator_advance(diter)) == ITER_OK) {2498int flags;24992500if(!S_ISREG(diter->st.st_mode))2501continue;2502if(diter->basename[0] =='.')2503continue;2504if(ends_with(diter->basename,".lock"))2505continue;25062507if(refs_read_ref_full(iter->ref_store,2508 diter->relative_path,0,2509 iter->oid.hash, &flags)) {2510error("bad ref for%s", diter->path.buf);2511continue;2512}25132514 iter->base.refname = diter->relative_path;2515 iter->base.oid = &iter->oid;2516 iter->base.flags = flags;2517return ITER_OK;2518}25192520 iter->dir_iterator = NULL;2521if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2522 ok = ITER_ERROR;2523return ok;2524}25252526static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2527struct object_id *peeled)2528{2529die("BUG: ref_iterator_peel() called for reflog_iterator");2530}25312532static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2533{2534struct files_reflog_iterator *iter =2535(struct files_reflog_iterator *)ref_iterator;2536int ok = ITER_DONE;25372538if(iter->dir_iterator)2539 ok =dir_iterator_abort(iter->dir_iterator);25402541base_ref_iterator_free(ref_iterator);2542return ok;2543}25442545static struct ref_iterator_vtable files_reflog_iterator_vtable = {2546 files_reflog_iterator_advance,2547 files_reflog_iterator_peel,2548 files_reflog_iterator_abort2549};25502551static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2552{2553struct files_ref_store *refs =2554files_downcast(ref_store, REF_STORE_READ,2555"reflog_iterator_begin");2556struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2557struct ref_iterator *ref_iterator = &iter->base;2558struct strbuf sb = STRBUF_INIT;25592560base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2561files_reflog_path(refs, &sb, NULL);2562 iter->dir_iterator =dir_iterator_begin(sb.buf);2563 iter->ref_store = ref_store;2564strbuf_release(&sb);2565return ref_iterator;2566}25672568/*2569 * If update is a direct update of head_ref (the reference pointed to2570 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2571 */2572static intsplit_head_update(struct ref_update *update,2573struct ref_transaction *transaction,2574const char*head_ref,2575struct string_list *affected_refnames,2576struct strbuf *err)2577{2578struct string_list_item *item;2579struct ref_update *new_update;25802581if((update->flags & REF_LOG_ONLY) ||2582(update->flags & REF_ISPRUNING) ||2583(update->flags & REF_UPDATE_VIA_HEAD))2584return0;25852586if(strcmp(update->refname, head_ref))2587return0;25882589/*2590 * First make sure that HEAD is not already in the2591 * transaction. This insertion is O(N) in the transaction2592 * size, but it happens at most once per transaction.2593 */2594 item =string_list_insert(affected_refnames,"HEAD");2595if(item->util) {2596/* An entry already existed */2597strbuf_addf(err,2598"multiple updates for 'HEAD' (including one "2599"via its referent '%s') are not allowed",2600 update->refname);2601return TRANSACTION_NAME_CONFLICT;2602}26032604 new_update =ref_transaction_add_update(2605 transaction,"HEAD",2606 update->flags | REF_LOG_ONLY | REF_NODEREF,2607 update->new_oid.hash, update->old_oid.hash,2608 update->msg);26092610 item->util = new_update;26112612return0;2613}26142615/*2616 * update is for a symref that points at referent and doesn't have2617 * REF_NODEREF set. Split it into two updates:2618 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2619 * - A new, separate update for the referent reference2620 * Note that the new update will itself be subject to splitting when2621 * the iteration gets to it.2622 */2623static intsplit_symref_update(struct files_ref_store *refs,2624struct ref_update *update,2625const char*referent,2626struct ref_transaction *transaction,2627struct string_list *affected_refnames,2628struct strbuf *err)2629{2630struct string_list_item *item;2631struct ref_update *new_update;2632unsigned int new_flags;26332634/*2635 * First make sure that referent is not already in the2636 * transaction. This insertion is O(N) in the transaction2637 * size, but it happens at most once per symref in a2638 * transaction.2639 */2640 item =string_list_insert(affected_refnames, referent);2641if(item->util) {2642/* An entry already existed */2643strbuf_addf(err,2644"multiple updates for '%s' (including one "2645"via symref '%s') are not allowed",2646 referent, update->refname);2647return TRANSACTION_NAME_CONFLICT;2648}26492650 new_flags = update->flags;2651if(!strcmp(update->refname,"HEAD")) {2652/*2653 * Record that the new update came via HEAD, so that2654 * when we process it, split_head_update() doesn't try2655 * to add another reflog update for HEAD. Note that2656 * this bit will be propagated if the new_update2657 * itself needs to be split.2658 */2659 new_flags |= REF_UPDATE_VIA_HEAD;2660}26612662 new_update =ref_transaction_add_update(2663 transaction, referent, new_flags,2664 update->new_oid.hash, update->old_oid.hash,2665 update->msg);26662667 new_update->parent_update = update;26682669/*2670 * Change the symbolic ref update to log only. Also, it2671 * doesn't need to check its old SHA-1 value, as that will be2672 * done when new_update is processed.2673 */2674 update->flags |= REF_LOG_ONLY | REF_NODEREF;2675 update->flags &= ~REF_HAVE_OLD;26762677 item->util = new_update;26782679return0;2680}26812682/*2683 * Return the refname under which update was originally requested.2684 */2685static const char*original_update_refname(struct ref_update *update)2686{2687while(update->parent_update)2688 update = update->parent_update;26892690return update->refname;2691}26922693/*2694 * Check whether the REF_HAVE_OLD and old_oid values stored in update2695 * are consistent with oid, which is the reference's current value. If2696 * everything is OK, return 0; otherwise, write an error message to2697 * err and return -1.2698 */2699static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2700struct strbuf *err)2701{2702if(!(update->flags & REF_HAVE_OLD) ||2703!oidcmp(oid, &update->old_oid))2704return0;27052706if(is_null_oid(&update->old_oid))2707strbuf_addf(err,"cannot lock ref '%s': "2708"reference already exists",2709original_update_refname(update));2710else if(is_null_oid(oid))2711strbuf_addf(err,"cannot lock ref '%s': "2712"reference is missing but expected%s",2713original_update_refname(update),2714oid_to_hex(&update->old_oid));2715else2716strbuf_addf(err,"cannot lock ref '%s': "2717"is at%sbut expected%s",2718original_update_refname(update),2719oid_to_hex(oid),2720oid_to_hex(&update->old_oid));27212722return-1;2723}27242725/*2726 * Prepare for carrying out update:2727 * - Lock the reference referred to by update.2728 * - Read the reference under lock.2729 * - Check that its old SHA-1 value (if specified) is correct, and in2730 * any case record it in update->lock->old_oid for later use when2731 * writing the reflog.2732 * - If it is a symref update without REF_NODEREF, split it up into a2733 * REF_LOG_ONLY update of the symref and add a separate update for2734 * the referent to transaction.2735 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2736 * update of HEAD.2737 */2738static intlock_ref_for_update(struct files_ref_store *refs,2739struct ref_update *update,2740struct ref_transaction *transaction,2741const char*head_ref,2742struct string_list *affected_refnames,2743struct strbuf *err)2744{2745struct strbuf referent = STRBUF_INIT;2746int mustexist = (update->flags & REF_HAVE_OLD) &&2747!is_null_oid(&update->old_oid);2748int ret;2749struct ref_lock *lock;27502751files_assert_main_repository(refs,"lock_ref_for_update");27522753if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2754 update->flags |= REF_DELETING;27552756if(head_ref) {2757 ret =split_head_update(update, transaction, head_ref,2758 affected_refnames, err);2759if(ret)2760return ret;2761}27622763 ret =lock_raw_ref(refs, update->refname, mustexist,2764 affected_refnames, NULL,2765&lock, &referent,2766&update->type, err);2767if(ret) {2768char*reason;27692770 reason =strbuf_detach(err, NULL);2771strbuf_addf(err,"cannot lock ref '%s':%s",2772original_update_refname(update), reason);2773free(reason);2774return ret;2775}27762777 update->backend_data = lock;27782779if(update->type & REF_ISSYMREF) {2780if(update->flags & REF_NODEREF) {2781/*2782 * We won't be reading the referent as part of2783 * the transaction, so we have to read it here2784 * to record and possibly check old_sha1:2785 */2786if(refs_read_ref_full(&refs->base,2787 referent.buf,0,2788 lock->old_oid.hash, NULL)) {2789if(update->flags & REF_HAVE_OLD) {2790strbuf_addf(err,"cannot lock ref '%s': "2791"error reading reference",2792original_update_refname(update));2793return-1;2794}2795}else if(check_old_oid(update, &lock->old_oid, err)) {2796return TRANSACTION_GENERIC_ERROR;2797}2798}else{2799/*2800 * Create a new update for the reference this2801 * symref is pointing at. Also, we will record2802 * and verify old_sha1 for this update as part2803 * of processing the split-off update, so we2804 * don't have to do it here.2805 */2806 ret =split_symref_update(refs, update,2807 referent.buf, transaction,2808 affected_refnames, err);2809if(ret)2810return ret;2811}2812}else{2813struct ref_update *parent_update;28142815if(check_old_oid(update, &lock->old_oid, err))2816return TRANSACTION_GENERIC_ERROR;28172818/*2819 * If this update is happening indirectly because of a2820 * symref update, record the old SHA-1 in the parent2821 * update:2822 */2823for(parent_update = update->parent_update;2824 parent_update;2825 parent_update = parent_update->parent_update) {2826struct ref_lock *parent_lock = parent_update->backend_data;2827oidcpy(&parent_lock->old_oid, &lock->old_oid);2828}2829}28302831if((update->flags & REF_HAVE_NEW) &&2832!(update->flags & REF_DELETING) &&2833!(update->flags & REF_LOG_ONLY)) {2834if(!(update->type & REF_ISSYMREF) &&2835!oidcmp(&lock->old_oid, &update->new_oid)) {2836/*2837 * The reference already has the desired2838 * value, so we don't need to write it.2839 */2840}else if(write_ref_to_lockfile(lock, &update->new_oid,2841 err)) {2842char*write_err =strbuf_detach(err, NULL);28432844/*2845 * The lock was freed upon failure of2846 * write_ref_to_lockfile():2847 */2848 update->backend_data = NULL;2849strbuf_addf(err,2850"cannot update ref '%s':%s",2851 update->refname, write_err);2852free(write_err);2853return TRANSACTION_GENERIC_ERROR;2854}else{2855 update->flags |= REF_NEEDS_COMMIT;2856}2857}2858if(!(update->flags & REF_NEEDS_COMMIT)) {2859/*2860 * We didn't call write_ref_to_lockfile(), so2861 * the lockfile is still open. Close it to2862 * free up the file descriptor:2863 */2864if(close_ref(lock)) {2865strbuf_addf(err,"couldn't close '%s.lock'",2866 update->refname);2867return TRANSACTION_GENERIC_ERROR;2868}2869}2870return0;2871}28722873/*2874 * Unlock any references in `transaction` that are still locked, and2875 * mark the transaction closed.2876 */2877static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2878{2879size_t i;28802881for(i =0; i < transaction->nr; i++) {2882struct ref_update *update = transaction->updates[i];2883struct ref_lock *lock = update->backend_data;28842885if(lock) {2886unlock_ref(lock);2887 update->backend_data = NULL;2888}2889}28902891 transaction->state = REF_TRANSACTION_CLOSED;2892}28932894static intfiles_transaction_prepare(struct ref_store *ref_store,2895struct ref_transaction *transaction,2896struct strbuf *err)2897{2898struct files_ref_store *refs =2899files_downcast(ref_store, REF_STORE_WRITE,2900"ref_transaction_prepare");2901size_t i;2902int ret =0;2903struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2904char*head_ref = NULL;2905int head_type;2906struct object_id head_oid;29072908assert(err);29092910if(!transaction->nr)2911goto cleanup;29122913/*2914 * Fail if a refname appears more than once in the2915 * transaction. (If we end up splitting up any updates using2916 * split_symref_update() or split_head_update(), those2917 * functions will check that the new updates don't have the2918 * same refname as any existing ones.)2919 */2920for(i =0; i < transaction->nr; i++) {2921struct ref_update *update = transaction->updates[i];2922struct string_list_item *item =2923string_list_append(&affected_refnames, update->refname);29242925/*2926 * We store a pointer to update in item->util, but at2927 * the moment we never use the value of this field2928 * except to check whether it is non-NULL.2929 */2930 item->util = update;2931}2932string_list_sort(&affected_refnames);2933if(ref_update_reject_duplicates(&affected_refnames, err)) {2934 ret = TRANSACTION_GENERIC_ERROR;2935goto cleanup;2936}29372938/*2939 * Special hack: If a branch is updated directly and HEAD2940 * points to it (may happen on the remote side of a push2941 * for example) then logically the HEAD reflog should be2942 * updated too.2943 *2944 * A generic solution would require reverse symref lookups,2945 * but finding all symrefs pointing to a given branch would be2946 * rather costly for this rare event (the direct update of a2947 * branch) to be worth it. So let's cheat and check with HEAD2948 * only, which should cover 99% of all usage scenarios (even2949 * 100% of the default ones).2950 *2951 * So if HEAD is a symbolic reference, then record the name of2952 * the reference that it points to. If we see an update of2953 * head_ref within the transaction, then split_head_update()2954 * arranges for the reflog of HEAD to be updated, too.2955 */2956 head_ref =refs_resolve_refdup(ref_store,"HEAD",2957 RESOLVE_REF_NO_RECURSE,2958 head_oid.hash, &head_type);29592960if(head_ref && !(head_type & REF_ISSYMREF)) {2961free(head_ref);2962 head_ref = NULL;2963}29642965/*2966 * Acquire all locks, verify old values if provided, check2967 * that new values are valid, and write new values to the2968 * lockfiles, ready to be activated. Only keep one lockfile2969 * open at a time to avoid running out of file descriptors.2970 * Note that lock_ref_for_update() might append more updates2971 * to the transaction.2972 */2973for(i =0; i < transaction->nr; i++) {2974struct ref_update *update = transaction->updates[i];29752976 ret =lock_ref_for_update(refs, update, transaction,2977 head_ref, &affected_refnames, err);2978if(ret)2979break;2980}29812982cleanup:2983free(head_ref);2984string_list_clear(&affected_refnames,0);29852986if(ret)2987files_transaction_cleanup(transaction);2988else2989 transaction->state = REF_TRANSACTION_PREPARED;29902991return ret;2992}29932994static intfiles_transaction_finish(struct ref_store *ref_store,2995struct ref_transaction *transaction,2996struct strbuf *err)2997{2998struct files_ref_store *refs =2999files_downcast(ref_store,0,"ref_transaction_finish");3000size_t i;3001int ret =0;3002struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3003struct string_list_item *ref_to_delete;3004struct strbuf sb = STRBUF_INIT;30053006assert(err);30073008if(!transaction->nr) {3009 transaction->state = REF_TRANSACTION_CLOSED;3010return0;3011}30123013/* Perform updates first so live commits remain referenced */3014for(i =0; i < transaction->nr; i++) {3015struct ref_update *update = transaction->updates[i];3016struct ref_lock *lock = update->backend_data;30173018if(update->flags & REF_NEEDS_COMMIT ||3019 update->flags & REF_LOG_ONLY) {3020if(files_log_ref_write(refs,3021 lock->ref_name,3022&lock->old_oid,3023&update->new_oid,3024 update->msg, update->flags,3025 err)) {3026char*old_msg =strbuf_detach(err, NULL);30273028strbuf_addf(err,"cannot update the ref '%s':%s",3029 lock->ref_name, old_msg);3030free(old_msg);3031unlock_ref(lock);3032 update->backend_data = NULL;3033 ret = TRANSACTION_GENERIC_ERROR;3034goto cleanup;3035}3036}3037if(update->flags & REF_NEEDS_COMMIT) {3038clear_loose_ref_cache(refs);3039if(commit_ref(lock)) {3040strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3041unlock_ref(lock);3042 update->backend_data = NULL;3043 ret = TRANSACTION_GENERIC_ERROR;3044goto cleanup;3045}3046}3047}3048/* Perform deletes now that updates are safely completed */3049for(i =0; i < transaction->nr; i++) {3050struct ref_update *update = transaction->updates[i];3051struct ref_lock *lock = update->backend_data;30523053if(update->flags & REF_DELETING &&3054!(update->flags & REF_LOG_ONLY)) {3055if(!(update->type & REF_ISPACKED) ||3056 update->type & REF_ISSYMREF) {3057/* It is a loose reference. */3058strbuf_reset(&sb);3059files_ref_path(refs, &sb, lock->ref_name);3060if(unlink_or_msg(sb.buf, err)) {3061 ret = TRANSACTION_GENERIC_ERROR;3062goto cleanup;3063}3064 update->flags |= REF_DELETED_LOOSE;3065}30663067if(!(update->flags & REF_ISPRUNING))3068string_list_append(&refs_to_delete,3069 lock->ref_name);3070}3071}30723073if(repack_without_refs(refs, &refs_to_delete, err)) {3074 ret = TRANSACTION_GENERIC_ERROR;3075goto cleanup;3076}30773078/* Delete the reflogs of any references that were deleted: */3079for_each_string_list_item(ref_to_delete, &refs_to_delete) {3080strbuf_reset(&sb);3081files_reflog_path(refs, &sb, ref_to_delete->string);3082if(!unlink_or_warn(sb.buf))3083try_remove_empty_parents(refs, ref_to_delete->string,3084 REMOVE_EMPTY_PARENTS_REFLOG);3085}30863087clear_loose_ref_cache(refs);30883089cleanup:3090files_transaction_cleanup(transaction);30913092for(i =0; i < transaction->nr; i++) {3093struct ref_update *update = transaction->updates[i];30943095if(update->flags & REF_DELETED_LOOSE) {3096/*3097 * The loose reference was deleted. Delete any3098 * empty parent directories. (Note that this3099 * can only work because we have already3100 * removed the lockfile.)3101 */3102try_remove_empty_parents(refs, update->refname,3103 REMOVE_EMPTY_PARENTS_REF);3104}3105}31063107strbuf_release(&sb);3108string_list_clear(&refs_to_delete,0);3109return ret;3110}31113112static intfiles_transaction_abort(struct ref_store *ref_store,3113struct ref_transaction *transaction,3114struct strbuf *err)3115{3116files_transaction_cleanup(transaction);3117return0;3118}31193120static intref_present(const char*refname,3121const struct object_id *oid,int flags,void*cb_data)3122{3123struct string_list *affected_refnames = cb_data;31243125returnstring_list_has_string(affected_refnames, refname);3126}31273128static intfiles_initial_transaction_commit(struct ref_store *ref_store,3129struct ref_transaction *transaction,3130struct strbuf *err)3131{3132struct files_ref_store *refs =3133files_downcast(ref_store, REF_STORE_WRITE,3134"initial_ref_transaction_commit");3135size_t i;3136int ret =0;3137struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31383139assert(err);31403141if(transaction->state != REF_TRANSACTION_OPEN)3142die("BUG: commit called for transaction that is not open");31433144/* Fail if a refname appears more than once in the transaction: */3145for(i =0; i < transaction->nr; i++)3146string_list_append(&affected_refnames,3147 transaction->updates[i]->refname);3148string_list_sort(&affected_refnames);3149if(ref_update_reject_duplicates(&affected_refnames, err)) {3150 ret = TRANSACTION_GENERIC_ERROR;3151goto cleanup;3152}31533154/*3155 * It's really undefined to call this function in an active3156 * repository or when there are existing references: we are3157 * only locking and changing packed-refs, so (1) any3158 * simultaneous processes might try to change a reference at3159 * the same time we do, and (2) any existing loose versions of3160 * the references that we are setting would have precedence3161 * over our values. But some remote helpers create the remote3162 * "HEAD" and "master" branches before calling this function,3163 * so here we really only check that none of the references3164 * that we are creating already exists.3165 */3166if(refs_for_each_rawref(&refs->base, ref_present,3167&affected_refnames))3168die("BUG: initial ref transaction called with existing refs");31693170for(i =0; i < transaction->nr; i++) {3171struct ref_update *update = transaction->updates[i];31723173if((update->flags & REF_HAVE_OLD) &&3174!is_null_oid(&update->old_oid))3175die("BUG: initial ref transaction with old_sha1 set");3176if(refs_verify_refname_available(&refs->base, update->refname,3177&affected_refnames, NULL,3178 err)) {3179 ret = TRANSACTION_NAME_CONFLICT;3180goto cleanup;3181}3182}31833184if(lock_packed_refs(refs,0)) {3185strbuf_addf(err,"unable to lock packed-refs file:%s",3186strerror(errno));3187 ret = TRANSACTION_GENERIC_ERROR;3188goto cleanup;3189}31903191for(i =0; i < transaction->nr; i++) {3192struct ref_update *update = transaction->updates[i];31933194if((update->flags & REF_HAVE_NEW) &&3195!is_null_oid(&update->new_oid))3196add_packed_ref(refs, update->refname,3197&update->new_oid);3198}31993200if(commit_packed_refs(refs)) {3201strbuf_addf(err,"unable to commit packed-refs file:%s",3202strerror(errno));3203 ret = TRANSACTION_GENERIC_ERROR;3204goto cleanup;3205}32063207cleanup:3208 transaction->state = REF_TRANSACTION_CLOSED;3209string_list_clear(&affected_refnames,0);3210return ret;3211}32123213struct expire_reflog_cb {3214unsigned int flags;3215 reflog_expiry_should_prune_fn *should_prune_fn;3216void*policy_cb;3217FILE*newlog;3218struct object_id last_kept_oid;3219};32203221static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3222const char*email, timestamp_t timestamp,int tz,3223const char*message,void*cb_data)3224{3225struct expire_reflog_cb *cb = cb_data;3226struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32273228if(cb->flags & EXPIRE_REFLOGS_REWRITE)3229 ooid = &cb->last_kept_oid;32303231if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3232 message, policy_cb)) {3233if(!cb->newlog)3234printf("would prune%s", message);3235else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3236printf("prune%s", message);3237}else{3238if(cb->newlog) {3239fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3240oid_to_hex(ooid),oid_to_hex(noid),3241 email, timestamp, tz, message);3242oidcpy(&cb->last_kept_oid, noid);3243}3244if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3245printf("keep%s", message);3246}3247return0;3248}32493250static intfiles_reflog_expire(struct ref_store *ref_store,3251const char*refname,const unsigned char*sha1,3252unsigned int flags,3253 reflog_expiry_prepare_fn prepare_fn,3254 reflog_expiry_should_prune_fn should_prune_fn,3255 reflog_expiry_cleanup_fn cleanup_fn,3256void*policy_cb_data)3257{3258struct files_ref_store *refs =3259files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3260static struct lock_file reflog_lock;3261struct expire_reflog_cb cb;3262struct ref_lock *lock;3263struct strbuf log_file_sb = STRBUF_INIT;3264char*log_file;3265int status =0;3266int type;3267struct strbuf err = STRBUF_INIT;3268struct object_id oid;32693270memset(&cb,0,sizeof(cb));3271 cb.flags = flags;3272 cb.policy_cb = policy_cb_data;3273 cb.should_prune_fn = should_prune_fn;32743275/*3276 * The reflog file is locked by holding the lock on the3277 * reference itself, plus we might need to update the3278 * reference if --updateref was specified:3279 */3280 lock =lock_ref_sha1_basic(refs, refname, sha1,3281 NULL, NULL, REF_NODEREF,3282&type, &err);3283if(!lock) {3284error("cannot lock ref '%s':%s", refname, err.buf);3285strbuf_release(&err);3286return-1;3287}3288if(!refs_reflog_exists(ref_store, refname)) {3289unlock_ref(lock);3290return0;3291}32923293files_reflog_path(refs, &log_file_sb, refname);3294 log_file =strbuf_detach(&log_file_sb, NULL);3295if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3296/*3297 * Even though holding $GIT_DIR/logs/$reflog.lock has3298 * no locking implications, we use the lock_file3299 * machinery here anyway because it does a lot of the3300 * work we need, including cleaning up if the program3301 * exits unexpectedly.3302 */3303if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3304struct strbuf err = STRBUF_INIT;3305unable_to_lock_message(log_file, errno, &err);3306error("%s", err.buf);3307strbuf_release(&err);3308goto failure;3309}3310 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3311if(!cb.newlog) {3312error("cannot fdopen%s(%s)",3313get_lock_file_path(&reflog_lock),strerror(errno));3314goto failure;3315}3316}33173318hashcpy(oid.hash, sha1);33193320(*prepare_fn)(refname, &oid, cb.policy_cb);3321refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3322(*cleanup_fn)(cb.policy_cb);33233324if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3325/*3326 * It doesn't make sense to adjust a reference pointed3327 * to by a symbolic ref based on expiring entries in3328 * the symbolic reference's reflog. Nor can we update3329 * a reference if there are no remaining reflog3330 * entries.3331 */3332int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3333!(type & REF_ISSYMREF) &&3334!is_null_oid(&cb.last_kept_oid);33353336if(close_lock_file(&reflog_lock)) {3337 status |=error("couldn't write%s:%s", log_file,3338strerror(errno));3339}else if(update &&3340(write_in_full(get_lock_file_fd(lock->lk),3341oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3342write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3343close_ref(lock) <0)) {3344 status |=error("couldn't write%s",3345get_lock_file_path(lock->lk));3346rollback_lock_file(&reflog_lock);3347}else if(commit_lock_file(&reflog_lock)) {3348 status |=error("unable to write reflog '%s' (%s)",3349 log_file,strerror(errno));3350}else if(update &&commit_ref(lock)) {3351 status |=error("couldn't set%s", lock->ref_name);3352}3353}3354free(log_file);3355unlock_ref(lock);3356return status;33573358 failure:3359rollback_lock_file(&reflog_lock);3360free(log_file);3361unlock_ref(lock);3362return-1;3363}33643365static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3366{3367struct files_ref_store *refs =3368files_downcast(ref_store, REF_STORE_WRITE,"init_db");3369struct strbuf sb = STRBUF_INIT;33703371/*3372 * Create .git/refs/{heads,tags}3373 */3374files_ref_path(refs, &sb,"refs/heads");3375safe_create_dir(sb.buf,1);33763377strbuf_reset(&sb);3378files_ref_path(refs, &sb,"refs/tags");3379safe_create_dir(sb.buf,1);33803381strbuf_release(&sb);3382return0;3383}33843385struct ref_storage_be refs_be_files = {3386 NULL,3387"files",3388 files_ref_store_create,3389 files_init_db,3390 files_transaction_prepare,3391 files_transaction_finish,3392 files_transaction_abort,3393 files_initial_transaction_commit,33943395 files_pack_refs,3396 files_peel_ref,3397 files_create_symref,3398 files_delete_refs,3399 files_rename_ref,34003401 files_ref_iterator_begin,3402 files_read_raw_ref,34033404 files_reflog_iterator_begin,3405 files_for_each_reflog_ent,3406 files_for_each_reflog_ent_reverse,3407 files_reflog_exists,3408 files_create_reflog,3409 files_delete_reflog,3410 files_reflog_expire3411};