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,0); 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 * Get the packed_ref_cache for the specified files_ref_store, 374 * creating and populating it if it hasn't been read before or if the 375 * file has been changed (according to its `validity` field) since it 376 * was last read. On the other hand, if we hold the lock, then assume 377 * that the file hasn't been changed out from under us, so skip the 378 * extra `stat()` call in `stat_validity_check()`. 379 */ 380static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 381{ 382const char*packed_refs_file =files_packed_refs_path(refs); 383 384if(refs->packed && 385!is_lock_file_locked(&refs->packed_refs_lock) && 386!stat_validity_check(&refs->packed->validity, packed_refs_file)) 387clear_packed_ref_cache(refs); 388 389if(!refs->packed) 390 refs->packed =read_packed_refs(packed_refs_file); 391 392return refs->packed; 393} 394 395static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 396{ 397returnget_ref_dir(packed_ref_cache->cache->root); 398} 399 400static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 401{ 402returnget_packed_ref_dir(get_packed_ref_cache(refs)); 403} 404 405/* 406 * Add a reference to the in-memory packed reference cache. This may 407 * only be called while the packed-refs file is locked (see 408 * lock_packed_refs()). To actually write the packed-refs file, call 409 * commit_packed_refs(). 410 */ 411static voidadd_packed_ref(struct files_ref_store *refs, 412const char*refname,const struct object_id *oid) 413{ 414struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 415 416if(!is_lock_file_locked(&refs->packed_refs_lock)) 417die("BUG: packed refs not locked"); 418add_ref_entry(get_packed_ref_dir(packed_ref_cache), 419create_ref_entry(refname, oid, REF_ISPACKED,1)); 420} 421 422/* 423 * Read the loose references from the namespace dirname into dir 424 * (without recursing). dirname must end with '/'. dir must be the 425 * directory entry corresponding to dirname. 426 */ 427static voidloose_fill_ref_dir(struct ref_store *ref_store, 428struct ref_dir *dir,const char*dirname) 429{ 430struct files_ref_store *refs = 431files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 432DIR*d; 433struct dirent *de; 434int dirnamelen =strlen(dirname); 435struct strbuf refname; 436struct strbuf path = STRBUF_INIT; 437size_t path_baselen; 438 439files_ref_path(refs, &path, dirname); 440 path_baselen = path.len; 441 442 d =opendir(path.buf); 443if(!d) { 444strbuf_release(&path); 445return; 446} 447 448strbuf_init(&refname, dirnamelen +257); 449strbuf_add(&refname, dirname, dirnamelen); 450 451while((de =readdir(d)) != NULL) { 452struct object_id oid; 453struct stat st; 454int flag; 455 456if(de->d_name[0] =='.') 457continue; 458if(ends_with(de->d_name,".lock")) 459continue; 460strbuf_addstr(&refname, de->d_name); 461strbuf_addstr(&path, de->d_name); 462if(stat(path.buf, &st) <0) { 463;/* silently ignore */ 464}else if(S_ISDIR(st.st_mode)) { 465strbuf_addch(&refname,'/'); 466add_entry_to_dir(dir, 467create_dir_entry(dir->cache, refname.buf, 468 refname.len,1)); 469}else{ 470if(!refs_resolve_ref_unsafe(&refs->base, 471 refname.buf, 472 RESOLVE_REF_READING, 473 oid.hash, &flag)) { 474oidclr(&oid); 475 flag |= REF_ISBROKEN; 476}else if(is_null_oid(&oid)) { 477/* 478 * It is so astronomically unlikely 479 * that NULL_SHA1 is the SHA-1 of an 480 * actual object that we consider its 481 * appearance in a loose reference 482 * file to be repo corruption 483 * (probably due to a software bug). 484 */ 485 flag |= REF_ISBROKEN; 486} 487 488if(check_refname_format(refname.buf, 489 REFNAME_ALLOW_ONELEVEL)) { 490if(!refname_is_safe(refname.buf)) 491die("loose refname is dangerous:%s", refname.buf); 492oidclr(&oid); 493 flag |= REF_BAD_NAME | REF_ISBROKEN; 494} 495add_entry_to_dir(dir, 496create_ref_entry(refname.buf, &oid, flag,0)); 497} 498strbuf_setlen(&refname, dirnamelen); 499strbuf_setlen(&path, path_baselen); 500} 501strbuf_release(&refname); 502strbuf_release(&path); 503closedir(d); 504 505/* 506 * Manually add refs/bisect, which, being per-worktree, might 507 * not appear in the directory listing for refs/ in the main 508 * repo. 509 */ 510if(!strcmp(dirname,"refs/")) { 511int pos =search_ref_dir(dir,"refs/bisect/",12); 512 513if(pos <0) { 514struct ref_entry *child_entry =create_dir_entry( 515 dir->cache,"refs/bisect/",12,1); 516add_entry_to_dir(dir, child_entry); 517} 518} 519} 520 521static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 522{ 523if(!refs->loose) { 524/* 525 * Mark the top-level directory complete because we 526 * are about to read the only subdirectory that can 527 * hold references: 528 */ 529 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 530 531/* We're going to fill the top level ourselves: */ 532 refs->loose->root->flag &= ~REF_INCOMPLETE; 533 534/* 535 * Add an incomplete entry for "refs/" (to be filled 536 * lazily): 537 */ 538add_entry_to_dir(get_ref_dir(refs->loose->root), 539create_dir_entry(refs->loose,"refs/",5,1)); 540} 541return refs->loose; 542} 543 544/* 545 * Return the ref_entry for the given refname from the packed 546 * references. If it does not exist, return NULL. 547 */ 548static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 549const char*refname) 550{ 551returnfind_ref_entry(get_packed_refs(refs), refname); 552} 553 554/* 555 * A loose ref file doesn't exist; check for a packed ref. 556 */ 557static intresolve_packed_ref(struct files_ref_store *refs, 558const char*refname, 559unsigned char*sha1,unsigned int*flags) 560{ 561struct ref_entry *entry; 562 563/* 564 * The loose reference file does not exist; check for a packed 565 * reference. 566 */ 567 entry =get_packed_ref(refs, refname); 568if(entry) { 569hashcpy(sha1, entry->u.value.oid.hash); 570*flags |= REF_ISPACKED; 571return0; 572} 573/* refname is not a packed reference. */ 574return-1; 575} 576 577static intfiles_read_raw_ref(struct ref_store *ref_store, 578const char*refname,unsigned char*sha1, 579struct strbuf *referent,unsigned int*type) 580{ 581struct files_ref_store *refs = 582files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 583struct strbuf sb_contents = STRBUF_INIT; 584struct strbuf sb_path = STRBUF_INIT; 585const char*path; 586const char*buf; 587struct stat st; 588int fd; 589int ret = -1; 590int save_errno; 591int remaining_retries =3; 592 593*type =0; 594strbuf_reset(&sb_path); 595 596files_ref_path(refs, &sb_path, refname); 597 598 path = sb_path.buf; 599 600stat_ref: 601/* 602 * We might have to loop back here to avoid a race 603 * condition: first we lstat() the file, then we try 604 * to read it as a link or as a file. But if somebody 605 * changes the type of the file (file <-> directory 606 * <-> symlink) between the lstat() and reading, then 607 * we don't want to report that as an error but rather 608 * try again starting with the lstat(). 609 * 610 * We'll keep a count of the retries, though, just to avoid 611 * any confusing situation sending us into an infinite loop. 612 */ 613 614if(remaining_retries-- <=0) 615goto out; 616 617if(lstat(path, &st) <0) { 618if(errno != ENOENT) 619goto out; 620if(resolve_packed_ref(refs, refname, sha1, type)) { 621 errno = ENOENT; 622goto out; 623} 624 ret =0; 625goto out; 626} 627 628/* Follow "normalized" - ie "refs/.." symlinks by hand */ 629if(S_ISLNK(st.st_mode)) { 630strbuf_reset(&sb_contents); 631if(strbuf_readlink(&sb_contents, path,0) <0) { 632if(errno == ENOENT || errno == EINVAL) 633/* inconsistent with lstat; retry */ 634goto stat_ref; 635else 636goto out; 637} 638if(starts_with(sb_contents.buf,"refs/") && 639!check_refname_format(sb_contents.buf,0)) { 640strbuf_swap(&sb_contents, referent); 641*type |= REF_ISSYMREF; 642 ret =0; 643goto out; 644} 645/* 646 * It doesn't look like a refname; fall through to just 647 * treating it like a non-symlink, and reading whatever it 648 * points to. 649 */ 650} 651 652/* Is it a directory? */ 653if(S_ISDIR(st.st_mode)) { 654/* 655 * Even though there is a directory where the loose 656 * ref is supposed to be, there could still be a 657 * packed ref: 658 */ 659if(resolve_packed_ref(refs, refname, sha1, type)) { 660 errno = EISDIR; 661goto out; 662} 663 ret =0; 664goto out; 665} 666 667/* 668 * Anything else, just open it and try to use it as 669 * a ref 670 */ 671 fd =open(path, O_RDONLY); 672if(fd <0) { 673if(errno == ENOENT && !S_ISLNK(st.st_mode)) 674/* inconsistent with lstat; retry */ 675goto stat_ref; 676else 677goto out; 678} 679strbuf_reset(&sb_contents); 680if(strbuf_read(&sb_contents, fd,256) <0) { 681int save_errno = errno; 682close(fd); 683 errno = save_errno; 684goto out; 685} 686close(fd); 687strbuf_rtrim(&sb_contents); 688 buf = sb_contents.buf; 689if(starts_with(buf,"ref:")) { 690 buf +=4; 691while(isspace(*buf)) 692 buf++; 693 694strbuf_reset(referent); 695strbuf_addstr(referent, buf); 696*type |= REF_ISSYMREF; 697 ret =0; 698goto out; 699} 700 701/* 702 * Please note that FETCH_HEAD has additional 703 * data after the sha. 704 */ 705if(get_sha1_hex(buf, sha1) || 706(buf[40] !='\0'&& !isspace(buf[40]))) { 707*type |= REF_ISBROKEN; 708 errno = EINVAL; 709goto out; 710} 711 712 ret =0; 713 714out: 715 save_errno = errno; 716strbuf_release(&sb_path); 717strbuf_release(&sb_contents); 718 errno = save_errno; 719return ret; 720} 721 722static voidunlock_ref(struct ref_lock *lock) 723{ 724/* Do not free lock->lk -- atexit() still looks at them */ 725if(lock->lk) 726rollback_lock_file(lock->lk); 727free(lock->ref_name); 728free(lock); 729} 730 731/* 732 * Lock refname, without following symrefs, and set *lock_p to point 733 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 734 * and type similarly to read_raw_ref(). 735 * 736 * The caller must verify that refname is a "safe" reference name (in 737 * the sense of refname_is_safe()) before calling this function. 738 * 739 * If the reference doesn't already exist, verify that refname doesn't 740 * have a D/F conflict with any existing references. extras and skip 741 * are passed to refs_verify_refname_available() for this check. 742 * 743 * If mustexist is not set and the reference is not found or is 744 * broken, lock the reference anyway but clear sha1. 745 * 746 * Return 0 on success. On failure, write an error message to err and 747 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 748 * 749 * Implementation note: This function is basically 750 * 751 * lock reference 752 * read_raw_ref() 753 * 754 * but it includes a lot more code to 755 * - Deal with possible races with other processes 756 * - Avoid calling refs_verify_refname_available() when it can be 757 * avoided, namely if we were successfully able to read the ref 758 * - Generate informative error messages in the case of failure 759 */ 760static intlock_raw_ref(struct files_ref_store *refs, 761const char*refname,int mustexist, 762const struct string_list *extras, 763const struct string_list *skip, 764struct ref_lock **lock_p, 765struct strbuf *referent, 766unsigned int*type, 767struct strbuf *err) 768{ 769struct ref_lock *lock; 770struct strbuf ref_file = STRBUF_INIT; 771int attempts_remaining =3; 772int ret = TRANSACTION_GENERIC_ERROR; 773 774assert(err); 775files_assert_main_repository(refs,"lock_raw_ref"); 776 777*type =0; 778 779/* First lock the file so it can't change out from under us. */ 780 781*lock_p = lock =xcalloc(1,sizeof(*lock)); 782 783 lock->ref_name =xstrdup(refname); 784files_ref_path(refs, &ref_file, refname); 785 786retry: 787switch(safe_create_leading_directories(ref_file.buf)) { 788case SCLD_OK: 789break;/* success */ 790case SCLD_EXISTS: 791/* 792 * Suppose refname is "refs/foo/bar". We just failed 793 * to create the containing directory, "refs/foo", 794 * because there was a non-directory in the way. This 795 * indicates a D/F conflict, probably because of 796 * another reference such as "refs/foo". There is no 797 * reason to expect this error to be transitory. 798 */ 799if(refs_verify_refname_available(&refs->base, refname, 800 extras, skip, err)) { 801if(mustexist) { 802/* 803 * To the user the relevant error is 804 * that the "mustexist" reference is 805 * missing: 806 */ 807strbuf_reset(err); 808strbuf_addf(err,"unable to resolve reference '%s'", 809 refname); 810}else{ 811/* 812 * The error message set by 813 * refs_verify_refname_available() is 814 * OK. 815 */ 816 ret = TRANSACTION_NAME_CONFLICT; 817} 818}else{ 819/* 820 * The file that is in the way isn't a loose 821 * reference. Report it as a low-level 822 * failure. 823 */ 824strbuf_addf(err,"unable to create lock file%s.lock; " 825"non-directory in the way", 826 ref_file.buf); 827} 828goto error_return; 829case SCLD_VANISHED: 830/* Maybe another process was tidying up. Try again. */ 831if(--attempts_remaining >0) 832goto retry; 833/* fall through */ 834default: 835strbuf_addf(err,"unable to create directory for%s", 836 ref_file.buf); 837goto error_return; 838} 839 840if(!lock->lk) 841 lock->lk =xcalloc(1,sizeof(struct lock_file)); 842 843if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 844if(errno == ENOENT && --attempts_remaining >0) { 845/* 846 * Maybe somebody just deleted one of the 847 * directories leading to ref_file. Try 848 * again: 849 */ 850goto retry; 851}else{ 852unable_to_lock_message(ref_file.buf, errno, err); 853goto error_return; 854} 855} 856 857/* 858 * Now we hold the lock and can read the reference without 859 * fear that its value will change. 860 */ 861 862if(files_read_raw_ref(&refs->base, refname, 863 lock->old_oid.hash, referent, type)) { 864if(errno == ENOENT) { 865if(mustexist) { 866/* Garden variety missing reference. */ 867strbuf_addf(err,"unable to resolve reference '%s'", 868 refname); 869goto error_return; 870}else{ 871/* 872 * Reference is missing, but that's OK. We 873 * know that there is not a conflict with 874 * another loose reference because 875 * (supposing that we are trying to lock 876 * reference "refs/foo/bar"): 877 * 878 * - We were successfully able to create 879 * the lockfile refs/foo/bar.lock, so we 880 * know there cannot be a loose reference 881 * named "refs/foo". 882 * 883 * - We got ENOENT and not EISDIR, so we 884 * know that there cannot be a loose 885 * reference named "refs/foo/bar/baz". 886 */ 887} 888}else if(errno == EISDIR) { 889/* 890 * There is a directory in the way. It might have 891 * contained references that have been deleted. If 892 * we don't require that the reference already 893 * exists, try to remove the directory so that it 894 * doesn't cause trouble when we want to rename the 895 * lockfile into place later. 896 */ 897if(mustexist) { 898/* Garden variety missing reference. */ 899strbuf_addf(err,"unable to resolve reference '%s'", 900 refname); 901goto error_return; 902}else if(remove_dir_recursively(&ref_file, 903 REMOVE_DIR_EMPTY_ONLY)) { 904if(refs_verify_refname_available( 905&refs->base, refname, 906 extras, skip, err)) { 907/* 908 * The error message set by 909 * verify_refname_available() is OK. 910 */ 911 ret = TRANSACTION_NAME_CONFLICT; 912goto error_return; 913}else{ 914/* 915 * We can't delete the directory, 916 * but we also don't know of any 917 * references that it should 918 * contain. 919 */ 920strbuf_addf(err,"there is a non-empty directory '%s' " 921"blocking reference '%s'", 922 ref_file.buf, refname); 923goto error_return; 924} 925} 926}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 927strbuf_addf(err,"unable to resolve reference '%s': " 928"reference broken", refname); 929goto error_return; 930}else{ 931strbuf_addf(err,"unable to resolve reference '%s':%s", 932 refname,strerror(errno)); 933goto error_return; 934} 935 936/* 937 * If the ref did not exist and we are creating it, 938 * make sure there is no existing ref that conflicts 939 * with refname: 940 */ 941if(refs_verify_refname_available( 942&refs->base, refname, 943 extras, skip, err)) 944goto error_return; 945} 946 947 ret =0; 948goto out; 949 950error_return: 951unlock_ref(lock); 952*lock_p = NULL; 953 954out: 955strbuf_release(&ref_file); 956return ret; 957} 958 959static intfiles_peel_ref(struct ref_store *ref_store, 960const char*refname,unsigned char*sha1) 961{ 962struct files_ref_store *refs = 963files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 964"peel_ref"); 965int flag; 966unsigned char base[20]; 967 968if(current_ref_iter && current_ref_iter->refname == refname) { 969struct object_id peeled; 970 971if(ref_iterator_peel(current_ref_iter, &peeled)) 972return-1; 973hashcpy(sha1, peeled.hash); 974return0; 975} 976 977if(refs_read_ref_full(ref_store, refname, 978 RESOLVE_REF_READING, base, &flag)) 979return-1; 980 981/* 982 * If the reference is packed, read its ref_entry from the 983 * cache in the hope that we already know its peeled value. 984 * We only try this optimization on packed references because 985 * (a) forcing the filling of the loose reference cache could 986 * be expensive and (b) loose references anyway usually do not 987 * have REF_KNOWS_PEELED. 988 */ 989if(flag & REF_ISPACKED) { 990struct ref_entry *r =get_packed_ref(refs, refname); 991if(r) { 992if(peel_entry(r,0)) 993return-1; 994hashcpy(sha1, r->u.value.peeled.hash); 995return0; 996} 997} 998 999returnpeel_object(base, sha1);1000}10011002struct files_ref_iterator {1003struct ref_iterator base;10041005struct packed_ref_cache *packed_ref_cache;1006struct ref_iterator *iter0;1007unsigned int flags;1008};10091010static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1011{1012struct files_ref_iterator *iter =1013(struct files_ref_iterator *)ref_iterator;1014int ok;10151016while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1017if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1018ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1019continue;10201021if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1022!ref_resolves_to_object(iter->iter0->refname,1023 iter->iter0->oid,1024 iter->iter0->flags))1025continue;10261027 iter->base.refname = iter->iter0->refname;1028 iter->base.oid = iter->iter0->oid;1029 iter->base.flags = iter->iter0->flags;1030return ITER_OK;1031}10321033 iter->iter0 = NULL;1034if(ref_iterator_abort(ref_iterator) != ITER_DONE)1035 ok = ITER_ERROR;10361037return ok;1038}10391040static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1041struct object_id *peeled)1042{1043struct files_ref_iterator *iter =1044(struct files_ref_iterator *)ref_iterator;10451046returnref_iterator_peel(iter->iter0, peeled);1047}10481049static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1050{1051struct files_ref_iterator *iter =1052(struct files_ref_iterator *)ref_iterator;1053int ok = ITER_DONE;10541055if(iter->iter0)1056 ok =ref_iterator_abort(iter->iter0);10571058release_packed_ref_cache(iter->packed_ref_cache);1059base_ref_iterator_free(ref_iterator);1060return ok;1061}10621063static struct ref_iterator_vtable files_ref_iterator_vtable = {1064 files_ref_iterator_advance,1065 files_ref_iterator_peel,1066 files_ref_iterator_abort1067};10681069static struct ref_iterator *files_ref_iterator_begin(1070struct ref_store *ref_store,1071const char*prefix,unsigned int flags)1072{1073struct files_ref_store *refs;1074struct ref_iterator *loose_iter, *packed_iter;1075struct files_ref_iterator *iter;1076struct ref_iterator *ref_iterator;10771078if(ref_paranoia <0)1079 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1080if(ref_paranoia)1081 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10821083 refs =files_downcast(ref_store,1084 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1085"ref_iterator_begin");10861087 iter =xcalloc(1,sizeof(*iter));1088 ref_iterator = &iter->base;1089base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10901091/*1092 * We must make sure that all loose refs are read before1093 * accessing the packed-refs file; this avoids a race1094 * condition if loose refs are migrated to the packed-refs1095 * file by a simultaneous process, but our in-memory view is1096 * from before the migration. We ensure this as follows:1097 * First, we call start the loose refs iteration with its1098 * `prime_ref` argument set to true. This causes the loose1099 * references in the subtree to be pre-read into the cache.1100 * (If they've already been read, that's OK; we only need to1101 * guarantee that they're read before the packed refs, not1102 * *how much* before.) After that, we call1103 * get_packed_ref_cache(), which internally checks whether the1104 * packed-ref cache is up to date with what is on disk, and1105 * re-reads it if not.1106 */11071108 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1109 prefix,1);11101111 iter->packed_ref_cache =get_packed_ref_cache(refs);1112acquire_packed_ref_cache(iter->packed_ref_cache);1113 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1114 prefix,0);11151116 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1117 iter->flags = flags;11181119return ref_iterator;1120}11211122/*1123 * Verify that the reference locked by lock has the value old_sha1.1124 * Fail if the reference doesn't exist and mustexist is set. Return 01125 * on success. On error, write an error message to err, set errno, and1126 * return a negative value.1127 */1128static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1129const unsigned char*old_sha1,int mustexist,1130struct strbuf *err)1131{1132assert(err);11331134if(refs_read_ref_full(ref_store, lock->ref_name,1135 mustexist ? RESOLVE_REF_READING :0,1136 lock->old_oid.hash, NULL)) {1137if(old_sha1) {1138int save_errno = errno;1139strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1140 errno = save_errno;1141return-1;1142}else{1143oidclr(&lock->old_oid);1144return0;1145}1146}1147if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1148strbuf_addf(err,"ref '%s' is at%sbut expected%s",1149 lock->ref_name,1150oid_to_hex(&lock->old_oid),1151sha1_to_hex(old_sha1));1152 errno = EBUSY;1153return-1;1154}1155return0;1156}11571158static intremove_empty_directories(struct strbuf *path)1159{1160/*1161 * we want to create a file but there is a directory there;1162 * if that is an empty directory (or a directory that contains1163 * only empty directories), remove them.1164 */1165returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1166}11671168static intcreate_reflock(const char*path,void*cb)1169{1170struct lock_file *lk = cb;11711172returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1173}11741175/*1176 * Locks a ref returning the lock on success and NULL on failure.1177 * On failure errno is set to something meaningful.1178 */1179static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1180const char*refname,1181const unsigned char*old_sha1,1182const struct string_list *extras,1183const struct string_list *skip,1184unsigned int flags,int*type,1185struct strbuf *err)1186{1187struct strbuf ref_file = STRBUF_INIT;1188struct ref_lock *lock;1189int last_errno =0;1190int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1191int resolve_flags = RESOLVE_REF_NO_RECURSE;1192int resolved;11931194files_assert_main_repository(refs,"lock_ref_sha1_basic");1195assert(err);11961197 lock =xcalloc(1,sizeof(struct ref_lock));11981199if(mustexist)1200 resolve_flags |= RESOLVE_REF_READING;1201if(flags & REF_DELETING)1202 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12031204files_ref_path(refs, &ref_file, refname);1205 resolved = !!refs_resolve_ref_unsafe(&refs->base,1206 refname, resolve_flags,1207 lock->old_oid.hash, type);1208if(!resolved && errno == EISDIR) {1209/*1210 * we are trying to lock foo but we used to1211 * have foo/bar which now does not exist;1212 * it is normal for the empty directory 'foo'1213 * to remain.1214 */1215if(remove_empty_directories(&ref_file)) {1216 last_errno = errno;1217if(!refs_verify_refname_available(1218&refs->base,1219 refname, extras, skip, err))1220strbuf_addf(err,"there are still refs under '%s'",1221 refname);1222goto error_return;1223}1224 resolved = !!refs_resolve_ref_unsafe(&refs->base,1225 refname, resolve_flags,1226 lock->old_oid.hash, type);1227}1228if(!resolved) {1229 last_errno = errno;1230if(last_errno != ENOTDIR ||1231!refs_verify_refname_available(&refs->base, refname,1232 extras, skip, err))1233strbuf_addf(err,"unable to resolve reference '%s':%s",1234 refname,strerror(last_errno));12351236goto error_return;1237}12381239/*1240 * If the ref did not exist and we are creating it, make sure1241 * there is no existing packed ref whose name begins with our1242 * refname, nor a packed ref whose name is a proper prefix of1243 * our refname.1244 */1245if(is_null_oid(&lock->old_oid) &&1246refs_verify_refname_available(&refs->base, refname,1247 extras, skip, err)) {1248 last_errno = ENOTDIR;1249goto error_return;1250}12511252 lock->lk =xcalloc(1,sizeof(struct lock_file));12531254 lock->ref_name =xstrdup(refname);12551256if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1257 last_errno = errno;1258unable_to_lock_message(ref_file.buf, errno, err);1259goto error_return;1260}12611262if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1263 last_errno = errno;1264goto error_return;1265}1266goto out;12671268 error_return:1269unlock_ref(lock);1270 lock = NULL;12711272 out:1273strbuf_release(&ref_file);1274 errno = last_errno;1275return lock;1276}12771278/*1279 * Write an entry to the packed-refs file for the specified refname.1280 * If peeled is non-NULL, write it as the entry's peeled value.1281 */1282static voidwrite_packed_entry(FILE*fh,const char*refname,1283const unsigned char*sha1,1284const unsigned char*peeled)1285{1286fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1287if(peeled)1288fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1289}12901291/*1292 * Lock the packed-refs file for writing. Flags is passed to1293 * hold_lock_file_for_update(). Return 0 on success. On errors, set1294 * errno appropriately and return a nonzero value.1295 */1296static intlock_packed_refs(struct files_ref_store *refs,int flags)1297{1298static int timeout_configured =0;1299static int timeout_value =1000;1300struct packed_ref_cache *packed_ref_cache;13011302files_assert_main_repository(refs,"lock_packed_refs");13031304if(!timeout_configured) {1305git_config_get_int("core.packedrefstimeout", &timeout_value);1306 timeout_configured =1;1307}13081309if(hold_lock_file_for_update_timeout(1310&refs->packed_refs_lock,files_packed_refs_path(refs),1311 flags, timeout_value) <0)1312return-1;1313/*1314 * Get the current packed-refs while holding the lock. It is1315 * important that we call `get_packed_ref_cache()` before1316 * setting `packed_ref_cache->lock`, because otherwise the1317 * former will see that the file is locked and assume that the1318 * cache can't be stale.1319 */1320 packed_ref_cache =get_packed_ref_cache(refs);1321/* Increment the reference count to prevent it from being freed: */1322acquire_packed_ref_cache(packed_ref_cache);1323return0;1324}13251326/*1327 * Write the current version of the packed refs cache from memory to1328 * disk. The packed-refs file must already be locked for writing (see1329 * lock_packed_refs()). Return zero on success. On errors, set errno1330 * and return a nonzero value1331 */1332static intcommit_packed_refs(struct files_ref_store *refs)1333{1334struct packed_ref_cache *packed_ref_cache =1335get_packed_ref_cache(refs);1336int ok, error =0;1337int save_errno =0;1338FILE*out;1339struct ref_iterator *iter;13401341files_assert_main_repository(refs,"commit_packed_refs");13421343if(!is_lock_file_locked(&refs->packed_refs_lock))1344die("BUG: packed-refs not locked");13451346 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1347if(!out)1348die_errno("unable to fdopen packed-refs descriptor");13491350fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13511352 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1353while((ok =ref_iterator_advance(iter)) == ITER_OK) {1354struct object_id peeled;1355int peel_error =ref_iterator_peel(iter, &peeled);13561357write_packed_entry(out, iter->refname, iter->oid->hash,1358 peel_error ? NULL : peeled.hash);1359}13601361if(ok != ITER_DONE)1362die("error while iterating over references");13631364if(commit_lock_file(&refs->packed_refs_lock)) {1365 save_errno = errno;1366 error = -1;1367}1368release_packed_ref_cache(packed_ref_cache);1369 errno = save_errno;1370return error;1371}13721373/*1374 * Rollback the lockfile for the packed-refs file, and discard the1375 * in-memory packed reference cache. (The packed-refs file will be1376 * read anew if it is needed again after this function is called.)1377 */1378static voidrollback_packed_refs(struct files_ref_store *refs)1379{1380struct packed_ref_cache *packed_ref_cache =1381get_packed_ref_cache(refs);13821383files_assert_main_repository(refs,"rollback_packed_refs");13841385if(!is_lock_file_locked(&refs->packed_refs_lock))1386die("BUG: packed-refs not locked");1387rollback_lock_file(&refs->packed_refs_lock);1388release_packed_ref_cache(packed_ref_cache);1389clear_packed_ref_cache(refs);1390}13911392struct ref_to_prune {1393struct ref_to_prune *next;1394unsigned char sha1[20];1395char name[FLEX_ARRAY];1396};13971398enum{1399 REMOVE_EMPTY_PARENTS_REF =0x01,1400 REMOVE_EMPTY_PARENTS_REFLOG =0x021401};14021403/*1404 * Remove empty parent directories associated with the specified1405 * reference and/or its reflog, but spare [logs/]refs/ and immediate1406 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1407 * REMOVE_EMPTY_PARENTS_REFLOG.1408 */1409static voidtry_remove_empty_parents(struct files_ref_store *refs,1410const char*refname,1411unsigned int flags)1412{1413struct strbuf buf = STRBUF_INIT;1414struct strbuf sb = STRBUF_INIT;1415char*p, *q;1416int i;14171418strbuf_addstr(&buf, refname);1419 p = buf.buf;1420for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1421while(*p && *p !='/')1422 p++;1423/* tolerate duplicate slashes; see check_refname_format() */1424while(*p =='/')1425 p++;1426}1427 q = buf.buf + buf.len;1428while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1429while(q > p && *q !='/')1430 q--;1431while(q > p && *(q-1) =='/')1432 q--;1433if(q == p)1434break;1435strbuf_setlen(&buf, q - buf.buf);14361437strbuf_reset(&sb);1438files_ref_path(refs, &sb, buf.buf);1439if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1440 flags &= ~REMOVE_EMPTY_PARENTS_REF;14411442strbuf_reset(&sb);1443files_reflog_path(refs, &sb, buf.buf);1444if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1445 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1446}1447strbuf_release(&buf);1448strbuf_release(&sb);1449}14501451/* make sure nobody touched the ref, and unlink */1452static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1453{1454struct ref_transaction *transaction;1455struct strbuf err = STRBUF_INIT;14561457if(check_refname_format(r->name,0))1458return;14591460 transaction =ref_store_transaction_begin(&refs->base, &err);1461if(!transaction ||1462ref_transaction_delete(transaction, r->name, r->sha1,1463 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1464ref_transaction_commit(transaction, &err)) {1465ref_transaction_free(transaction);1466error("%s", err.buf);1467strbuf_release(&err);1468return;1469}1470ref_transaction_free(transaction);1471strbuf_release(&err);1472}14731474static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1475{1476while(r) {1477prune_ref(refs, r);1478 r = r->next;1479}1480}14811482/*1483 * Return true if the specified reference should be packed.1484 */1485static intshould_pack_ref(const char*refname,1486const struct object_id *oid,unsigned int ref_flags,1487unsigned int pack_flags)1488{1489/* Do not pack per-worktree refs: */1490if(ref_type(refname) != REF_TYPE_NORMAL)1491return0;14921493/* Do not pack non-tags unless PACK_REFS_ALL is set: */1494if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1495return0;14961497/* Do not pack symbolic refs: */1498if(ref_flags & REF_ISSYMREF)1499return0;15001501/* Do not pack broken refs: */1502if(!ref_resolves_to_object(refname, oid, ref_flags))1503return0;15041505return1;1506}15071508static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1509{1510struct files_ref_store *refs =1511files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1512"pack_refs");1513struct ref_iterator *iter;1514struct ref_dir *packed_refs;1515int ok;1516struct ref_to_prune *refs_to_prune = NULL;15171518lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1519 packed_refs =get_packed_refs(refs);15201521 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1522while((ok =ref_iterator_advance(iter)) == ITER_OK) {1523/*1524 * If the loose reference can be packed, add an entry1525 * in the packed ref cache. If the reference should be1526 * pruned, also add it to refs_to_prune.1527 */1528struct ref_entry *packed_entry;15291530if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1531 flags))1532continue;15331534/*1535 * Create an entry in the packed-refs cache equivalent1536 * to the one from the loose ref cache, except that1537 * we don't copy the peeled status, because we want it1538 * to be re-peeled.1539 */1540 packed_entry =find_ref_entry(packed_refs, iter->refname);1541if(packed_entry) {1542/* Overwrite existing packed entry with info from loose entry */1543 packed_entry->flag = REF_ISPACKED;1544oidcpy(&packed_entry->u.value.oid, iter->oid);1545}else{1546 packed_entry =create_ref_entry(iter->refname, iter->oid,1547 REF_ISPACKED,0);1548add_ref_entry(packed_refs, packed_entry);1549}1550oidclr(&packed_entry->u.value.peeled);15511552/* Schedule the loose reference for pruning if requested. */1553if((flags & PACK_REFS_PRUNE)) {1554struct ref_to_prune *n;1555FLEX_ALLOC_STR(n, name, iter->refname);1556hashcpy(n->sha1, iter->oid->hash);1557 n->next = refs_to_prune;1558 refs_to_prune = n;1559}1560}1561if(ok != ITER_DONE)1562die("error while iterating over references");15631564if(commit_packed_refs(refs))1565die_errno("unable to overwrite old ref-pack file");15661567prune_refs(refs, refs_to_prune);1568return0;1569}15701571/*1572 * Rewrite the packed-refs file, omitting any refs listed in1573 * 'refnames'. On error, leave packed-refs unchanged, write an error1574 * message to 'err', and return a nonzero value.1575 *1576 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1577 */1578static intrepack_without_refs(struct files_ref_store *refs,1579struct string_list *refnames,struct strbuf *err)1580{1581struct ref_dir *packed;1582struct string_list_item *refname;1583int ret, needs_repacking =0, removed =0;15841585files_assert_main_repository(refs,"repack_without_refs");1586assert(err);15871588/* Look for a packed ref */1589for_each_string_list_item(refname, refnames) {1590if(get_packed_ref(refs, refname->string)) {1591 needs_repacking =1;1592break;1593}1594}15951596/* Avoid locking if we have nothing to do */1597if(!needs_repacking)1598return0;/* no refname exists in packed refs */15991600if(lock_packed_refs(refs,0)) {1601unable_to_lock_message(files_packed_refs_path(refs), errno, err);1602return-1;1603}1604 packed =get_packed_refs(refs);16051606/* Remove refnames from the cache */1607for_each_string_list_item(refname, refnames)1608if(remove_entry_from_dir(packed, refname->string) != -1)1609 removed =1;1610if(!removed) {1611/*1612 * All packed entries disappeared while we were1613 * acquiring the lock.1614 */1615rollback_packed_refs(refs);1616return0;1617}16181619/* Write what remains */1620 ret =commit_packed_refs(refs);1621if(ret)1622strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1623strerror(errno));1624return ret;1625}16261627static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1628struct string_list *refnames,unsigned int flags)1629{1630struct files_ref_store *refs =1631files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1632struct strbuf err = STRBUF_INIT;1633int i, result =0;16341635if(!refnames->nr)1636return0;16371638 result =repack_without_refs(refs, refnames, &err);1639if(result) {1640/*1641 * If we failed to rewrite the packed-refs file, then1642 * it is unsafe to try to remove loose refs, because1643 * doing so might expose an obsolete packed value for1644 * a reference that might even point at an object that1645 * has been garbage collected.1646 */1647if(refnames->nr ==1)1648error(_("could not delete reference%s:%s"),1649 refnames->items[0].string, err.buf);1650else1651error(_("could not delete references:%s"), err.buf);16521653goto out;1654}16551656for(i =0; i < refnames->nr; i++) {1657const char*refname = refnames->items[i].string;16581659if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1660 result |=error(_("could not remove reference%s"), refname);1661}16621663out:1664strbuf_release(&err);1665return result;1666}16671668/*1669 * People using contrib's git-new-workdir have .git/logs/refs ->1670 * /some/other/path/.git/logs/refs, and that may live on another device.1671 *1672 * IOW, to avoid cross device rename errors, the temporary renamed log must1673 * live into logs/refs.1674 */1675#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16761677struct rename_cb {1678const char*tmp_renamed_log;1679int true_errno;1680};16811682static intrename_tmp_log_callback(const char*path,void*cb_data)1683{1684struct rename_cb *cb = cb_data;16851686if(rename(cb->tmp_renamed_log, path)) {1687/*1688 * rename(a, b) when b is an existing directory ought1689 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1690 * Sheesh. Record the true errno for error reporting,1691 * but report EISDIR to raceproof_create_file() so1692 * that it knows to retry.1693 */1694 cb->true_errno = errno;1695if(errno == ENOTDIR)1696 errno = EISDIR;1697return-1;1698}else{1699return0;1700}1701}17021703static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1704{1705struct strbuf path = STRBUF_INIT;1706struct strbuf tmp = STRBUF_INIT;1707struct rename_cb cb;1708int ret;17091710files_reflog_path(refs, &path, newrefname);1711files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1712 cb.tmp_renamed_log = tmp.buf;1713 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1714if(ret) {1715if(errno == EISDIR)1716error("directory not empty:%s", path.buf);1717else1718error("unable to move logfile%sto%s:%s",1719 tmp.buf, path.buf,1720strerror(cb.true_errno));1721}17221723strbuf_release(&path);1724strbuf_release(&tmp);1725return ret;1726}17271728static intwrite_ref_to_lockfile(struct ref_lock *lock,1729const struct object_id *oid,struct strbuf *err);1730static intcommit_ref_update(struct files_ref_store *refs,1731struct ref_lock *lock,1732const struct object_id *oid,const char*logmsg,1733struct strbuf *err);17341735static intfiles_rename_ref(struct ref_store *ref_store,1736const char*oldrefname,const char*newrefname,1737const char*logmsg)1738{1739struct files_ref_store *refs =1740files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1741struct object_id oid, orig_oid;1742int flag =0, logmoved =0;1743struct ref_lock *lock;1744struct stat loginfo;1745struct strbuf sb_oldref = STRBUF_INIT;1746struct strbuf sb_newref = STRBUF_INIT;1747struct strbuf tmp_renamed_log = STRBUF_INIT;1748int log, ret;1749struct strbuf err = STRBUF_INIT;17501751files_reflog_path(refs, &sb_oldref, oldrefname);1752files_reflog_path(refs, &sb_newref, newrefname);1753files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17541755 log = !lstat(sb_oldref.buf, &loginfo);1756if(log &&S_ISLNK(loginfo.st_mode)) {1757 ret =error("reflog for%sis a symlink", oldrefname);1758goto out;1759}17601761if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1762 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1763 orig_oid.hash, &flag)) {1764 ret =error("refname%snot found", oldrefname);1765goto out;1766}17671768if(flag & REF_ISSYMREF) {1769 ret =error("refname%sis a symbolic ref, renaming it is not supported",1770 oldrefname);1771goto out;1772}1773if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1774 ret =1;1775goto out;1776}17771778if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1779 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1780 oldrefname,strerror(errno));1781goto out;1782}17831784if(refs_delete_ref(&refs->base, logmsg, oldrefname,1785 orig_oid.hash, REF_NODEREF)) {1786error("unable to delete old%s", oldrefname);1787goto rollback;1788}17891790/*1791 * Since we are doing a shallow lookup, oid is not the1792 * correct value to pass to delete_ref as old_oid. But that1793 * doesn't matter, because an old_oid check wouldn't add to1794 * the safety anyway; we want to delete the reference whatever1795 * its current value.1796 */1797if(!refs_read_ref_full(&refs->base, newrefname,1798 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1799 oid.hash, NULL) &&1800refs_delete_ref(&refs->base, NULL, newrefname,1801 NULL, REF_NODEREF)) {1802if(errno == EISDIR) {1803struct strbuf path = STRBUF_INIT;1804int result;18051806files_ref_path(refs, &path, newrefname);1807 result =remove_empty_directories(&path);1808strbuf_release(&path);18091810if(result) {1811error("Directory not empty:%s", newrefname);1812goto rollback;1813}1814}else{1815error("unable to delete existing%s", newrefname);1816goto rollback;1817}1818}18191820if(log &&rename_tmp_log(refs, newrefname))1821goto rollback;18221823 logmoved = log;18241825 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1826 REF_NODEREF, NULL, &err);1827if(!lock) {1828error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1829strbuf_release(&err);1830goto rollback;1831}1832oidcpy(&lock->old_oid, &orig_oid);18331834if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1835commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1836error("unable to write current sha1 into%s:%s", newrefname, err.buf);1837strbuf_release(&err);1838goto rollback;1839}18401841 ret =0;1842goto out;18431844 rollback:1845 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1846 REF_NODEREF, NULL, &err);1847if(!lock) {1848error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1849strbuf_release(&err);1850goto rollbacklog;1851}18521853 flag = log_all_ref_updates;1854 log_all_ref_updates = LOG_REFS_NONE;1855if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1856commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1857error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1858strbuf_release(&err);1859}1860 log_all_ref_updates = flag;18611862 rollbacklog:1863if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1864error("unable to restore logfile%sfrom%s:%s",1865 oldrefname, newrefname,strerror(errno));1866if(!logmoved && log &&1867rename(tmp_renamed_log.buf, sb_oldref.buf))1868error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1869 oldrefname,strerror(errno));1870 ret =1;1871 out:1872strbuf_release(&sb_newref);1873strbuf_release(&sb_oldref);1874strbuf_release(&tmp_renamed_log);18751876return ret;1877}18781879static intclose_ref(struct ref_lock *lock)1880{1881if(close_lock_file(lock->lk))1882return-1;1883return0;1884}18851886static intcommit_ref(struct ref_lock *lock)1887{1888char*path =get_locked_file_path(lock->lk);1889struct stat st;18901891if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1892/*1893 * There is a directory at the path we want to rename1894 * the lockfile to. Hopefully it is empty; try to1895 * delete it.1896 */1897size_t len =strlen(path);1898struct strbuf sb_path = STRBUF_INIT;18991900strbuf_attach(&sb_path, path, len, len);19011902/*1903 * If this fails, commit_lock_file() will also fail1904 * and will report the problem.1905 */1906remove_empty_directories(&sb_path);1907strbuf_release(&sb_path);1908}else{1909free(path);1910}19111912if(commit_lock_file(lock->lk))1913return-1;1914return0;1915}19161917static intopen_or_create_logfile(const char*path,void*cb)1918{1919int*fd = cb;19201921*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1922return(*fd <0) ? -1:0;1923}19241925/*1926 * Create a reflog for a ref. If force_create = 0, only create the1927 * reflog for certain refs (those for which should_autocreate_reflog1928 * returns non-zero). Otherwise, create it regardless of the reference1929 * name. If the logfile already existed or was created, return 0 and1930 * set *logfd to the file descriptor opened for appending to the file.1931 * If no logfile exists and we decided not to create one, return 0 and1932 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1933 * return -1.1934 */1935static intlog_ref_setup(struct files_ref_store *refs,1936const char*refname,int force_create,1937int*logfd,struct strbuf *err)1938{1939struct strbuf logfile_sb = STRBUF_INIT;1940char*logfile;19411942files_reflog_path(refs, &logfile_sb, refname);1943 logfile =strbuf_detach(&logfile_sb, NULL);19441945if(force_create ||should_autocreate_reflog(refname)) {1946if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1947if(errno == ENOENT)1948strbuf_addf(err,"unable to create directory for '%s': "1949"%s", logfile,strerror(errno));1950else if(errno == EISDIR)1951strbuf_addf(err,"there are still logs under '%s'",1952 logfile);1953else1954strbuf_addf(err,"unable to append to '%s':%s",1955 logfile,strerror(errno));19561957goto error;1958}1959}else{1960*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1961if(*logfd <0) {1962if(errno == ENOENT || errno == EISDIR) {1963/*1964 * The logfile doesn't already exist,1965 * but that is not an error; it only1966 * means that we won't write log1967 * entries to it.1968 */1969;1970}else{1971strbuf_addf(err,"unable to append to '%s':%s",1972 logfile,strerror(errno));1973goto error;1974}1975}1976}19771978if(*logfd >=0)1979adjust_shared_perm(logfile);19801981free(logfile);1982return0;19831984error:1985free(logfile);1986return-1;1987}19881989static intfiles_create_reflog(struct ref_store *ref_store,1990const char*refname,int force_create,1991struct strbuf *err)1992{1993struct files_ref_store *refs =1994files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1995int fd;19961997if(log_ref_setup(refs, refname, force_create, &fd, err))1998return-1;19992000if(fd >=0)2001close(fd);20022003return0;2004}20052006static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2007const struct object_id *new_oid,2008const char*committer,const char*msg)2009{2010int msglen, written;2011unsigned maxlen, len;2012char*logrec;20132014 msglen = msg ?strlen(msg) :0;2015 maxlen =strlen(committer) + msglen +100;2016 logrec =xmalloc(maxlen);2017 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2018oid_to_hex(old_oid),2019oid_to_hex(new_oid),2020 committer);2021if(msglen)2022 len +=copy_reflog_msg(logrec + len -1, msg) -1;20232024 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2025free(logrec);2026if(written != len)2027return-1;20282029return0;2030}20312032static intfiles_log_ref_write(struct files_ref_store *refs,2033const char*refname,const struct object_id *old_oid,2034const struct object_id *new_oid,const char*msg,2035int flags,struct strbuf *err)2036{2037int logfd, result;20382039if(log_all_ref_updates == LOG_REFS_UNSET)2040 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20412042 result =log_ref_setup(refs, refname,2043 flags & REF_FORCE_CREATE_REFLOG,2044&logfd, err);20452046if(result)2047return result;20482049if(logfd <0)2050return0;2051 result =log_ref_write_fd(logfd, old_oid, new_oid,2052git_committer_info(0), msg);2053if(result) {2054struct strbuf sb = STRBUF_INIT;2055int save_errno = errno;20562057files_reflog_path(refs, &sb, refname);2058strbuf_addf(err,"unable to append to '%s':%s",2059 sb.buf,strerror(save_errno));2060strbuf_release(&sb);2061close(logfd);2062return-1;2063}2064if(close(logfd)) {2065struct strbuf sb = STRBUF_INIT;2066int save_errno = errno;20672068files_reflog_path(refs, &sb, refname);2069strbuf_addf(err,"unable to append to '%s':%s",2070 sb.buf,strerror(save_errno));2071strbuf_release(&sb);2072return-1;2073}2074return0;2075}20762077/*2078 * Write sha1 into the open lockfile, then close the lockfile. On2079 * errors, rollback the lockfile, fill in *err and2080 * return -1.2081 */2082static intwrite_ref_to_lockfile(struct ref_lock *lock,2083const struct object_id *oid,struct strbuf *err)2084{2085static char term ='\n';2086struct object *o;2087int fd;20882089 o =parse_object(oid);2090if(!o) {2091strbuf_addf(err,2092"trying to write ref '%s' with nonexistent object%s",2093 lock->ref_name,oid_to_hex(oid));2094unlock_ref(lock);2095return-1;2096}2097if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2098strbuf_addf(err,2099"trying to write non-commit object%sto branch '%s'",2100oid_to_hex(oid), lock->ref_name);2101unlock_ref(lock);2102return-1;2103}2104 fd =get_lock_file_fd(lock->lk);2105if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2106write_in_full(fd, &term,1) !=1||2107close_ref(lock) <0) {2108strbuf_addf(err,2109"couldn't write '%s'",get_lock_file_path(lock->lk));2110unlock_ref(lock);2111return-1;2112}2113return0;2114}21152116/*2117 * Commit a change to a loose reference that has already been written2118 * to the loose reference lockfile. Also update the reflogs if2119 * necessary, using the specified lockmsg (which can be NULL).2120 */2121static intcommit_ref_update(struct files_ref_store *refs,2122struct ref_lock *lock,2123const struct object_id *oid,const char*logmsg,2124struct strbuf *err)2125{2126files_assert_main_repository(refs,"commit_ref_update");21272128clear_loose_ref_cache(refs);2129if(files_log_ref_write(refs, lock->ref_name,2130&lock->old_oid, oid,2131 logmsg,0, err)) {2132char*old_msg =strbuf_detach(err, NULL);2133strbuf_addf(err,"cannot update the ref '%s':%s",2134 lock->ref_name, old_msg);2135free(old_msg);2136unlock_ref(lock);2137return-1;2138}21392140if(strcmp(lock->ref_name,"HEAD") !=0) {2141/*2142 * Special hack: If a branch is updated directly and HEAD2143 * points to it (may happen on the remote side of a push2144 * for example) then logically the HEAD reflog should be2145 * updated too.2146 * A generic solution implies reverse symref information,2147 * but finding all symrefs pointing to the given branch2148 * would be rather costly for this rare event (the direct2149 * update of a branch) to be worth it. So let's cheat and2150 * check with HEAD only which should cover 99% of all usage2151 * scenarios (even 100% of the default ones).2152 */2153struct object_id head_oid;2154int head_flag;2155const char*head_ref;21562157 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2158 RESOLVE_REF_READING,2159 head_oid.hash, &head_flag);2160if(head_ref && (head_flag & REF_ISSYMREF) &&2161!strcmp(head_ref, lock->ref_name)) {2162struct strbuf log_err = STRBUF_INIT;2163if(files_log_ref_write(refs,"HEAD",2164&lock->old_oid, oid,2165 logmsg,0, &log_err)) {2166error("%s", log_err.buf);2167strbuf_release(&log_err);2168}2169}2170}21712172if(commit_ref(lock)) {2173strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2174unlock_ref(lock);2175return-1;2176}21772178unlock_ref(lock);2179return0;2180}21812182static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2183{2184int ret = -1;2185#ifndef NO_SYMLINK_HEAD2186char*ref_path =get_locked_file_path(lock->lk);2187unlink(ref_path);2188 ret =symlink(target, ref_path);2189free(ref_path);21902191if(ret)2192fprintf(stderr,"no symlink - falling back to symbolic ref\n");2193#endif2194return ret;2195}21962197static voidupdate_symref_reflog(struct files_ref_store *refs,2198struct ref_lock *lock,const char*refname,2199const char*target,const char*logmsg)2200{2201struct strbuf err = STRBUF_INIT;2202struct object_id new_oid;2203if(logmsg &&2204!refs_read_ref_full(&refs->base, target,2205 RESOLVE_REF_READING, new_oid.hash, NULL) &&2206files_log_ref_write(refs, refname, &lock->old_oid,2207&new_oid, logmsg,0, &err)) {2208error("%s", err.buf);2209strbuf_release(&err);2210}2211}22122213static intcreate_symref_locked(struct files_ref_store *refs,2214struct ref_lock *lock,const char*refname,2215const char*target,const char*logmsg)2216{2217if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2218update_symref_reflog(refs, lock, refname, target, logmsg);2219return0;2220}22212222if(!fdopen_lock_file(lock->lk,"w"))2223returnerror("unable to fdopen%s:%s",2224 lock->lk->tempfile.filename.buf,strerror(errno));22252226update_symref_reflog(refs, lock, refname, target, logmsg);22272228/* no error check; commit_ref will check ferror */2229fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2230if(commit_ref(lock) <0)2231returnerror("unable to write symref for%s:%s", refname,2232strerror(errno));2233return0;2234}22352236static intfiles_create_symref(struct ref_store *ref_store,2237const char*refname,const char*target,2238const char*logmsg)2239{2240struct files_ref_store *refs =2241files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2242struct strbuf err = STRBUF_INIT;2243struct ref_lock *lock;2244int ret;22452246 lock =lock_ref_sha1_basic(refs, refname, NULL,2247 NULL, NULL, REF_NODEREF, NULL,2248&err);2249if(!lock) {2250error("%s", err.buf);2251strbuf_release(&err);2252return-1;2253}22542255 ret =create_symref_locked(refs, lock, refname, target, logmsg);2256unlock_ref(lock);2257return ret;2258}22592260static intfiles_reflog_exists(struct ref_store *ref_store,2261const char*refname)2262{2263struct files_ref_store *refs =2264files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2265struct strbuf sb = STRBUF_INIT;2266struct stat st;2267int ret;22682269files_reflog_path(refs, &sb, refname);2270 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2271strbuf_release(&sb);2272return ret;2273}22742275static intfiles_delete_reflog(struct ref_store *ref_store,2276const char*refname)2277{2278struct files_ref_store *refs =2279files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2280struct strbuf sb = STRBUF_INIT;2281int ret;22822283files_reflog_path(refs, &sb, refname);2284 ret =remove_path(sb.buf);2285strbuf_release(&sb);2286return ret;2287}22882289static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2290{2291struct object_id ooid, noid;2292char*email_end, *message;2293 timestamp_t timestamp;2294int tz;2295const char*p = sb->buf;22962297/* old SP new SP name <email> SP time TAB msg LF */2298if(!sb->len || sb->buf[sb->len -1] !='\n'||2299parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2300parse_oid_hex(p, &noid, &p) || *p++ !=' '||2301!(email_end =strchr(p,'>')) ||2302 email_end[1] !=' '||2303!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2304!message || message[0] !=' '||2305(message[1] !='+'&& message[1] !='-') ||2306!isdigit(message[2]) || !isdigit(message[3]) ||2307!isdigit(message[4]) || !isdigit(message[5]))2308return0;/* corrupt? */2309 email_end[1] ='\0';2310 tz =strtol(message +1, NULL,10);2311if(message[6] !='\t')2312 message +=6;2313else2314 message +=7;2315returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2316}23172318static char*find_beginning_of_line(char*bob,char*scan)2319{2320while(bob < scan && *(--scan) !='\n')2321;/* keep scanning backwards */2322/*2323 * Return either beginning of the buffer, or LF at the end of2324 * the previous line.2325 */2326return scan;2327}23282329static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2330const char*refname,2331 each_reflog_ent_fn fn,2332void*cb_data)2333{2334struct files_ref_store *refs =2335files_downcast(ref_store, REF_STORE_READ,2336"for_each_reflog_ent_reverse");2337struct strbuf sb = STRBUF_INIT;2338FILE*logfp;2339long pos;2340int ret =0, at_tail =1;23412342files_reflog_path(refs, &sb, refname);2343 logfp =fopen(sb.buf,"r");2344strbuf_release(&sb);2345if(!logfp)2346return-1;23472348/* Jump to the end */2349if(fseek(logfp,0, SEEK_END) <0)2350 ret =error("cannot seek back reflog for%s:%s",2351 refname,strerror(errno));2352 pos =ftell(logfp);2353while(!ret &&0< pos) {2354int cnt;2355size_t nread;2356char buf[BUFSIZ];2357char*endp, *scanp;23582359/* Fill next block from the end */2360 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2361if(fseek(logfp, pos - cnt, SEEK_SET)) {2362 ret =error("cannot seek back reflog for%s:%s",2363 refname,strerror(errno));2364break;2365}2366 nread =fread(buf, cnt,1, logfp);2367if(nread !=1) {2368 ret =error("cannot read%dbytes from reflog for%s:%s",2369 cnt, refname,strerror(errno));2370break;2371}2372 pos -= cnt;23732374 scanp = endp = buf + cnt;2375if(at_tail && scanp[-1] =='\n')2376/* Looking at the final LF at the end of the file */2377 scanp--;2378 at_tail =0;23792380while(buf < scanp) {2381/*2382 * terminating LF of the previous line, or the beginning2383 * of the buffer.2384 */2385char*bp;23862387 bp =find_beginning_of_line(buf, scanp);23882389if(*bp =='\n') {2390/*2391 * The newline is the end of the previous line,2392 * so we know we have complete line starting2393 * at (bp + 1). Prefix it onto any prior data2394 * we collected for the line and process it.2395 */2396strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2397 scanp = bp;2398 endp = bp +1;2399 ret =show_one_reflog_ent(&sb, fn, cb_data);2400strbuf_reset(&sb);2401if(ret)2402break;2403}else if(!pos) {2404/*2405 * We are at the start of the buffer, and the2406 * start of the file; there is no previous2407 * line, and we have everything for this one.2408 * Process it, and we can end the loop.2409 */2410strbuf_splice(&sb,0,0, buf, endp - buf);2411 ret =show_one_reflog_ent(&sb, fn, cb_data);2412strbuf_reset(&sb);2413break;2414}24152416if(bp == buf) {2417/*2418 * We are at the start of the buffer, and there2419 * is more file to read backwards. Which means2420 * we are in the middle of a line. Note that we2421 * may get here even if *bp was a newline; that2422 * just means we are at the exact end of the2423 * previous line, rather than some spot in the2424 * middle.2425 *2426 * Save away what we have to be combined with2427 * the data from the next read.2428 */2429strbuf_splice(&sb,0,0, buf, endp - buf);2430break;2431}2432}24332434}2435if(!ret && sb.len)2436die("BUG: reverse reflog parser had leftover data");24372438fclose(logfp);2439strbuf_release(&sb);2440return ret;2441}24422443static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2444const char*refname,2445 each_reflog_ent_fn fn,void*cb_data)2446{2447struct files_ref_store *refs =2448files_downcast(ref_store, REF_STORE_READ,2449"for_each_reflog_ent");2450FILE*logfp;2451struct strbuf sb = STRBUF_INIT;2452int ret =0;24532454files_reflog_path(refs, &sb, refname);2455 logfp =fopen(sb.buf,"r");2456strbuf_release(&sb);2457if(!logfp)2458return-1;24592460while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2461 ret =show_one_reflog_ent(&sb, fn, cb_data);2462fclose(logfp);2463strbuf_release(&sb);2464return ret;2465}24662467struct files_reflog_iterator {2468struct ref_iterator base;24692470struct ref_store *ref_store;2471struct dir_iterator *dir_iterator;2472struct object_id oid;2473};24742475static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2476{2477struct files_reflog_iterator *iter =2478(struct files_reflog_iterator *)ref_iterator;2479struct dir_iterator *diter = iter->dir_iterator;2480int ok;24812482while((ok =dir_iterator_advance(diter)) == ITER_OK) {2483int flags;24842485if(!S_ISREG(diter->st.st_mode))2486continue;2487if(diter->basename[0] =='.')2488continue;2489if(ends_with(diter->basename,".lock"))2490continue;24912492if(refs_read_ref_full(iter->ref_store,2493 diter->relative_path,0,2494 iter->oid.hash, &flags)) {2495error("bad ref for%s", diter->path.buf);2496continue;2497}24982499 iter->base.refname = diter->relative_path;2500 iter->base.oid = &iter->oid;2501 iter->base.flags = flags;2502return ITER_OK;2503}25042505 iter->dir_iterator = NULL;2506if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2507 ok = ITER_ERROR;2508return ok;2509}25102511static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2512struct object_id *peeled)2513{2514die("BUG: ref_iterator_peel() called for reflog_iterator");2515}25162517static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2518{2519struct files_reflog_iterator *iter =2520(struct files_reflog_iterator *)ref_iterator;2521int ok = ITER_DONE;25222523if(iter->dir_iterator)2524 ok =dir_iterator_abort(iter->dir_iterator);25252526base_ref_iterator_free(ref_iterator);2527return ok;2528}25292530static struct ref_iterator_vtable files_reflog_iterator_vtable = {2531 files_reflog_iterator_advance,2532 files_reflog_iterator_peel,2533 files_reflog_iterator_abort2534};25352536static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2537{2538struct files_ref_store *refs =2539files_downcast(ref_store, REF_STORE_READ,2540"reflog_iterator_begin");2541struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2542struct ref_iterator *ref_iterator = &iter->base;2543struct strbuf sb = STRBUF_INIT;25442545base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2546files_reflog_path(refs, &sb, NULL);2547 iter->dir_iterator =dir_iterator_begin(sb.buf);2548 iter->ref_store = ref_store;2549strbuf_release(&sb);2550return ref_iterator;2551}25522553/*2554 * If update is a direct update of head_ref (the reference pointed to2555 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2556 */2557static intsplit_head_update(struct ref_update *update,2558struct ref_transaction *transaction,2559const char*head_ref,2560struct string_list *affected_refnames,2561struct strbuf *err)2562{2563struct string_list_item *item;2564struct ref_update *new_update;25652566if((update->flags & REF_LOG_ONLY) ||2567(update->flags & REF_ISPRUNING) ||2568(update->flags & REF_UPDATE_VIA_HEAD))2569return0;25702571if(strcmp(update->refname, head_ref))2572return0;25732574/*2575 * First make sure that HEAD is not already in the2576 * transaction. This insertion is O(N) in the transaction2577 * size, but it happens at most once per transaction.2578 */2579 item =string_list_insert(affected_refnames,"HEAD");2580if(item->util) {2581/* An entry already existed */2582strbuf_addf(err,2583"multiple updates for 'HEAD' (including one "2584"via its referent '%s') are not allowed",2585 update->refname);2586return TRANSACTION_NAME_CONFLICT;2587}25882589 new_update =ref_transaction_add_update(2590 transaction,"HEAD",2591 update->flags | REF_LOG_ONLY | REF_NODEREF,2592 update->new_oid.hash, update->old_oid.hash,2593 update->msg);25942595 item->util = new_update;25962597return0;2598}25992600/*2601 * update is for a symref that points at referent and doesn't have2602 * REF_NODEREF set. Split it into two updates:2603 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2604 * - A new, separate update for the referent reference2605 * Note that the new update will itself be subject to splitting when2606 * the iteration gets to it.2607 */2608static intsplit_symref_update(struct files_ref_store *refs,2609struct ref_update *update,2610const char*referent,2611struct ref_transaction *transaction,2612struct string_list *affected_refnames,2613struct strbuf *err)2614{2615struct string_list_item *item;2616struct ref_update *new_update;2617unsigned int new_flags;26182619/*2620 * First make sure that referent is not already in the2621 * transaction. This insertion is O(N) in the transaction2622 * size, but it happens at most once per symref in a2623 * transaction.2624 */2625 item =string_list_insert(affected_refnames, referent);2626if(item->util) {2627/* An entry already existed */2628strbuf_addf(err,2629"multiple updates for '%s' (including one "2630"via symref '%s') are not allowed",2631 referent, update->refname);2632return TRANSACTION_NAME_CONFLICT;2633}26342635 new_flags = update->flags;2636if(!strcmp(update->refname,"HEAD")) {2637/*2638 * Record that the new update came via HEAD, so that2639 * when we process it, split_head_update() doesn't try2640 * to add another reflog update for HEAD. Note that2641 * this bit will be propagated if the new_update2642 * itself needs to be split.2643 */2644 new_flags |= REF_UPDATE_VIA_HEAD;2645}26462647 new_update =ref_transaction_add_update(2648 transaction, referent, new_flags,2649 update->new_oid.hash, update->old_oid.hash,2650 update->msg);26512652 new_update->parent_update = update;26532654/*2655 * Change the symbolic ref update to log only. Also, it2656 * doesn't need to check its old SHA-1 value, as that will be2657 * done when new_update is processed.2658 */2659 update->flags |= REF_LOG_ONLY | REF_NODEREF;2660 update->flags &= ~REF_HAVE_OLD;26612662 item->util = new_update;26632664return0;2665}26662667/*2668 * Return the refname under which update was originally requested.2669 */2670static const char*original_update_refname(struct ref_update *update)2671{2672while(update->parent_update)2673 update = update->parent_update;26742675return update->refname;2676}26772678/*2679 * Check whether the REF_HAVE_OLD and old_oid values stored in update2680 * are consistent with oid, which is the reference's current value. If2681 * everything is OK, return 0; otherwise, write an error message to2682 * err and return -1.2683 */2684static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2685struct strbuf *err)2686{2687if(!(update->flags & REF_HAVE_OLD) ||2688!oidcmp(oid, &update->old_oid))2689return0;26902691if(is_null_oid(&update->old_oid))2692strbuf_addf(err,"cannot lock ref '%s': "2693"reference already exists",2694original_update_refname(update));2695else if(is_null_oid(oid))2696strbuf_addf(err,"cannot lock ref '%s': "2697"reference is missing but expected%s",2698original_update_refname(update),2699oid_to_hex(&update->old_oid));2700else2701strbuf_addf(err,"cannot lock ref '%s': "2702"is at%sbut expected%s",2703original_update_refname(update),2704oid_to_hex(oid),2705oid_to_hex(&update->old_oid));27062707return-1;2708}27092710/*2711 * Prepare for carrying out update:2712 * - Lock the reference referred to by update.2713 * - Read the reference under lock.2714 * - Check that its old SHA-1 value (if specified) is correct, and in2715 * any case record it in update->lock->old_oid for later use when2716 * writing the reflog.2717 * - If it is a symref update without REF_NODEREF, split it up into a2718 * REF_LOG_ONLY update of the symref and add a separate update for2719 * the referent to transaction.2720 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2721 * update of HEAD.2722 */2723static intlock_ref_for_update(struct files_ref_store *refs,2724struct ref_update *update,2725struct ref_transaction *transaction,2726const char*head_ref,2727struct string_list *affected_refnames,2728struct strbuf *err)2729{2730struct strbuf referent = STRBUF_INIT;2731int mustexist = (update->flags & REF_HAVE_OLD) &&2732!is_null_oid(&update->old_oid);2733int ret;2734struct ref_lock *lock;27352736files_assert_main_repository(refs,"lock_ref_for_update");27372738if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2739 update->flags |= REF_DELETING;27402741if(head_ref) {2742 ret =split_head_update(update, transaction, head_ref,2743 affected_refnames, err);2744if(ret)2745return ret;2746}27472748 ret =lock_raw_ref(refs, update->refname, mustexist,2749 affected_refnames, NULL,2750&lock, &referent,2751&update->type, err);2752if(ret) {2753char*reason;27542755 reason =strbuf_detach(err, NULL);2756strbuf_addf(err,"cannot lock ref '%s':%s",2757original_update_refname(update), reason);2758free(reason);2759return ret;2760}27612762 update->backend_data = lock;27632764if(update->type & REF_ISSYMREF) {2765if(update->flags & REF_NODEREF) {2766/*2767 * We won't be reading the referent as part of2768 * the transaction, so we have to read it here2769 * to record and possibly check old_sha1:2770 */2771if(refs_read_ref_full(&refs->base,2772 referent.buf,0,2773 lock->old_oid.hash, NULL)) {2774if(update->flags & REF_HAVE_OLD) {2775strbuf_addf(err,"cannot lock ref '%s': "2776"error reading reference",2777original_update_refname(update));2778return-1;2779}2780}else if(check_old_oid(update, &lock->old_oid, err)) {2781return TRANSACTION_GENERIC_ERROR;2782}2783}else{2784/*2785 * Create a new update for the reference this2786 * symref is pointing at. Also, we will record2787 * and verify old_sha1 for this update as part2788 * of processing the split-off update, so we2789 * don't have to do it here.2790 */2791 ret =split_symref_update(refs, update,2792 referent.buf, transaction,2793 affected_refnames, err);2794if(ret)2795return ret;2796}2797}else{2798struct ref_update *parent_update;27992800if(check_old_oid(update, &lock->old_oid, err))2801return TRANSACTION_GENERIC_ERROR;28022803/*2804 * If this update is happening indirectly because of a2805 * symref update, record the old SHA-1 in the parent2806 * update:2807 */2808for(parent_update = update->parent_update;2809 parent_update;2810 parent_update = parent_update->parent_update) {2811struct ref_lock *parent_lock = parent_update->backend_data;2812oidcpy(&parent_lock->old_oid, &lock->old_oid);2813}2814}28152816if((update->flags & REF_HAVE_NEW) &&2817!(update->flags & REF_DELETING) &&2818!(update->flags & REF_LOG_ONLY)) {2819if(!(update->type & REF_ISSYMREF) &&2820!oidcmp(&lock->old_oid, &update->new_oid)) {2821/*2822 * The reference already has the desired2823 * value, so we don't need to write it.2824 */2825}else if(write_ref_to_lockfile(lock, &update->new_oid,2826 err)) {2827char*write_err =strbuf_detach(err, NULL);28282829/*2830 * The lock was freed upon failure of2831 * write_ref_to_lockfile():2832 */2833 update->backend_data = NULL;2834strbuf_addf(err,2835"cannot update ref '%s':%s",2836 update->refname, write_err);2837free(write_err);2838return TRANSACTION_GENERIC_ERROR;2839}else{2840 update->flags |= REF_NEEDS_COMMIT;2841}2842}2843if(!(update->flags & REF_NEEDS_COMMIT)) {2844/*2845 * We didn't call write_ref_to_lockfile(), so2846 * the lockfile is still open. Close it to2847 * free up the file descriptor:2848 */2849if(close_ref(lock)) {2850strbuf_addf(err,"couldn't close '%s.lock'",2851 update->refname);2852return TRANSACTION_GENERIC_ERROR;2853}2854}2855return0;2856}28572858/*2859 * Unlock any references in `transaction` that are still locked, and2860 * mark the transaction closed.2861 */2862static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2863{2864size_t i;28652866for(i =0; i < transaction->nr; i++) {2867struct ref_update *update = transaction->updates[i];2868struct ref_lock *lock = update->backend_data;28692870if(lock) {2871unlock_ref(lock);2872 update->backend_data = NULL;2873}2874}28752876 transaction->state = REF_TRANSACTION_CLOSED;2877}28782879static intfiles_transaction_prepare(struct ref_store *ref_store,2880struct ref_transaction *transaction,2881struct strbuf *err)2882{2883struct files_ref_store *refs =2884files_downcast(ref_store, REF_STORE_WRITE,2885"ref_transaction_prepare");2886size_t i;2887int ret =0;2888struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2889char*head_ref = NULL;2890int head_type;2891struct object_id head_oid;28922893assert(err);28942895if(!transaction->nr)2896goto cleanup;28972898/*2899 * Fail if a refname appears more than once in the2900 * transaction. (If we end up splitting up any updates using2901 * split_symref_update() or split_head_update(), those2902 * functions will check that the new updates don't have the2903 * same refname as any existing ones.)2904 */2905for(i =0; i < transaction->nr; i++) {2906struct ref_update *update = transaction->updates[i];2907struct string_list_item *item =2908string_list_append(&affected_refnames, update->refname);29092910/*2911 * We store a pointer to update in item->util, but at2912 * the moment we never use the value of this field2913 * except to check whether it is non-NULL.2914 */2915 item->util = update;2916}2917string_list_sort(&affected_refnames);2918if(ref_update_reject_duplicates(&affected_refnames, err)) {2919 ret = TRANSACTION_GENERIC_ERROR;2920goto cleanup;2921}29222923/*2924 * Special hack: If a branch is updated directly and HEAD2925 * points to it (may happen on the remote side of a push2926 * for example) then logically the HEAD reflog should be2927 * updated too.2928 *2929 * A generic solution would require reverse symref lookups,2930 * but finding all symrefs pointing to a given branch would be2931 * rather costly for this rare event (the direct update of a2932 * branch) to be worth it. So let's cheat and check with HEAD2933 * only, which should cover 99% of all usage scenarios (even2934 * 100% of the default ones).2935 *2936 * So if HEAD is a symbolic reference, then record the name of2937 * the reference that it points to. If we see an update of2938 * head_ref within the transaction, then split_head_update()2939 * arranges for the reflog of HEAD to be updated, too.2940 */2941 head_ref =refs_resolve_refdup(ref_store,"HEAD",2942 RESOLVE_REF_NO_RECURSE,2943 head_oid.hash, &head_type);29442945if(head_ref && !(head_type & REF_ISSYMREF)) {2946free(head_ref);2947 head_ref = NULL;2948}29492950/*2951 * Acquire all locks, verify old values if provided, check2952 * that new values are valid, and write new values to the2953 * lockfiles, ready to be activated. Only keep one lockfile2954 * open at a time to avoid running out of file descriptors.2955 * Note that lock_ref_for_update() might append more updates2956 * to the transaction.2957 */2958for(i =0; i < transaction->nr; i++) {2959struct ref_update *update = transaction->updates[i];29602961 ret =lock_ref_for_update(refs, update, transaction,2962 head_ref, &affected_refnames, err);2963if(ret)2964break;2965}29662967cleanup:2968free(head_ref);2969string_list_clear(&affected_refnames,0);29702971if(ret)2972files_transaction_cleanup(transaction);2973else2974 transaction->state = REF_TRANSACTION_PREPARED;29752976return ret;2977}29782979static intfiles_transaction_finish(struct ref_store *ref_store,2980struct ref_transaction *transaction,2981struct strbuf *err)2982{2983struct files_ref_store *refs =2984files_downcast(ref_store,0,"ref_transaction_finish");2985size_t i;2986int ret =0;2987struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2988struct string_list_item *ref_to_delete;2989struct strbuf sb = STRBUF_INIT;29902991assert(err);29922993if(!transaction->nr) {2994 transaction->state = REF_TRANSACTION_CLOSED;2995return0;2996}29972998/* Perform updates first so live commits remain referenced */2999for(i =0; i < transaction->nr; i++) {3000struct ref_update *update = transaction->updates[i];3001struct ref_lock *lock = update->backend_data;30023003if(update->flags & REF_NEEDS_COMMIT ||3004 update->flags & REF_LOG_ONLY) {3005if(files_log_ref_write(refs,3006 lock->ref_name,3007&lock->old_oid,3008&update->new_oid,3009 update->msg, update->flags,3010 err)) {3011char*old_msg =strbuf_detach(err, NULL);30123013strbuf_addf(err,"cannot update the ref '%s':%s",3014 lock->ref_name, old_msg);3015free(old_msg);3016unlock_ref(lock);3017 update->backend_data = NULL;3018 ret = TRANSACTION_GENERIC_ERROR;3019goto cleanup;3020}3021}3022if(update->flags & REF_NEEDS_COMMIT) {3023clear_loose_ref_cache(refs);3024if(commit_ref(lock)) {3025strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3026unlock_ref(lock);3027 update->backend_data = NULL;3028 ret = TRANSACTION_GENERIC_ERROR;3029goto cleanup;3030}3031}3032}3033/* Perform deletes now that updates are safely completed */3034for(i =0; i < transaction->nr; i++) {3035struct ref_update *update = transaction->updates[i];3036struct ref_lock *lock = update->backend_data;30373038if(update->flags & REF_DELETING &&3039!(update->flags & REF_LOG_ONLY)) {3040if(!(update->type & REF_ISPACKED) ||3041 update->type & REF_ISSYMREF) {3042/* It is a loose reference. */3043strbuf_reset(&sb);3044files_ref_path(refs, &sb, lock->ref_name);3045if(unlink_or_msg(sb.buf, err)) {3046 ret = TRANSACTION_GENERIC_ERROR;3047goto cleanup;3048}3049 update->flags |= REF_DELETED_LOOSE;3050}30513052if(!(update->flags & REF_ISPRUNING))3053string_list_append(&refs_to_delete,3054 lock->ref_name);3055}3056}30573058if(repack_without_refs(refs, &refs_to_delete, err)) {3059 ret = TRANSACTION_GENERIC_ERROR;3060goto cleanup;3061}30623063/* Delete the reflogs of any references that were deleted: */3064for_each_string_list_item(ref_to_delete, &refs_to_delete) {3065strbuf_reset(&sb);3066files_reflog_path(refs, &sb, ref_to_delete->string);3067if(!unlink_or_warn(sb.buf))3068try_remove_empty_parents(refs, ref_to_delete->string,3069 REMOVE_EMPTY_PARENTS_REFLOG);3070}30713072clear_loose_ref_cache(refs);30733074cleanup:3075files_transaction_cleanup(transaction);30763077for(i =0; i < transaction->nr; i++) {3078struct ref_update *update = transaction->updates[i];30793080if(update->flags & REF_DELETED_LOOSE) {3081/*3082 * The loose reference was deleted. Delete any3083 * empty parent directories. (Note that this3084 * can only work because we have already3085 * removed the lockfile.)3086 */3087try_remove_empty_parents(refs, update->refname,3088 REMOVE_EMPTY_PARENTS_REF);3089}3090}30913092strbuf_release(&sb);3093string_list_clear(&refs_to_delete,0);3094return ret;3095}30963097static intfiles_transaction_abort(struct ref_store *ref_store,3098struct ref_transaction *transaction,3099struct strbuf *err)3100{3101files_transaction_cleanup(transaction);3102return0;3103}31043105static intref_present(const char*refname,3106const struct object_id *oid,int flags,void*cb_data)3107{3108struct string_list *affected_refnames = cb_data;31093110returnstring_list_has_string(affected_refnames, refname);3111}31123113static intfiles_initial_transaction_commit(struct ref_store *ref_store,3114struct ref_transaction *transaction,3115struct strbuf *err)3116{3117struct files_ref_store *refs =3118files_downcast(ref_store, REF_STORE_WRITE,3119"initial_ref_transaction_commit");3120size_t i;3121int ret =0;3122struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31233124assert(err);31253126if(transaction->state != REF_TRANSACTION_OPEN)3127die("BUG: commit called for transaction that is not open");31283129/* Fail if a refname appears more than once in the transaction: */3130for(i =0; i < transaction->nr; i++)3131string_list_append(&affected_refnames,3132 transaction->updates[i]->refname);3133string_list_sort(&affected_refnames);3134if(ref_update_reject_duplicates(&affected_refnames, err)) {3135 ret = TRANSACTION_GENERIC_ERROR;3136goto cleanup;3137}31383139/*3140 * It's really undefined to call this function in an active3141 * repository or when there are existing references: we are3142 * only locking and changing packed-refs, so (1) any3143 * simultaneous processes might try to change a reference at3144 * the same time we do, and (2) any existing loose versions of3145 * the references that we are setting would have precedence3146 * over our values. But some remote helpers create the remote3147 * "HEAD" and "master" branches before calling this function,3148 * so here we really only check that none of the references3149 * that we are creating already exists.3150 */3151if(refs_for_each_rawref(&refs->base, ref_present,3152&affected_refnames))3153die("BUG: initial ref transaction called with existing refs");31543155for(i =0; i < transaction->nr; i++) {3156struct ref_update *update = transaction->updates[i];31573158if((update->flags & REF_HAVE_OLD) &&3159!is_null_oid(&update->old_oid))3160die("BUG: initial ref transaction with old_sha1 set");3161if(refs_verify_refname_available(&refs->base, update->refname,3162&affected_refnames, NULL,3163 err)) {3164 ret = TRANSACTION_NAME_CONFLICT;3165goto cleanup;3166}3167}31683169if(lock_packed_refs(refs,0)) {3170strbuf_addf(err,"unable to lock packed-refs file:%s",3171strerror(errno));3172 ret = TRANSACTION_GENERIC_ERROR;3173goto cleanup;3174}31753176for(i =0; i < transaction->nr; i++) {3177struct ref_update *update = transaction->updates[i];31783179if((update->flags & REF_HAVE_NEW) &&3180!is_null_oid(&update->new_oid))3181add_packed_ref(refs, update->refname,3182&update->new_oid);3183}31843185if(commit_packed_refs(refs)) {3186strbuf_addf(err,"unable to commit packed-refs file:%s",3187strerror(errno));3188 ret = TRANSACTION_GENERIC_ERROR;3189goto cleanup;3190}31913192cleanup:3193 transaction->state = REF_TRANSACTION_CLOSED;3194string_list_clear(&affected_refnames,0);3195return ret;3196}31973198struct expire_reflog_cb {3199unsigned int flags;3200 reflog_expiry_should_prune_fn *should_prune_fn;3201void*policy_cb;3202FILE*newlog;3203struct object_id last_kept_oid;3204};32053206static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3207const char*email, timestamp_t timestamp,int tz,3208const char*message,void*cb_data)3209{3210struct expire_reflog_cb *cb = cb_data;3211struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32123213if(cb->flags & EXPIRE_REFLOGS_REWRITE)3214 ooid = &cb->last_kept_oid;32153216if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3217 message, policy_cb)) {3218if(!cb->newlog)3219printf("would prune%s", message);3220else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3221printf("prune%s", message);3222}else{3223if(cb->newlog) {3224fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3225oid_to_hex(ooid),oid_to_hex(noid),3226 email, timestamp, tz, message);3227oidcpy(&cb->last_kept_oid, noid);3228}3229if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3230printf("keep%s", message);3231}3232return0;3233}32343235static intfiles_reflog_expire(struct ref_store *ref_store,3236const char*refname,const unsigned char*sha1,3237unsigned int flags,3238 reflog_expiry_prepare_fn prepare_fn,3239 reflog_expiry_should_prune_fn should_prune_fn,3240 reflog_expiry_cleanup_fn cleanup_fn,3241void*policy_cb_data)3242{3243struct files_ref_store *refs =3244files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3245static struct lock_file reflog_lock;3246struct expire_reflog_cb cb;3247struct ref_lock *lock;3248struct strbuf log_file_sb = STRBUF_INIT;3249char*log_file;3250int status =0;3251int type;3252struct strbuf err = STRBUF_INIT;3253struct object_id oid;32543255memset(&cb,0,sizeof(cb));3256 cb.flags = flags;3257 cb.policy_cb = policy_cb_data;3258 cb.should_prune_fn = should_prune_fn;32593260/*3261 * The reflog file is locked by holding the lock on the3262 * reference itself, plus we might need to update the3263 * reference if --updateref was specified:3264 */3265 lock =lock_ref_sha1_basic(refs, refname, sha1,3266 NULL, NULL, REF_NODEREF,3267&type, &err);3268if(!lock) {3269error("cannot lock ref '%s':%s", refname, err.buf);3270strbuf_release(&err);3271return-1;3272}3273if(!refs_reflog_exists(ref_store, refname)) {3274unlock_ref(lock);3275return0;3276}32773278files_reflog_path(refs, &log_file_sb, refname);3279 log_file =strbuf_detach(&log_file_sb, NULL);3280if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3281/*3282 * Even though holding $GIT_DIR/logs/$reflog.lock has3283 * no locking implications, we use the lock_file3284 * machinery here anyway because it does a lot of the3285 * work we need, including cleaning up if the program3286 * exits unexpectedly.3287 */3288if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3289struct strbuf err = STRBUF_INIT;3290unable_to_lock_message(log_file, errno, &err);3291error("%s", err.buf);3292strbuf_release(&err);3293goto failure;3294}3295 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3296if(!cb.newlog) {3297error("cannot fdopen%s(%s)",3298get_lock_file_path(&reflog_lock),strerror(errno));3299goto failure;3300}3301}33023303hashcpy(oid.hash, sha1);33043305(*prepare_fn)(refname, &oid, cb.policy_cb);3306refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3307(*cleanup_fn)(cb.policy_cb);33083309if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3310/*3311 * It doesn't make sense to adjust a reference pointed3312 * to by a symbolic ref based on expiring entries in3313 * the symbolic reference's reflog. Nor can we update3314 * a reference if there are no remaining reflog3315 * entries.3316 */3317int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3318!(type & REF_ISSYMREF) &&3319!is_null_oid(&cb.last_kept_oid);33203321if(close_lock_file(&reflog_lock)) {3322 status |=error("couldn't write%s:%s", log_file,3323strerror(errno));3324}else if(update &&3325(write_in_full(get_lock_file_fd(lock->lk),3326oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3327write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3328close_ref(lock) <0)) {3329 status |=error("couldn't write%s",3330get_lock_file_path(lock->lk));3331rollback_lock_file(&reflog_lock);3332}else if(commit_lock_file(&reflog_lock)) {3333 status |=error("unable to write reflog '%s' (%s)",3334 log_file,strerror(errno));3335}else if(update &&commit_ref(lock)) {3336 status |=error("couldn't set%s", lock->ref_name);3337}3338}3339free(log_file);3340unlock_ref(lock);3341return status;33423343 failure:3344rollback_lock_file(&reflog_lock);3345free(log_file);3346unlock_ref(lock);3347return-1;3348}33493350static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3351{3352struct files_ref_store *refs =3353files_downcast(ref_store, REF_STORE_WRITE,"init_db");3354struct strbuf sb = STRBUF_INIT;33553356/*3357 * Create .git/refs/{heads,tags}3358 */3359files_ref_path(refs, &sb,"refs/heads");3360safe_create_dir(sb.buf,1);33613362strbuf_reset(&sb);3363files_ref_path(refs, &sb,"refs/tags");3364safe_create_dir(sb.buf,1);33653366strbuf_release(&sb);3367return0;3368}33693370struct ref_storage_be refs_be_files = {3371 NULL,3372"files",3373 files_ref_store_create,3374 files_init_db,3375 files_transaction_prepare,3376 files_transaction_finish,3377 files_transaction_abort,3378 files_initial_transaction_commit,33793380 files_pack_refs,3381 files_peel_ref,3382 files_create_symref,3383 files_delete_refs,3384 files_rename_ref,33853386 files_ref_iterator_begin,3387 files_read_raw_ref,33883389 files_reflog_iterator_begin,3390 files_for_each_reflog_ent,3391 files_for_each_reflog_ent_reverse,3392 files_reflog_exists,3393 files_create_reflog,3394 files_delete_reflog,3395 files_reflog_expire3396};