1#include"../cache.h" 2#include"../config.h" 3#include"../refs.h" 4#include"refs-internal.h" 5#include"ref-cache.h" 6#include"../iterator.h" 7#include"../dir-iterator.h" 8#include"../lockfile.h" 9#include"../object.h" 10#include"../dir.h" 11 12struct ref_lock { 13char*ref_name; 14struct lock_file *lk; 15struct object_id old_oid; 16}; 17 18/* 19 * Return true if refname, which has the specified oid and flags, can 20 * be resolved to an object in the database. If the referred-to object 21 * does not exist, emit a warning and return false. 22 */ 23static intref_resolves_to_object(const char*refname, 24const struct object_id *oid, 25unsigned int flags) 26{ 27if(flags & REF_ISBROKEN) 28return0; 29if(!has_sha1_file(oid->hash)) { 30error("%sdoes not point to a valid object!", refname); 31return0; 32} 33return1; 34} 35 36struct packed_ref_cache { 37struct ref_cache *cache; 38 39/* 40 * Count of references to the data structure in this instance, 41 * including the pointer from files_ref_store::packed if any. 42 * The data will not be freed as long as the reference count 43 * is nonzero. 44 */ 45unsigned int referrers; 46 47/* The metadata from when this packed-refs cache was read */ 48struct stat_validity validity; 49}; 50 51/* 52 * Future: need to be in "struct repository" 53 * when doing a full libification. 54 */ 55struct files_ref_store { 56struct ref_store base; 57unsigned int store_flags; 58 59char*gitdir; 60char*gitcommondir; 61char*packed_refs_path; 62 63struct ref_cache *loose; 64struct packed_ref_cache *packed; 65 66/* 67 * Lock used for the "packed-refs" file. Note that this (and 68 * thus the enclosing `files_ref_store`) must not be freed. 69 */ 70struct lock_file packed_refs_lock; 71}; 72 73/* 74 * Increment the reference count of *packed_refs. 75 */ 76static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 77{ 78 packed_refs->referrers++; 79} 80 81/* 82 * Decrease the reference count of *packed_refs. If it goes to zero, 83 * free *packed_refs and return true; otherwise return false. 84 */ 85static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 86{ 87if(!--packed_refs->referrers) { 88free_ref_cache(packed_refs->cache); 89stat_validity_clear(&packed_refs->validity); 90free(packed_refs); 91return1; 92}else{ 93return0; 94} 95} 96 97static voidclear_packed_ref_cache(struct files_ref_store *refs) 98{ 99if(refs->packed) { 100struct packed_ref_cache *packed_refs = refs->packed; 101 102if(is_lock_file_locked(&refs->packed_refs_lock)) 103die("BUG: packed-ref cache cleared while locked"); 104 refs->packed = NULL; 105release_packed_ref_cache(packed_refs); 106} 107} 108 109static voidclear_loose_ref_cache(struct files_ref_store *refs) 110{ 111if(refs->loose) { 112free_ref_cache(refs->loose); 113 refs->loose = NULL; 114} 115} 116 117/* 118 * Create a new submodule ref cache and add it to the internal 119 * set of caches. 120 */ 121static struct ref_store *files_ref_store_create(const char*gitdir, 122unsigned int flags) 123{ 124struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 125struct ref_store *ref_store = (struct ref_store *)refs; 126struct strbuf sb = STRBUF_INIT; 127 128base_ref_store_init(ref_store, &refs_be_files); 129 refs->store_flags = flags; 130 131 refs->gitdir =xstrdup(gitdir); 132get_common_dir_noenv(&sb, gitdir); 133 refs->gitcommondir =strbuf_detach(&sb, NULL); 134strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 135 refs->packed_refs_path =strbuf_detach(&sb, NULL); 136 137return ref_store; 138} 139 140/* 141 * Die if refs is not the main ref store. caller is used in any 142 * necessary error messages. 143 */ 144static voidfiles_assert_main_repository(struct files_ref_store *refs, 145const char*caller) 146{ 147if(refs->store_flags & REF_STORE_MAIN) 148return; 149 150die("BUG: operation%sonly allowed for main ref store", caller); 151} 152 153/* 154 * Downcast ref_store to files_ref_store. Die if ref_store is not a 155 * files_ref_store. required_flags is compared with ref_store's 156 * store_flags to ensure the ref_store has all required capabilities. 157 * "caller" is used in any necessary error messages. 158 */ 159static struct files_ref_store *files_downcast(struct ref_store *ref_store, 160unsigned int required_flags, 161const char*caller) 162{ 163struct files_ref_store *refs; 164 165if(ref_store->be != &refs_be_files) 166die("BUG: ref_store is type\"%s\"not\"files\"in%s", 167 ref_store->be->name, caller); 168 169 refs = (struct files_ref_store *)ref_store; 170 171if((refs->store_flags & required_flags) != required_flags) 172die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 173 caller, required_flags, refs->store_flags); 174 175return refs; 176} 177 178/* The length of a peeled reference line in packed-refs, including EOL: */ 179#define PEELED_LINE_LENGTH 42 180 181/* 182 * The packed-refs header line that we write out. Perhaps other 183 * traits will be added later. The trailing space is required. 184 */ 185static const char PACKED_REFS_HEADER[] = 186"# pack-refs with: peeled fully-peeled\n"; 187 188/* 189 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 190 * Return a pointer to the refname within the line (null-terminated), 191 * or NULL if there was a problem. 192 */ 193static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 194{ 195const char*ref; 196 197if(parse_oid_hex(line->buf, oid, &ref) <0) 198return NULL; 199if(!isspace(*ref++)) 200return NULL; 201 202if(isspace(*ref)) 203return NULL; 204 205if(line->buf[line->len -1] !='\n') 206return NULL; 207 line->buf[--line->len] =0; 208 209return ref; 210} 211 212/* 213 * Read from `packed_refs_file` into a newly-allocated 214 * `packed_ref_cache` and return it. The return value will already 215 * have its reference count incremented. 216 * 217 * A comment line of the form "# pack-refs with: " may contain zero or 218 * more traits. We interpret the traits as follows: 219 * 220 * No traits: 221 * 222 * Probably no references are peeled. But if the file contains a 223 * peeled value for a reference, we will use it. 224 * 225 * peeled: 226 * 227 * References under "refs/tags/", if they *can* be peeled, *are* 228 * peeled in this file. References outside of "refs/tags/" are 229 * probably not peeled even if they could have been, but if we find 230 * a peeled value for such a reference we will use it. 231 * 232 * fully-peeled: 233 * 234 * All references in the file that can be peeled are peeled. 235 * Inversely (and this is more important), any references in the 236 * file for which no peeled value is recorded is not peelable. This 237 * trait should typically be written alongside "peeled" for 238 * compatibility with older clients, but we do not require it 239 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 240 */ 241static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 242{ 243FILE*f; 244struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 245struct ref_entry *last = NULL; 246struct strbuf line = STRBUF_INIT; 247enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 248struct ref_dir *dir; 249 250acquire_packed_ref_cache(packed_refs); 251 packed_refs->cache =create_ref_cache(NULL, NULL); 252 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 253 254 f =fopen(packed_refs_file,"r"); 255if(!f) { 256if(errno == ENOENT) { 257/* 258 * This is OK; it just means that no 259 * "packed-refs" file has been written yet, 260 * which is equivalent to it being empty. 261 */ 262return packed_refs; 263}else{ 264die_errno("couldn't read%s", packed_refs_file); 265} 266} 267 268stat_validity_update(&packed_refs->validity,fileno(f)); 269 270 dir =get_ref_dir(packed_refs->cache->root); 271while(strbuf_getwholeline(&line, f,'\n') != EOF) { 272struct object_id oid; 273const char*refname; 274const char*traits; 275 276if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 277if(strstr(traits," fully-peeled ")) 278 peeled = PEELED_FULLY; 279else if(strstr(traits," peeled ")) 280 peeled = PEELED_TAGS; 281/* perhaps other traits later as well */ 282continue; 283} 284 285 refname =parse_ref_line(&line, &oid); 286if(refname) { 287int flag = REF_ISPACKED; 288 289if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 290if(!refname_is_safe(refname)) 291die("packed refname is dangerous:%s", refname); 292oidclr(&oid); 293 flag |= REF_BAD_NAME | REF_ISBROKEN; 294} 295 last =create_ref_entry(refname, &oid, flag); 296if(peeled == PEELED_FULLY || 297(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 298 last->flag |= REF_KNOWS_PEELED; 299add_ref_entry(dir, last); 300continue; 301} 302if(last && 303 line.buf[0] =='^'&& 304 line.len == PEELED_LINE_LENGTH && 305 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 306!get_oid_hex(line.buf +1, &oid)) { 307oidcpy(&last->u.value.peeled, &oid); 308/* 309 * Regardless of what the file header said, 310 * we definitely know the value of *this* 311 * reference: 312 */ 313 last->flag |= REF_KNOWS_PEELED; 314} 315} 316 317fclose(f); 318strbuf_release(&line); 319 320return packed_refs; 321} 322 323static const char*files_packed_refs_path(struct files_ref_store *refs) 324{ 325return refs->packed_refs_path; 326} 327 328static voidfiles_reflog_path(struct files_ref_store *refs, 329struct strbuf *sb, 330const char*refname) 331{ 332if(!refname) { 333/* 334 * FIXME: of course this is wrong in multi worktree 335 * setting. To be fixed real soon. 336 */ 337strbuf_addf(sb,"%s/logs", refs->gitcommondir); 338return; 339} 340 341switch(ref_type(refname)) { 342case REF_TYPE_PER_WORKTREE: 343case REF_TYPE_PSEUDOREF: 344strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 345break; 346case REF_TYPE_NORMAL: 347strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 348break; 349default: 350die("BUG: unknown ref type%dof ref%s", 351ref_type(refname), refname); 352} 353} 354 355static voidfiles_ref_path(struct files_ref_store *refs, 356struct strbuf *sb, 357const char*refname) 358{ 359switch(ref_type(refname)) { 360case REF_TYPE_PER_WORKTREE: 361case REF_TYPE_PSEUDOREF: 362strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 363break; 364case REF_TYPE_NORMAL: 365strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 366break; 367default: 368die("BUG: unknown ref type%dof ref%s", 369ref_type(refname), refname); 370} 371} 372 373/* 374 * Get the packed_ref_cache for the specified files_ref_store, 375 * creating and populating it if it hasn't been read before or if the 376 * file has been changed (according to its `validity` field) since it 377 * was last read. On the other hand, if we hold the lock, then assume 378 * that the file hasn't been changed out from under us, so skip the 379 * extra `stat()` call in `stat_validity_check()`. 380 */ 381static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 382{ 383const char*packed_refs_file =files_packed_refs_path(refs); 384 385if(refs->packed && 386!is_lock_file_locked(&refs->packed_refs_lock) && 387!stat_validity_check(&refs->packed->validity, packed_refs_file)) 388clear_packed_ref_cache(refs); 389 390if(!refs->packed) 391 refs->packed =read_packed_refs(packed_refs_file); 392 393return refs->packed; 394} 395 396static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 397{ 398returnget_ref_dir(packed_ref_cache->cache->root); 399} 400 401static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 402{ 403returnget_packed_ref_dir(get_packed_ref_cache(refs)); 404} 405 406/* 407 * Add a reference to the in-memory packed reference cache. This may 408 * only be called while the packed-refs file is locked (see 409 * lock_packed_refs()). To actually write the packed-refs file, call 410 * commit_packed_refs(). 411 */ 412static voidadd_packed_ref(struct files_ref_store *refs, 413const char*refname,const struct object_id *oid) 414{ 415struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 416 417if(!is_lock_file_locked(&refs->packed_refs_lock)) 418die("BUG: packed refs not locked"); 419 420if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 421die("Reference has invalid format: '%s'", refname); 422 423add_ref_entry(get_packed_ref_dir(packed_ref_cache), 424create_ref_entry(refname, oid, REF_ISPACKED)); 425} 426 427/* 428 * Read the loose references from the namespace dirname into dir 429 * (without recursing). dirname must end with '/'. dir must be the 430 * directory entry corresponding to dirname. 431 */ 432static voidloose_fill_ref_dir(struct ref_store *ref_store, 433struct ref_dir *dir,const char*dirname) 434{ 435struct files_ref_store *refs = 436files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 437DIR*d; 438struct dirent *de; 439int dirnamelen =strlen(dirname); 440struct strbuf refname; 441struct strbuf path = STRBUF_INIT; 442size_t path_baselen; 443 444files_ref_path(refs, &path, dirname); 445 path_baselen = path.len; 446 447 d =opendir(path.buf); 448if(!d) { 449strbuf_release(&path); 450return; 451} 452 453strbuf_init(&refname, dirnamelen +257); 454strbuf_add(&refname, dirname, dirnamelen); 455 456while((de =readdir(d)) != NULL) { 457struct object_id oid; 458struct stat st; 459int flag; 460 461if(de->d_name[0] =='.') 462continue; 463if(ends_with(de->d_name,".lock")) 464continue; 465strbuf_addstr(&refname, de->d_name); 466strbuf_addstr(&path, de->d_name); 467if(stat(path.buf, &st) <0) { 468;/* silently ignore */ 469}else if(S_ISDIR(st.st_mode)) { 470strbuf_addch(&refname,'/'); 471add_entry_to_dir(dir, 472create_dir_entry(dir->cache, refname.buf, 473 refname.len,1)); 474}else{ 475if(!refs_resolve_ref_unsafe(&refs->base, 476 refname.buf, 477 RESOLVE_REF_READING, 478 oid.hash, &flag)) { 479oidclr(&oid); 480 flag |= REF_ISBROKEN; 481}else if(is_null_oid(&oid)) { 482/* 483 * It is so astronomically unlikely 484 * that NULL_SHA1 is the SHA-1 of an 485 * actual object that we consider its 486 * appearance in a loose reference 487 * file to be repo corruption 488 * (probably due to a software bug). 489 */ 490 flag |= REF_ISBROKEN; 491} 492 493if(check_refname_format(refname.buf, 494 REFNAME_ALLOW_ONELEVEL)) { 495if(!refname_is_safe(refname.buf)) 496die("loose refname is dangerous:%s", refname.buf); 497oidclr(&oid); 498 flag |= REF_BAD_NAME | REF_ISBROKEN; 499} 500add_entry_to_dir(dir, 501create_ref_entry(refname.buf, &oid, flag)); 502} 503strbuf_setlen(&refname, dirnamelen); 504strbuf_setlen(&path, path_baselen); 505} 506strbuf_release(&refname); 507strbuf_release(&path); 508closedir(d); 509 510/* 511 * Manually add refs/bisect, which, being per-worktree, might 512 * not appear in the directory listing for refs/ in the main 513 * repo. 514 */ 515if(!strcmp(dirname,"refs/")) { 516int pos =search_ref_dir(dir,"refs/bisect/",12); 517 518if(pos <0) { 519struct ref_entry *child_entry =create_dir_entry( 520 dir->cache,"refs/bisect/",12,1); 521add_entry_to_dir(dir, child_entry); 522} 523} 524} 525 526static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 527{ 528if(!refs->loose) { 529/* 530 * Mark the top-level directory complete because we 531 * are about to read the only subdirectory that can 532 * hold references: 533 */ 534 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 535 536/* We're going to fill the top level ourselves: */ 537 refs->loose->root->flag &= ~REF_INCOMPLETE; 538 539/* 540 * Add an incomplete entry for "refs/" (to be filled 541 * lazily): 542 */ 543add_entry_to_dir(get_ref_dir(refs->loose->root), 544create_dir_entry(refs->loose,"refs/",5,1)); 545} 546return refs->loose; 547} 548 549/* 550 * Return the ref_entry for the given refname from the packed 551 * references. If it does not exist, return NULL. 552 */ 553static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 554const char*refname) 555{ 556returnfind_ref_entry(get_packed_refs(refs), refname); 557} 558 559/* 560 * A loose ref file doesn't exist; check for a packed ref. 561 */ 562static intresolve_packed_ref(struct files_ref_store *refs, 563const char*refname, 564unsigned char*sha1,unsigned int*flags) 565{ 566struct ref_entry *entry; 567 568/* 569 * The loose reference file does not exist; check for a packed 570 * reference. 571 */ 572 entry =get_packed_ref(refs, refname); 573if(entry) { 574hashcpy(sha1, entry->u.value.oid.hash); 575*flags |= REF_ISPACKED; 576return0; 577} 578/* refname is not a packed reference. */ 579return-1; 580} 581 582static intfiles_read_raw_ref(struct ref_store *ref_store, 583const char*refname,unsigned char*sha1, 584struct strbuf *referent,unsigned int*type) 585{ 586struct files_ref_store *refs = 587files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 588struct strbuf sb_contents = STRBUF_INIT; 589struct strbuf sb_path = STRBUF_INIT; 590const char*path; 591const char*buf; 592struct stat st; 593int fd; 594int ret = -1; 595int save_errno; 596int remaining_retries =3; 597 598*type =0; 599strbuf_reset(&sb_path); 600 601files_ref_path(refs, &sb_path, refname); 602 603 path = sb_path.buf; 604 605stat_ref: 606/* 607 * We might have to loop back here to avoid a race 608 * condition: first we lstat() the file, then we try 609 * to read it as a link or as a file. But if somebody 610 * changes the type of the file (file <-> directory 611 * <-> symlink) between the lstat() and reading, then 612 * we don't want to report that as an error but rather 613 * try again starting with the lstat(). 614 * 615 * We'll keep a count of the retries, though, just to avoid 616 * any confusing situation sending us into an infinite loop. 617 */ 618 619if(remaining_retries-- <=0) 620goto out; 621 622if(lstat(path, &st) <0) { 623if(errno != ENOENT) 624goto out; 625if(resolve_packed_ref(refs, refname, sha1, type)) { 626 errno = ENOENT; 627goto out; 628} 629 ret =0; 630goto out; 631} 632 633/* Follow "normalized" - ie "refs/.." symlinks by hand */ 634if(S_ISLNK(st.st_mode)) { 635strbuf_reset(&sb_contents); 636if(strbuf_readlink(&sb_contents, path,0) <0) { 637if(errno == ENOENT || errno == EINVAL) 638/* inconsistent with lstat; retry */ 639goto stat_ref; 640else 641goto out; 642} 643if(starts_with(sb_contents.buf,"refs/") && 644!check_refname_format(sb_contents.buf,0)) { 645strbuf_swap(&sb_contents, referent); 646*type |= REF_ISSYMREF; 647 ret =0; 648goto out; 649} 650/* 651 * It doesn't look like a refname; fall through to just 652 * treating it like a non-symlink, and reading whatever it 653 * points to. 654 */ 655} 656 657/* Is it a directory? */ 658if(S_ISDIR(st.st_mode)) { 659/* 660 * Even though there is a directory where the loose 661 * ref is supposed to be, there could still be a 662 * packed ref: 663 */ 664if(resolve_packed_ref(refs, refname, sha1, type)) { 665 errno = EISDIR; 666goto out; 667} 668 ret =0; 669goto out; 670} 671 672/* 673 * Anything else, just open it and try to use it as 674 * a ref 675 */ 676 fd =open(path, O_RDONLY); 677if(fd <0) { 678if(errno == ENOENT && !S_ISLNK(st.st_mode)) 679/* inconsistent with lstat; retry */ 680goto stat_ref; 681else 682goto out; 683} 684strbuf_reset(&sb_contents); 685if(strbuf_read(&sb_contents, fd,256) <0) { 686int save_errno = errno; 687close(fd); 688 errno = save_errno; 689goto out; 690} 691close(fd); 692strbuf_rtrim(&sb_contents); 693 buf = sb_contents.buf; 694if(starts_with(buf,"ref:")) { 695 buf +=4; 696while(isspace(*buf)) 697 buf++; 698 699strbuf_reset(referent); 700strbuf_addstr(referent, buf); 701*type |= REF_ISSYMREF; 702 ret =0; 703goto out; 704} 705 706/* 707 * Please note that FETCH_HEAD has additional 708 * data after the sha. 709 */ 710if(get_sha1_hex(buf, sha1) || 711(buf[40] !='\0'&& !isspace(buf[40]))) { 712*type |= REF_ISBROKEN; 713 errno = EINVAL; 714goto out; 715} 716 717 ret =0; 718 719out: 720 save_errno = errno; 721strbuf_release(&sb_path); 722strbuf_release(&sb_contents); 723 errno = save_errno; 724return ret; 725} 726 727static voidunlock_ref(struct ref_lock *lock) 728{ 729/* Do not free lock->lk -- atexit() still looks at them */ 730if(lock->lk) 731rollback_lock_file(lock->lk); 732free(lock->ref_name); 733free(lock); 734} 735 736/* 737 * Lock refname, without following symrefs, and set *lock_p to point 738 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 739 * and type similarly to read_raw_ref(). 740 * 741 * The caller must verify that refname is a "safe" reference name (in 742 * the sense of refname_is_safe()) before calling this function. 743 * 744 * If the reference doesn't already exist, verify that refname doesn't 745 * have a D/F conflict with any existing references. extras and skip 746 * are passed to refs_verify_refname_available() for this check. 747 * 748 * If mustexist is not set and the reference is not found or is 749 * broken, lock the reference anyway but clear sha1. 750 * 751 * Return 0 on success. On failure, write an error message to err and 752 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 753 * 754 * Implementation note: This function is basically 755 * 756 * lock reference 757 * read_raw_ref() 758 * 759 * but it includes a lot more code to 760 * - Deal with possible races with other processes 761 * - Avoid calling refs_verify_refname_available() when it can be 762 * avoided, namely if we were successfully able to read the ref 763 * - Generate informative error messages in the case of failure 764 */ 765static intlock_raw_ref(struct files_ref_store *refs, 766const char*refname,int mustexist, 767const struct string_list *extras, 768const struct string_list *skip, 769struct ref_lock **lock_p, 770struct strbuf *referent, 771unsigned int*type, 772struct strbuf *err) 773{ 774struct ref_lock *lock; 775struct strbuf ref_file = STRBUF_INIT; 776int attempts_remaining =3; 777int ret = TRANSACTION_GENERIC_ERROR; 778 779assert(err); 780files_assert_main_repository(refs,"lock_raw_ref"); 781 782*type =0; 783 784/* First lock the file so it can't change out from under us. */ 785 786*lock_p = lock =xcalloc(1,sizeof(*lock)); 787 788 lock->ref_name =xstrdup(refname); 789files_ref_path(refs, &ref_file, refname); 790 791retry: 792switch(safe_create_leading_directories(ref_file.buf)) { 793case SCLD_OK: 794break;/* success */ 795case SCLD_EXISTS: 796/* 797 * Suppose refname is "refs/foo/bar". We just failed 798 * to create the containing directory, "refs/foo", 799 * because there was a non-directory in the way. This 800 * indicates a D/F conflict, probably because of 801 * another reference such as "refs/foo". There is no 802 * reason to expect this error to be transitory. 803 */ 804if(refs_verify_refname_available(&refs->base, refname, 805 extras, skip, err)) { 806if(mustexist) { 807/* 808 * To the user the relevant error is 809 * that the "mustexist" reference is 810 * missing: 811 */ 812strbuf_reset(err); 813strbuf_addf(err,"unable to resolve reference '%s'", 814 refname); 815}else{ 816/* 817 * The error message set by 818 * refs_verify_refname_available() is 819 * OK. 820 */ 821 ret = TRANSACTION_NAME_CONFLICT; 822} 823}else{ 824/* 825 * The file that is in the way isn't a loose 826 * reference. Report it as a low-level 827 * failure. 828 */ 829strbuf_addf(err,"unable to create lock file%s.lock; " 830"non-directory in the way", 831 ref_file.buf); 832} 833goto error_return; 834case SCLD_VANISHED: 835/* Maybe another process was tidying up. Try again. */ 836if(--attempts_remaining >0) 837goto retry; 838/* fall through */ 839default: 840strbuf_addf(err,"unable to create directory for%s", 841 ref_file.buf); 842goto error_return; 843} 844 845if(!lock->lk) 846 lock->lk =xcalloc(1,sizeof(struct lock_file)); 847 848if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 849if(errno == ENOENT && --attempts_remaining >0) { 850/* 851 * Maybe somebody just deleted one of the 852 * directories leading to ref_file. Try 853 * again: 854 */ 855goto retry; 856}else{ 857unable_to_lock_message(ref_file.buf, errno, err); 858goto error_return; 859} 860} 861 862/* 863 * Now we hold the lock and can read the reference without 864 * fear that its value will change. 865 */ 866 867if(files_read_raw_ref(&refs->base, refname, 868 lock->old_oid.hash, referent, type)) { 869if(errno == ENOENT) { 870if(mustexist) { 871/* Garden variety missing reference. */ 872strbuf_addf(err,"unable to resolve reference '%s'", 873 refname); 874goto error_return; 875}else{ 876/* 877 * Reference is missing, but that's OK. We 878 * know that there is not a conflict with 879 * another loose reference because 880 * (supposing that we are trying to lock 881 * reference "refs/foo/bar"): 882 * 883 * - We were successfully able to create 884 * the lockfile refs/foo/bar.lock, so we 885 * know there cannot be a loose reference 886 * named "refs/foo". 887 * 888 * - We got ENOENT and not EISDIR, so we 889 * know that there cannot be a loose 890 * reference named "refs/foo/bar/baz". 891 */ 892} 893}else if(errno == EISDIR) { 894/* 895 * There is a directory in the way. It might have 896 * contained references that have been deleted. If 897 * we don't require that the reference already 898 * exists, try to remove the directory so that it 899 * doesn't cause trouble when we want to rename the 900 * lockfile into place later. 901 */ 902if(mustexist) { 903/* Garden variety missing reference. */ 904strbuf_addf(err,"unable to resolve reference '%s'", 905 refname); 906goto error_return; 907}else if(remove_dir_recursively(&ref_file, 908 REMOVE_DIR_EMPTY_ONLY)) { 909if(refs_verify_refname_available( 910&refs->base, refname, 911 extras, skip, err)) { 912/* 913 * The error message set by 914 * verify_refname_available() is OK. 915 */ 916 ret = TRANSACTION_NAME_CONFLICT; 917goto error_return; 918}else{ 919/* 920 * We can't delete the directory, 921 * but we also don't know of any 922 * references that it should 923 * contain. 924 */ 925strbuf_addf(err,"there is a non-empty directory '%s' " 926"blocking reference '%s'", 927 ref_file.buf, refname); 928goto error_return; 929} 930} 931}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 932strbuf_addf(err,"unable to resolve reference '%s': " 933"reference broken", refname); 934goto error_return; 935}else{ 936strbuf_addf(err,"unable to resolve reference '%s':%s", 937 refname,strerror(errno)); 938goto error_return; 939} 940 941/* 942 * If the ref did not exist and we are creating it, 943 * make sure there is no existing ref that conflicts 944 * with refname: 945 */ 946if(refs_verify_refname_available( 947&refs->base, refname, 948 extras, skip, err)) 949goto error_return; 950} 951 952 ret =0; 953goto out; 954 955error_return: 956unlock_ref(lock); 957*lock_p = NULL; 958 959out: 960strbuf_release(&ref_file); 961return ret; 962} 963 964static intfiles_peel_ref(struct ref_store *ref_store, 965const char*refname,unsigned char*sha1) 966{ 967struct files_ref_store *refs = 968files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 969"peel_ref"); 970int flag; 971unsigned char base[20]; 972 973if(current_ref_iter && current_ref_iter->refname == refname) { 974struct object_id peeled; 975 976if(ref_iterator_peel(current_ref_iter, &peeled)) 977return-1; 978hashcpy(sha1, peeled.hash); 979return0; 980} 981 982if(refs_read_ref_full(ref_store, refname, 983 RESOLVE_REF_READING, base, &flag)) 984return-1; 985 986/* 987 * If the reference is packed, read its ref_entry from the 988 * cache in the hope that we already know its peeled value. 989 * We only try this optimization on packed references because 990 * (a) forcing the filling of the loose reference cache could 991 * be expensive and (b) loose references anyway usually do not 992 * have REF_KNOWS_PEELED. 993 */ 994if(flag & REF_ISPACKED) { 995struct ref_entry *r =get_packed_ref(refs, refname); 996if(r) { 997if(peel_entry(r,0)) 998return-1; 999hashcpy(sha1, r->u.value.peeled.hash);1000return0;1001}1002}10031004returnpeel_object(base, sha1);1005}10061007struct files_ref_iterator {1008struct ref_iterator base;10091010struct packed_ref_cache *packed_ref_cache;1011struct ref_iterator *iter0;1012unsigned int flags;1013};10141015static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1016{1017struct files_ref_iterator *iter =1018(struct files_ref_iterator *)ref_iterator;1019int ok;10201021while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1022if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1023ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1024continue;10251026if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1027!ref_resolves_to_object(iter->iter0->refname,1028 iter->iter0->oid,1029 iter->iter0->flags))1030continue;10311032 iter->base.refname = iter->iter0->refname;1033 iter->base.oid = iter->iter0->oid;1034 iter->base.flags = iter->iter0->flags;1035return ITER_OK;1036}10371038 iter->iter0 = NULL;1039if(ref_iterator_abort(ref_iterator) != ITER_DONE)1040 ok = ITER_ERROR;10411042return ok;1043}10441045static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1046struct object_id *peeled)1047{1048struct files_ref_iterator *iter =1049(struct files_ref_iterator *)ref_iterator;10501051returnref_iterator_peel(iter->iter0, peeled);1052}10531054static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1055{1056struct files_ref_iterator *iter =1057(struct files_ref_iterator *)ref_iterator;1058int ok = ITER_DONE;10591060if(iter->iter0)1061 ok =ref_iterator_abort(iter->iter0);10621063release_packed_ref_cache(iter->packed_ref_cache);1064base_ref_iterator_free(ref_iterator);1065return ok;1066}10671068static struct ref_iterator_vtable files_ref_iterator_vtable = {1069 files_ref_iterator_advance,1070 files_ref_iterator_peel,1071 files_ref_iterator_abort1072};10731074static struct ref_iterator *files_ref_iterator_begin(1075struct ref_store *ref_store,1076const char*prefix,unsigned int flags)1077{1078struct files_ref_store *refs;1079struct ref_iterator *loose_iter, *packed_iter;1080struct files_ref_iterator *iter;1081struct ref_iterator *ref_iterator;1082unsigned int required_flags = REF_STORE_READ;10831084if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1085 required_flags |= REF_STORE_ODB;10861087 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");10881089 iter =xcalloc(1,sizeof(*iter));1090 ref_iterator = &iter->base;1091base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10921093/*1094 * We must make sure that all loose refs are read before1095 * accessing the packed-refs file; this avoids a race1096 * condition if loose refs are migrated to the packed-refs1097 * file by a simultaneous process, but our in-memory view is1098 * from before the migration. We ensure this as follows:1099 * First, we call start the loose refs iteration with its1100 * `prime_ref` argument set to true. This causes the loose1101 * references in the subtree to be pre-read into the cache.1102 * (If they've already been read, that's OK; we only need to1103 * guarantee that they're read before the packed refs, not1104 * *how much* before.) After that, we call1105 * get_packed_ref_cache(), which internally checks whether the1106 * packed-ref cache is up to date with what is on disk, and1107 * re-reads it if not.1108 */11091110 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1111 prefix,1);11121113 iter->packed_ref_cache =get_packed_ref_cache(refs);1114acquire_packed_ref_cache(iter->packed_ref_cache);1115 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1116 prefix,0);11171118 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1119 iter->flags = flags;11201121return ref_iterator;1122}11231124/*1125 * Verify that the reference locked by lock has the value old_sha1.1126 * Fail if the reference doesn't exist and mustexist is set. Return 01127 * on success. On error, write an error message to err, set errno, and1128 * return a negative value.1129 */1130static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1131const unsigned char*old_sha1,int mustexist,1132struct strbuf *err)1133{1134assert(err);11351136if(refs_read_ref_full(ref_store, lock->ref_name,1137 mustexist ? RESOLVE_REF_READING :0,1138 lock->old_oid.hash, NULL)) {1139if(old_sha1) {1140int save_errno = errno;1141strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1142 errno = save_errno;1143return-1;1144}else{1145oidclr(&lock->old_oid);1146return0;1147}1148}1149if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1150strbuf_addf(err,"ref '%s' is at%sbut expected%s",1151 lock->ref_name,1152oid_to_hex(&lock->old_oid),1153sha1_to_hex(old_sha1));1154 errno = EBUSY;1155return-1;1156}1157return0;1158}11591160static intremove_empty_directories(struct strbuf *path)1161{1162/*1163 * we want to create a file but there is a directory there;1164 * if that is an empty directory (or a directory that contains1165 * only empty directories), remove them.1166 */1167returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1168}11691170static intcreate_reflock(const char*path,void*cb)1171{1172struct lock_file *lk = cb;11731174returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1175}11761177/*1178 * Locks a ref returning the lock on success and NULL on failure.1179 * On failure errno is set to something meaningful.1180 */1181static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1182const char*refname,1183const unsigned char*old_sha1,1184const struct string_list *extras,1185const struct string_list *skip,1186unsigned int flags,int*type,1187struct strbuf *err)1188{1189struct strbuf ref_file = STRBUF_INIT;1190struct ref_lock *lock;1191int last_errno =0;1192int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1193int resolve_flags = RESOLVE_REF_NO_RECURSE;1194int resolved;11951196files_assert_main_repository(refs,"lock_ref_sha1_basic");1197assert(err);11981199 lock =xcalloc(1,sizeof(struct ref_lock));12001201if(mustexist)1202 resolve_flags |= RESOLVE_REF_READING;1203if(flags & REF_DELETING)1204 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12051206files_ref_path(refs, &ref_file, refname);1207 resolved = !!refs_resolve_ref_unsafe(&refs->base,1208 refname, resolve_flags,1209 lock->old_oid.hash, type);1210if(!resolved && errno == EISDIR) {1211/*1212 * we are trying to lock foo but we used to1213 * have foo/bar which now does not exist;1214 * it is normal for the empty directory 'foo'1215 * to remain.1216 */1217if(remove_empty_directories(&ref_file)) {1218 last_errno = errno;1219if(!refs_verify_refname_available(1220&refs->base,1221 refname, extras, skip, err))1222strbuf_addf(err,"there are still refs under '%s'",1223 refname);1224goto error_return;1225}1226 resolved = !!refs_resolve_ref_unsafe(&refs->base,1227 refname, resolve_flags,1228 lock->old_oid.hash, type);1229}1230if(!resolved) {1231 last_errno = errno;1232if(last_errno != ENOTDIR ||1233!refs_verify_refname_available(&refs->base, refname,1234 extras, skip, err))1235strbuf_addf(err,"unable to resolve reference '%s':%s",1236 refname,strerror(last_errno));12371238goto error_return;1239}12401241/*1242 * If the ref did not exist and we are creating it, make sure1243 * there is no existing packed ref whose name begins with our1244 * refname, nor a packed ref whose name is a proper prefix of1245 * our refname.1246 */1247if(is_null_oid(&lock->old_oid) &&1248refs_verify_refname_available(&refs->base, refname,1249 extras, skip, err)) {1250 last_errno = ENOTDIR;1251goto error_return;1252}12531254 lock->lk =xcalloc(1,sizeof(struct lock_file));12551256 lock->ref_name =xstrdup(refname);12571258if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1259 last_errno = errno;1260unable_to_lock_message(ref_file.buf, errno, err);1261goto error_return;1262}12631264if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1265 last_errno = errno;1266goto error_return;1267}1268goto out;12691270 error_return:1271unlock_ref(lock);1272 lock = NULL;12731274 out:1275strbuf_release(&ref_file);1276 errno = last_errno;1277return lock;1278}12791280/*1281 * Write an entry to the packed-refs file for the specified refname.1282 * If peeled is non-NULL, write it as the entry's peeled value.1283 */1284static voidwrite_packed_entry(FILE*fh,const char*refname,1285const unsigned char*sha1,1286const unsigned char*peeled)1287{1288fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1289if(peeled)1290fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1291}12921293/*1294 * Lock the packed-refs file for writing. Flags is passed to1295 * hold_lock_file_for_update(). Return 0 on success. On errors, set1296 * errno appropriately and return a nonzero value.1297 */1298static intlock_packed_refs(struct files_ref_store *refs,int flags)1299{1300static int timeout_configured =0;1301static int timeout_value =1000;1302struct packed_ref_cache *packed_ref_cache;13031304files_assert_main_repository(refs,"lock_packed_refs");13051306if(!timeout_configured) {1307git_config_get_int("core.packedrefstimeout", &timeout_value);1308 timeout_configured =1;1309}13101311if(hold_lock_file_for_update_timeout(1312&refs->packed_refs_lock,files_packed_refs_path(refs),1313 flags, timeout_value) <0)1314return-1;1315/*1316 * Get the current packed-refs while holding the lock. It is1317 * important that we call `get_packed_ref_cache()` before1318 * setting `packed_ref_cache->lock`, because otherwise the1319 * former will see that the file is locked and assume that the1320 * cache can't be stale.1321 */1322 packed_ref_cache =get_packed_ref_cache(refs);1323/* Increment the reference count to prevent it from being freed: */1324acquire_packed_ref_cache(packed_ref_cache);1325return0;1326}13271328/*1329 * Write the current version of the packed refs cache from memory to1330 * disk. The packed-refs file must already be locked for writing (see1331 * lock_packed_refs()). Return zero on success. On errors, set errno1332 * and return a nonzero value1333 */1334static intcommit_packed_refs(struct files_ref_store *refs)1335{1336struct packed_ref_cache *packed_ref_cache =1337get_packed_ref_cache(refs);1338int ok, error =0;1339int save_errno =0;1340FILE*out;1341struct ref_iterator *iter;13421343files_assert_main_repository(refs,"commit_packed_refs");13441345if(!is_lock_file_locked(&refs->packed_refs_lock))1346die("BUG: packed-refs not locked");13471348 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1349if(!out)1350die_errno("unable to fdopen packed-refs descriptor");13511352fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13531354 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1355while((ok =ref_iterator_advance(iter)) == ITER_OK) {1356struct object_id peeled;1357int peel_error =ref_iterator_peel(iter, &peeled);13581359write_packed_entry(out, iter->refname, iter->oid->hash,1360 peel_error ? NULL : peeled.hash);1361}13621363if(ok != ITER_DONE)1364die("error while iterating over references");13651366if(commit_lock_file(&refs->packed_refs_lock)) {1367 save_errno = errno;1368 error = -1;1369}1370release_packed_ref_cache(packed_ref_cache);1371 errno = save_errno;1372return error;1373}13741375/*1376 * Rollback the lockfile for the packed-refs file, and discard the1377 * in-memory packed reference cache. (The packed-refs file will be1378 * read anew if it is needed again after this function is called.)1379 */1380static voidrollback_packed_refs(struct files_ref_store *refs)1381{1382struct packed_ref_cache *packed_ref_cache =1383get_packed_ref_cache(refs);13841385files_assert_main_repository(refs,"rollback_packed_refs");13861387if(!is_lock_file_locked(&refs->packed_refs_lock))1388die("BUG: packed-refs not locked");1389rollback_lock_file(&refs->packed_refs_lock);1390release_packed_ref_cache(packed_ref_cache);1391clear_packed_ref_cache(refs);1392}13931394struct ref_to_prune {1395struct ref_to_prune *next;1396unsigned char sha1[20];1397char name[FLEX_ARRAY];1398};13991400enum{1401 REMOVE_EMPTY_PARENTS_REF =0x01,1402 REMOVE_EMPTY_PARENTS_REFLOG =0x021403};14041405/*1406 * Remove empty parent directories associated with the specified1407 * reference and/or its reflog, but spare [logs/]refs/ and immediate1408 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1409 * REMOVE_EMPTY_PARENTS_REFLOG.1410 */1411static voidtry_remove_empty_parents(struct files_ref_store *refs,1412const char*refname,1413unsigned int flags)1414{1415struct strbuf buf = STRBUF_INIT;1416struct strbuf sb = STRBUF_INIT;1417char*p, *q;1418int i;14191420strbuf_addstr(&buf, refname);1421 p = buf.buf;1422for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1423while(*p && *p !='/')1424 p++;1425/* tolerate duplicate slashes; see check_refname_format() */1426while(*p =='/')1427 p++;1428}1429 q = buf.buf + buf.len;1430while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1431while(q > p && *q !='/')1432 q--;1433while(q > p && *(q-1) =='/')1434 q--;1435if(q == p)1436break;1437strbuf_setlen(&buf, q - buf.buf);14381439strbuf_reset(&sb);1440files_ref_path(refs, &sb, buf.buf);1441if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1442 flags &= ~REMOVE_EMPTY_PARENTS_REF;14431444strbuf_reset(&sb);1445files_reflog_path(refs, &sb, buf.buf);1446if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1447 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1448}1449strbuf_release(&buf);1450strbuf_release(&sb);1451}14521453/* make sure nobody touched the ref, and unlink */1454static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1455{1456struct ref_transaction *transaction;1457struct strbuf err = STRBUF_INIT;14581459if(check_refname_format(r->name,0))1460return;14611462 transaction =ref_store_transaction_begin(&refs->base, &err);1463if(!transaction ||1464ref_transaction_delete(transaction, r->name, r->sha1,1465 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1466ref_transaction_commit(transaction, &err)) {1467ref_transaction_free(transaction);1468error("%s", err.buf);1469strbuf_release(&err);1470return;1471}1472ref_transaction_free(transaction);1473strbuf_release(&err);1474}14751476static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1477{1478while(r) {1479prune_ref(refs, r);1480 r = r->next;1481}1482}14831484/*1485 * Return true if the specified reference should be packed.1486 */1487static intshould_pack_ref(const char*refname,1488const struct object_id *oid,unsigned int ref_flags,1489unsigned int pack_flags)1490{1491/* Do not pack per-worktree refs: */1492if(ref_type(refname) != REF_TYPE_NORMAL)1493return0;14941495/* Do not pack non-tags unless PACK_REFS_ALL is set: */1496if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1497return0;14981499/* Do not pack symbolic refs: */1500if(ref_flags & REF_ISSYMREF)1501return0;15021503/* Do not pack broken refs: */1504if(!ref_resolves_to_object(refname, oid, ref_flags))1505return0;15061507return1;1508}15091510static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1511{1512struct files_ref_store *refs =1513files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1514"pack_refs");1515struct ref_iterator *iter;1516struct ref_dir *packed_refs;1517int ok;1518struct ref_to_prune *refs_to_prune = NULL;15191520lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1521 packed_refs =get_packed_refs(refs);15221523 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1524while((ok =ref_iterator_advance(iter)) == ITER_OK) {1525/*1526 * If the loose reference can be packed, add an entry1527 * in the packed ref cache. If the reference should be1528 * pruned, also add it to refs_to_prune.1529 */1530struct ref_entry *packed_entry;15311532if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1533 flags))1534continue;15351536/*1537 * Create an entry in the packed-refs cache equivalent1538 * to the one from the loose ref cache, except that1539 * we don't copy the peeled status, because we want it1540 * to be re-peeled.1541 */1542 packed_entry =find_ref_entry(packed_refs, iter->refname);1543if(packed_entry) {1544/* Overwrite existing packed entry with info from loose entry */1545 packed_entry->flag = REF_ISPACKED;1546oidcpy(&packed_entry->u.value.oid, iter->oid);1547}else{1548 packed_entry =create_ref_entry(iter->refname, iter->oid,1549 REF_ISPACKED);1550add_ref_entry(packed_refs, packed_entry);1551}1552oidclr(&packed_entry->u.value.peeled);15531554/* Schedule the loose reference for pruning if requested. */1555if((flags & PACK_REFS_PRUNE)) {1556struct ref_to_prune *n;1557FLEX_ALLOC_STR(n, name, iter->refname);1558hashcpy(n->sha1, iter->oid->hash);1559 n->next = refs_to_prune;1560 refs_to_prune = n;1561}1562}1563if(ok != ITER_DONE)1564die("error while iterating over references");15651566if(commit_packed_refs(refs))1567die_errno("unable to overwrite old ref-pack file");15681569prune_refs(refs, refs_to_prune);1570return0;1571}15721573/*1574 * Rewrite the packed-refs file, omitting any refs listed in1575 * 'refnames'. On error, leave packed-refs unchanged, write an error1576 * message to 'err', and return a nonzero value.1577 *1578 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1579 */1580static intrepack_without_refs(struct files_ref_store *refs,1581struct string_list *refnames,struct strbuf *err)1582{1583struct ref_dir *packed;1584struct string_list_item *refname;1585int ret, needs_repacking =0, removed =0;15861587files_assert_main_repository(refs,"repack_without_refs");1588assert(err);15891590/* Look for a packed ref */1591for_each_string_list_item(refname, refnames) {1592if(get_packed_ref(refs, refname->string)) {1593 needs_repacking =1;1594break;1595}1596}15971598/* Avoid locking if we have nothing to do */1599if(!needs_repacking)1600return0;/* no refname exists in packed refs */16011602if(lock_packed_refs(refs,0)) {1603unable_to_lock_message(files_packed_refs_path(refs), errno, err);1604return-1;1605}1606 packed =get_packed_refs(refs);16071608/* Remove refnames from the cache */1609for_each_string_list_item(refname, refnames)1610if(remove_entry_from_dir(packed, refname->string) != -1)1611 removed =1;1612if(!removed) {1613/*1614 * All packed entries disappeared while we were1615 * acquiring the lock.1616 */1617rollback_packed_refs(refs);1618return0;1619}16201621/* Write what remains */1622 ret =commit_packed_refs(refs);1623if(ret)1624strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1625strerror(errno));1626return ret;1627}16281629static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1630struct string_list *refnames,unsigned int flags)1631{1632struct files_ref_store *refs =1633files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1634struct strbuf err = STRBUF_INIT;1635int i, result =0;16361637if(!refnames->nr)1638return0;16391640 result =repack_without_refs(refs, refnames, &err);1641if(result) {1642/*1643 * If we failed to rewrite the packed-refs file, then1644 * it is unsafe to try to remove loose refs, because1645 * doing so might expose an obsolete packed value for1646 * a reference that might even point at an object that1647 * has been garbage collected.1648 */1649if(refnames->nr ==1)1650error(_("could not delete reference%s:%s"),1651 refnames->items[0].string, err.buf);1652else1653error(_("could not delete references:%s"), err.buf);16541655goto out;1656}16571658for(i =0; i < refnames->nr; i++) {1659const char*refname = refnames->items[i].string;16601661if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1662 result |=error(_("could not remove reference%s"), refname);1663}16641665out:1666strbuf_release(&err);1667return result;1668}16691670/*1671 * People using contrib's git-new-workdir have .git/logs/refs ->1672 * /some/other/path/.git/logs/refs, and that may live on another device.1673 *1674 * IOW, to avoid cross device rename errors, the temporary renamed log must1675 * live into logs/refs.1676 */1677#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16781679struct rename_cb {1680const char*tmp_renamed_log;1681int true_errno;1682};16831684static intrename_tmp_log_callback(const char*path,void*cb_data)1685{1686struct rename_cb *cb = cb_data;16871688if(rename(cb->tmp_renamed_log, path)) {1689/*1690 * rename(a, b) when b is an existing directory ought1691 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1692 * Sheesh. Record the true errno for error reporting,1693 * but report EISDIR to raceproof_create_file() so1694 * that it knows to retry.1695 */1696 cb->true_errno = errno;1697if(errno == ENOTDIR)1698 errno = EISDIR;1699return-1;1700}else{1701return0;1702}1703}17041705static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1706{1707struct strbuf path = STRBUF_INIT;1708struct strbuf tmp = STRBUF_INIT;1709struct rename_cb cb;1710int ret;17111712files_reflog_path(refs, &path, newrefname);1713files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1714 cb.tmp_renamed_log = tmp.buf;1715 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1716if(ret) {1717if(errno == EISDIR)1718error("directory not empty:%s", path.buf);1719else1720error("unable to move logfile%sto%s:%s",1721 tmp.buf, path.buf,1722strerror(cb.true_errno));1723}17241725strbuf_release(&path);1726strbuf_release(&tmp);1727return ret;1728}17291730static intwrite_ref_to_lockfile(struct ref_lock *lock,1731const struct object_id *oid,struct strbuf *err);1732static intcommit_ref_update(struct files_ref_store *refs,1733struct ref_lock *lock,1734const struct object_id *oid,const char*logmsg,1735struct strbuf *err);17361737static intfiles_rename_ref(struct ref_store *ref_store,1738const char*oldrefname,const char*newrefname,1739const char*logmsg)1740{1741struct files_ref_store *refs =1742files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1743struct object_id oid, orig_oid;1744int flag =0, logmoved =0;1745struct ref_lock *lock;1746struct stat loginfo;1747struct strbuf sb_oldref = STRBUF_INIT;1748struct strbuf sb_newref = STRBUF_INIT;1749struct strbuf tmp_renamed_log = STRBUF_INIT;1750int log, ret;1751struct strbuf err = STRBUF_INIT;17521753files_reflog_path(refs, &sb_oldref, oldrefname);1754files_reflog_path(refs, &sb_newref, newrefname);1755files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17561757 log = !lstat(sb_oldref.buf, &loginfo);1758if(log &&S_ISLNK(loginfo.st_mode)) {1759 ret =error("reflog for%sis a symlink", oldrefname);1760goto out;1761}17621763if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1764 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1765 orig_oid.hash, &flag)) {1766 ret =error("refname%snot found", oldrefname);1767goto out;1768}17691770if(flag & REF_ISSYMREF) {1771 ret =error("refname%sis a symbolic ref, renaming it is not supported",1772 oldrefname);1773goto out;1774}1775if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1776 ret =1;1777goto out;1778}17791780if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1781 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1782 oldrefname,strerror(errno));1783goto out;1784}17851786if(refs_delete_ref(&refs->base, logmsg, oldrefname,1787 orig_oid.hash, REF_NODEREF)) {1788error("unable to delete old%s", oldrefname);1789goto rollback;1790}17911792/*1793 * Since we are doing a shallow lookup, oid is not the1794 * correct value to pass to delete_ref as old_oid. But that1795 * doesn't matter, because an old_oid check wouldn't add to1796 * the safety anyway; we want to delete the reference whatever1797 * its current value.1798 */1799if(!refs_read_ref_full(&refs->base, newrefname,1800 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1801 oid.hash, NULL) &&1802refs_delete_ref(&refs->base, NULL, newrefname,1803 NULL, REF_NODEREF)) {1804if(errno == EISDIR) {1805struct strbuf path = STRBUF_INIT;1806int result;18071808files_ref_path(refs, &path, newrefname);1809 result =remove_empty_directories(&path);1810strbuf_release(&path);18111812if(result) {1813error("Directory not empty:%s", newrefname);1814goto rollback;1815}1816}else{1817error("unable to delete existing%s", newrefname);1818goto rollback;1819}1820}18211822if(log &&rename_tmp_log(refs, newrefname))1823goto rollback;18241825 logmoved = log;18261827 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1828 REF_NODEREF, NULL, &err);1829if(!lock) {1830error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1831strbuf_release(&err);1832goto rollback;1833}1834oidcpy(&lock->old_oid, &orig_oid);18351836if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1837commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1838error("unable to write current sha1 into%s:%s", newrefname, err.buf);1839strbuf_release(&err);1840goto rollback;1841}18421843 ret =0;1844goto out;18451846 rollback:1847 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1848 REF_NODEREF, NULL, &err);1849if(!lock) {1850error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1851strbuf_release(&err);1852goto rollbacklog;1853}18541855 flag = log_all_ref_updates;1856 log_all_ref_updates = LOG_REFS_NONE;1857if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1858commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1859error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1860strbuf_release(&err);1861}1862 log_all_ref_updates = flag;18631864 rollbacklog:1865if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1866error("unable to restore logfile%sfrom%s:%s",1867 oldrefname, newrefname,strerror(errno));1868if(!logmoved && log &&1869rename(tmp_renamed_log.buf, sb_oldref.buf))1870error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1871 oldrefname,strerror(errno));1872 ret =1;1873 out:1874strbuf_release(&sb_newref);1875strbuf_release(&sb_oldref);1876strbuf_release(&tmp_renamed_log);18771878return ret;1879}18801881static intclose_ref(struct ref_lock *lock)1882{1883if(close_lock_file(lock->lk))1884return-1;1885return0;1886}18871888static intcommit_ref(struct ref_lock *lock)1889{1890char*path =get_locked_file_path(lock->lk);1891struct stat st;18921893if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1894/*1895 * There is a directory at the path we want to rename1896 * the lockfile to. Hopefully it is empty; try to1897 * delete it.1898 */1899size_t len =strlen(path);1900struct strbuf sb_path = STRBUF_INIT;19011902strbuf_attach(&sb_path, path, len, len);19031904/*1905 * If this fails, commit_lock_file() will also fail1906 * and will report the problem.1907 */1908remove_empty_directories(&sb_path);1909strbuf_release(&sb_path);1910}else{1911free(path);1912}19131914if(commit_lock_file(lock->lk))1915return-1;1916return0;1917}19181919static intopen_or_create_logfile(const char*path,void*cb)1920{1921int*fd = cb;19221923*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1924return(*fd <0) ? -1:0;1925}19261927/*1928 * Create a reflog for a ref. If force_create = 0, only create the1929 * reflog for certain refs (those for which should_autocreate_reflog1930 * returns non-zero). Otherwise, create it regardless of the reference1931 * name. If the logfile already existed or was created, return 0 and1932 * set *logfd to the file descriptor opened for appending to the file.1933 * If no logfile exists and we decided not to create one, return 0 and1934 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1935 * return -1.1936 */1937static intlog_ref_setup(struct files_ref_store *refs,1938const char*refname,int force_create,1939int*logfd,struct strbuf *err)1940{1941struct strbuf logfile_sb = STRBUF_INIT;1942char*logfile;19431944files_reflog_path(refs, &logfile_sb, refname);1945 logfile =strbuf_detach(&logfile_sb, NULL);19461947if(force_create ||should_autocreate_reflog(refname)) {1948if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1949if(errno == ENOENT)1950strbuf_addf(err,"unable to create directory for '%s': "1951"%s", logfile,strerror(errno));1952else if(errno == EISDIR)1953strbuf_addf(err,"there are still logs under '%s'",1954 logfile);1955else1956strbuf_addf(err,"unable to append to '%s':%s",1957 logfile,strerror(errno));19581959goto error;1960}1961}else{1962*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1963if(*logfd <0) {1964if(errno == ENOENT || errno == EISDIR) {1965/*1966 * The logfile doesn't already exist,1967 * but that is not an error; it only1968 * means that we won't write log1969 * entries to it.1970 */1971;1972}else{1973strbuf_addf(err,"unable to append to '%s':%s",1974 logfile,strerror(errno));1975goto error;1976}1977}1978}19791980if(*logfd >=0)1981adjust_shared_perm(logfile);19821983free(logfile);1984return0;19851986error:1987free(logfile);1988return-1;1989}19901991static intfiles_create_reflog(struct ref_store *ref_store,1992const char*refname,int force_create,1993struct strbuf *err)1994{1995struct files_ref_store *refs =1996files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1997int fd;19981999if(log_ref_setup(refs, refname, force_create, &fd, err))2000return-1;20012002if(fd >=0)2003close(fd);20042005return0;2006}20072008static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2009const struct object_id *new_oid,2010const char*committer,const char*msg)2011{2012int msglen, written;2013unsigned maxlen, len;2014char*logrec;20152016 msglen = msg ?strlen(msg) :0;2017 maxlen =strlen(committer) + msglen +100;2018 logrec =xmalloc(maxlen);2019 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2020oid_to_hex(old_oid),2021oid_to_hex(new_oid),2022 committer);2023if(msglen)2024 len +=copy_reflog_msg(logrec + len -1, msg) -1;20252026 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2027free(logrec);2028if(written != len)2029return-1;20302031return0;2032}20332034static intfiles_log_ref_write(struct files_ref_store *refs,2035const char*refname,const struct object_id *old_oid,2036const struct object_id *new_oid,const char*msg,2037int flags,struct strbuf *err)2038{2039int logfd, result;20402041if(log_all_ref_updates == LOG_REFS_UNSET)2042 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20432044 result =log_ref_setup(refs, refname,2045 flags & REF_FORCE_CREATE_REFLOG,2046&logfd, err);20472048if(result)2049return result;20502051if(logfd <0)2052return0;2053 result =log_ref_write_fd(logfd, old_oid, new_oid,2054git_committer_info(0), msg);2055if(result) {2056struct strbuf sb = STRBUF_INIT;2057int save_errno = errno;20582059files_reflog_path(refs, &sb, refname);2060strbuf_addf(err,"unable to append to '%s':%s",2061 sb.buf,strerror(save_errno));2062strbuf_release(&sb);2063close(logfd);2064return-1;2065}2066if(close(logfd)) {2067struct strbuf sb = STRBUF_INIT;2068int save_errno = errno;20692070files_reflog_path(refs, &sb, refname);2071strbuf_addf(err,"unable to append to '%s':%s",2072 sb.buf,strerror(save_errno));2073strbuf_release(&sb);2074return-1;2075}2076return0;2077}20782079/*2080 * Write sha1 into the open lockfile, then close the lockfile. On2081 * errors, rollback the lockfile, fill in *err and2082 * return -1.2083 */2084static intwrite_ref_to_lockfile(struct ref_lock *lock,2085const struct object_id *oid,struct strbuf *err)2086{2087static char term ='\n';2088struct object *o;2089int fd;20902091 o =parse_object(oid);2092if(!o) {2093strbuf_addf(err,2094"trying to write ref '%s' with nonexistent object%s",2095 lock->ref_name,oid_to_hex(oid));2096unlock_ref(lock);2097return-1;2098}2099if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2100strbuf_addf(err,2101"trying to write non-commit object%sto branch '%s'",2102oid_to_hex(oid), lock->ref_name);2103unlock_ref(lock);2104return-1;2105}2106 fd =get_lock_file_fd(lock->lk);2107if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2108write_in_full(fd, &term,1) !=1||2109close_ref(lock) <0) {2110strbuf_addf(err,2111"couldn't write '%s'",get_lock_file_path(lock->lk));2112unlock_ref(lock);2113return-1;2114}2115return0;2116}21172118/*2119 * Commit a change to a loose reference that has already been written2120 * to the loose reference lockfile. Also update the reflogs if2121 * necessary, using the specified lockmsg (which can be NULL).2122 */2123static intcommit_ref_update(struct files_ref_store *refs,2124struct ref_lock *lock,2125const struct object_id *oid,const char*logmsg,2126struct strbuf *err)2127{2128files_assert_main_repository(refs,"commit_ref_update");21292130clear_loose_ref_cache(refs);2131if(files_log_ref_write(refs, lock->ref_name,2132&lock->old_oid, oid,2133 logmsg,0, err)) {2134char*old_msg =strbuf_detach(err, NULL);2135strbuf_addf(err,"cannot update the ref '%s':%s",2136 lock->ref_name, old_msg);2137free(old_msg);2138unlock_ref(lock);2139return-1;2140}21412142if(strcmp(lock->ref_name,"HEAD") !=0) {2143/*2144 * Special hack: If a branch is updated directly and HEAD2145 * points to it (may happen on the remote side of a push2146 * for example) then logically the HEAD reflog should be2147 * updated too.2148 * A generic solution implies reverse symref information,2149 * but finding all symrefs pointing to the given branch2150 * would be rather costly for this rare event (the direct2151 * update of a branch) to be worth it. So let's cheat and2152 * check with HEAD only which should cover 99% of all usage2153 * scenarios (even 100% of the default ones).2154 */2155struct object_id head_oid;2156int head_flag;2157const char*head_ref;21582159 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2160 RESOLVE_REF_READING,2161 head_oid.hash, &head_flag);2162if(head_ref && (head_flag & REF_ISSYMREF) &&2163!strcmp(head_ref, lock->ref_name)) {2164struct strbuf log_err = STRBUF_INIT;2165if(files_log_ref_write(refs,"HEAD",2166&lock->old_oid, oid,2167 logmsg,0, &log_err)) {2168error("%s", log_err.buf);2169strbuf_release(&log_err);2170}2171}2172}21732174if(commit_ref(lock)) {2175strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2176unlock_ref(lock);2177return-1;2178}21792180unlock_ref(lock);2181return0;2182}21832184static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2185{2186int ret = -1;2187#ifndef NO_SYMLINK_HEAD2188char*ref_path =get_locked_file_path(lock->lk);2189unlink(ref_path);2190 ret =symlink(target, ref_path);2191free(ref_path);21922193if(ret)2194fprintf(stderr,"no symlink - falling back to symbolic ref\n");2195#endif2196return ret;2197}21982199static voidupdate_symref_reflog(struct files_ref_store *refs,2200struct ref_lock *lock,const char*refname,2201const char*target,const char*logmsg)2202{2203struct strbuf err = STRBUF_INIT;2204struct object_id new_oid;2205if(logmsg &&2206!refs_read_ref_full(&refs->base, target,2207 RESOLVE_REF_READING, new_oid.hash, NULL) &&2208files_log_ref_write(refs, refname, &lock->old_oid,2209&new_oid, logmsg,0, &err)) {2210error("%s", err.buf);2211strbuf_release(&err);2212}2213}22142215static intcreate_symref_locked(struct files_ref_store *refs,2216struct ref_lock *lock,const char*refname,2217const char*target,const char*logmsg)2218{2219if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2220update_symref_reflog(refs, lock, refname, target, logmsg);2221return0;2222}22232224if(!fdopen_lock_file(lock->lk,"w"))2225returnerror("unable to fdopen%s:%s",2226 lock->lk->tempfile.filename.buf,strerror(errno));22272228update_symref_reflog(refs, lock, refname, target, logmsg);22292230/* no error check; commit_ref will check ferror */2231fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2232if(commit_ref(lock) <0)2233returnerror("unable to write symref for%s:%s", refname,2234strerror(errno));2235return0;2236}22372238static intfiles_create_symref(struct ref_store *ref_store,2239const char*refname,const char*target,2240const char*logmsg)2241{2242struct files_ref_store *refs =2243files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2244struct strbuf err = STRBUF_INIT;2245struct ref_lock *lock;2246int ret;22472248 lock =lock_ref_sha1_basic(refs, refname, NULL,2249 NULL, NULL, REF_NODEREF, NULL,2250&err);2251if(!lock) {2252error("%s", err.buf);2253strbuf_release(&err);2254return-1;2255}22562257 ret =create_symref_locked(refs, lock, refname, target, logmsg);2258unlock_ref(lock);2259return ret;2260}22612262static intfiles_reflog_exists(struct ref_store *ref_store,2263const char*refname)2264{2265struct files_ref_store *refs =2266files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2267struct strbuf sb = STRBUF_INIT;2268struct stat st;2269int ret;22702271files_reflog_path(refs, &sb, refname);2272 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2273strbuf_release(&sb);2274return ret;2275}22762277static intfiles_delete_reflog(struct ref_store *ref_store,2278const char*refname)2279{2280struct files_ref_store *refs =2281files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2282struct strbuf sb = STRBUF_INIT;2283int ret;22842285files_reflog_path(refs, &sb, refname);2286 ret =remove_path(sb.buf);2287strbuf_release(&sb);2288return ret;2289}22902291static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2292{2293struct object_id ooid, noid;2294char*email_end, *message;2295 timestamp_t timestamp;2296int tz;2297const char*p = sb->buf;22982299/* old SP new SP name <email> SP time TAB msg LF */2300if(!sb->len || sb->buf[sb->len -1] !='\n'||2301parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2302parse_oid_hex(p, &noid, &p) || *p++ !=' '||2303!(email_end =strchr(p,'>')) ||2304 email_end[1] !=' '||2305!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2306!message || message[0] !=' '||2307(message[1] !='+'&& message[1] !='-') ||2308!isdigit(message[2]) || !isdigit(message[3]) ||2309!isdigit(message[4]) || !isdigit(message[5]))2310return0;/* corrupt? */2311 email_end[1] ='\0';2312 tz =strtol(message +1, NULL,10);2313if(message[6] !='\t')2314 message +=6;2315else2316 message +=7;2317returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2318}23192320static char*find_beginning_of_line(char*bob,char*scan)2321{2322while(bob < scan && *(--scan) !='\n')2323;/* keep scanning backwards */2324/*2325 * Return either beginning of the buffer, or LF at the end of2326 * the previous line.2327 */2328return scan;2329}23302331static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2332const char*refname,2333 each_reflog_ent_fn fn,2334void*cb_data)2335{2336struct files_ref_store *refs =2337files_downcast(ref_store, REF_STORE_READ,2338"for_each_reflog_ent_reverse");2339struct strbuf sb = STRBUF_INIT;2340FILE*logfp;2341long pos;2342int ret =0, at_tail =1;23432344files_reflog_path(refs, &sb, refname);2345 logfp =fopen(sb.buf,"r");2346strbuf_release(&sb);2347if(!logfp)2348return-1;23492350/* Jump to the end */2351if(fseek(logfp,0, SEEK_END) <0)2352 ret =error("cannot seek back reflog for%s:%s",2353 refname,strerror(errno));2354 pos =ftell(logfp);2355while(!ret &&0< pos) {2356int cnt;2357size_t nread;2358char buf[BUFSIZ];2359char*endp, *scanp;23602361/* Fill next block from the end */2362 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2363if(fseek(logfp, pos - cnt, SEEK_SET)) {2364 ret =error("cannot seek back reflog for%s:%s",2365 refname,strerror(errno));2366break;2367}2368 nread =fread(buf, cnt,1, logfp);2369if(nread !=1) {2370 ret =error("cannot read%dbytes from reflog for%s:%s",2371 cnt, refname,strerror(errno));2372break;2373}2374 pos -= cnt;23752376 scanp = endp = buf + cnt;2377if(at_tail && scanp[-1] =='\n')2378/* Looking at the final LF at the end of the file */2379 scanp--;2380 at_tail =0;23812382while(buf < scanp) {2383/*2384 * terminating LF of the previous line, or the beginning2385 * of the buffer.2386 */2387char*bp;23882389 bp =find_beginning_of_line(buf, scanp);23902391if(*bp =='\n') {2392/*2393 * The newline is the end of the previous line,2394 * so we know we have complete line starting2395 * at (bp + 1). Prefix it onto any prior data2396 * we collected for the line and process it.2397 */2398strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2399 scanp = bp;2400 endp = bp +1;2401 ret =show_one_reflog_ent(&sb, fn, cb_data);2402strbuf_reset(&sb);2403if(ret)2404break;2405}else if(!pos) {2406/*2407 * We are at the start of the buffer, and the2408 * start of the file; there is no previous2409 * line, and we have everything for this one.2410 * Process it, and we can end the loop.2411 */2412strbuf_splice(&sb,0,0, buf, endp - buf);2413 ret =show_one_reflog_ent(&sb, fn, cb_data);2414strbuf_reset(&sb);2415break;2416}24172418if(bp == buf) {2419/*2420 * We are at the start of the buffer, and there2421 * is more file to read backwards. Which means2422 * we are in the middle of a line. Note that we2423 * may get here even if *bp was a newline; that2424 * just means we are at the exact end of the2425 * previous line, rather than some spot in the2426 * middle.2427 *2428 * Save away what we have to be combined with2429 * the data from the next read.2430 */2431strbuf_splice(&sb,0,0, buf, endp - buf);2432break;2433}2434}24352436}2437if(!ret && sb.len)2438die("BUG: reverse reflog parser had leftover data");24392440fclose(logfp);2441strbuf_release(&sb);2442return ret;2443}24442445static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2446const char*refname,2447 each_reflog_ent_fn fn,void*cb_data)2448{2449struct files_ref_store *refs =2450files_downcast(ref_store, REF_STORE_READ,2451"for_each_reflog_ent");2452FILE*logfp;2453struct strbuf sb = STRBUF_INIT;2454int ret =0;24552456files_reflog_path(refs, &sb, refname);2457 logfp =fopen(sb.buf,"r");2458strbuf_release(&sb);2459if(!logfp)2460return-1;24612462while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2463 ret =show_one_reflog_ent(&sb, fn, cb_data);2464fclose(logfp);2465strbuf_release(&sb);2466return ret;2467}24682469struct files_reflog_iterator {2470struct ref_iterator base;24712472struct ref_store *ref_store;2473struct dir_iterator *dir_iterator;2474struct object_id oid;2475};24762477static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2478{2479struct files_reflog_iterator *iter =2480(struct files_reflog_iterator *)ref_iterator;2481struct dir_iterator *diter = iter->dir_iterator;2482int ok;24832484while((ok =dir_iterator_advance(diter)) == ITER_OK) {2485int flags;24862487if(!S_ISREG(diter->st.st_mode))2488continue;2489if(diter->basename[0] =='.')2490continue;2491if(ends_with(diter->basename,".lock"))2492continue;24932494if(refs_read_ref_full(iter->ref_store,2495 diter->relative_path,0,2496 iter->oid.hash, &flags)) {2497error("bad ref for%s", diter->path.buf);2498continue;2499}25002501 iter->base.refname = diter->relative_path;2502 iter->base.oid = &iter->oid;2503 iter->base.flags = flags;2504return ITER_OK;2505}25062507 iter->dir_iterator = NULL;2508if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2509 ok = ITER_ERROR;2510return ok;2511}25122513static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2514struct object_id *peeled)2515{2516die("BUG: ref_iterator_peel() called for reflog_iterator");2517}25182519static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2520{2521struct files_reflog_iterator *iter =2522(struct files_reflog_iterator *)ref_iterator;2523int ok = ITER_DONE;25242525if(iter->dir_iterator)2526 ok =dir_iterator_abort(iter->dir_iterator);25272528base_ref_iterator_free(ref_iterator);2529return ok;2530}25312532static struct ref_iterator_vtable files_reflog_iterator_vtable = {2533 files_reflog_iterator_advance,2534 files_reflog_iterator_peel,2535 files_reflog_iterator_abort2536};25372538static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2539{2540struct files_ref_store *refs =2541files_downcast(ref_store, REF_STORE_READ,2542"reflog_iterator_begin");2543struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2544struct ref_iterator *ref_iterator = &iter->base;2545struct strbuf sb = STRBUF_INIT;25462547base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2548files_reflog_path(refs, &sb, NULL);2549 iter->dir_iterator =dir_iterator_begin(sb.buf);2550 iter->ref_store = ref_store;2551strbuf_release(&sb);2552return ref_iterator;2553}25542555/*2556 * If update is a direct update of head_ref (the reference pointed to2557 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2558 */2559static intsplit_head_update(struct ref_update *update,2560struct ref_transaction *transaction,2561const char*head_ref,2562struct string_list *affected_refnames,2563struct strbuf *err)2564{2565struct string_list_item *item;2566struct ref_update *new_update;25672568if((update->flags & REF_LOG_ONLY) ||2569(update->flags & REF_ISPRUNING) ||2570(update->flags & REF_UPDATE_VIA_HEAD))2571return0;25722573if(strcmp(update->refname, head_ref))2574return0;25752576/*2577 * First make sure that HEAD is not already in the2578 * transaction. This insertion is O(N) in the transaction2579 * size, but it happens at most once per transaction.2580 */2581 item =string_list_insert(affected_refnames,"HEAD");2582if(item->util) {2583/* An entry already existed */2584strbuf_addf(err,2585"multiple updates for 'HEAD' (including one "2586"via its referent '%s') are not allowed",2587 update->refname);2588return TRANSACTION_NAME_CONFLICT;2589}25902591 new_update =ref_transaction_add_update(2592 transaction,"HEAD",2593 update->flags | REF_LOG_ONLY | REF_NODEREF,2594 update->new_oid.hash, update->old_oid.hash,2595 update->msg);25962597 item->util = new_update;25982599return0;2600}26012602/*2603 * update is for a symref that points at referent and doesn't have2604 * REF_NODEREF set. Split it into two updates:2605 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2606 * - A new, separate update for the referent reference2607 * Note that the new update will itself be subject to splitting when2608 * the iteration gets to it.2609 */2610static intsplit_symref_update(struct files_ref_store *refs,2611struct ref_update *update,2612const char*referent,2613struct ref_transaction *transaction,2614struct string_list *affected_refnames,2615struct strbuf *err)2616{2617struct string_list_item *item;2618struct ref_update *new_update;2619unsigned int new_flags;26202621/*2622 * First make sure that referent is not already in the2623 * transaction. This insertion is O(N) in the transaction2624 * size, but it happens at most once per symref in a2625 * transaction.2626 */2627 item =string_list_insert(affected_refnames, referent);2628if(item->util) {2629/* An entry already existed */2630strbuf_addf(err,2631"multiple updates for '%s' (including one "2632"via symref '%s') are not allowed",2633 referent, update->refname);2634return TRANSACTION_NAME_CONFLICT;2635}26362637 new_flags = update->flags;2638if(!strcmp(update->refname,"HEAD")) {2639/*2640 * Record that the new update came via HEAD, so that2641 * when we process it, split_head_update() doesn't try2642 * to add another reflog update for HEAD. Note that2643 * this bit will be propagated if the new_update2644 * itself needs to be split.2645 */2646 new_flags |= REF_UPDATE_VIA_HEAD;2647}26482649 new_update =ref_transaction_add_update(2650 transaction, referent, new_flags,2651 update->new_oid.hash, update->old_oid.hash,2652 update->msg);26532654 new_update->parent_update = update;26552656/*2657 * Change the symbolic ref update to log only. Also, it2658 * doesn't need to check its old SHA-1 value, as that will be2659 * done when new_update is processed.2660 */2661 update->flags |= REF_LOG_ONLY | REF_NODEREF;2662 update->flags &= ~REF_HAVE_OLD;26632664 item->util = new_update;26652666return0;2667}26682669/*2670 * Return the refname under which update was originally requested.2671 */2672static const char*original_update_refname(struct ref_update *update)2673{2674while(update->parent_update)2675 update = update->parent_update;26762677return update->refname;2678}26792680/*2681 * Check whether the REF_HAVE_OLD and old_oid values stored in update2682 * are consistent with oid, which is the reference's current value. If2683 * everything is OK, return 0; otherwise, write an error message to2684 * err and return -1.2685 */2686static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2687struct strbuf *err)2688{2689if(!(update->flags & REF_HAVE_OLD) ||2690!oidcmp(oid, &update->old_oid))2691return0;26922693if(is_null_oid(&update->old_oid))2694strbuf_addf(err,"cannot lock ref '%s': "2695"reference already exists",2696original_update_refname(update));2697else if(is_null_oid(oid))2698strbuf_addf(err,"cannot lock ref '%s': "2699"reference is missing but expected%s",2700original_update_refname(update),2701oid_to_hex(&update->old_oid));2702else2703strbuf_addf(err,"cannot lock ref '%s': "2704"is at%sbut expected%s",2705original_update_refname(update),2706oid_to_hex(oid),2707oid_to_hex(&update->old_oid));27082709return-1;2710}27112712/*2713 * Prepare for carrying out update:2714 * - Lock the reference referred to by update.2715 * - Read the reference under lock.2716 * - Check that its old SHA-1 value (if specified) is correct, and in2717 * any case record it in update->lock->old_oid for later use when2718 * writing the reflog.2719 * - If it is a symref update without REF_NODEREF, split it up into a2720 * REF_LOG_ONLY update of the symref and add a separate update for2721 * the referent to transaction.2722 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2723 * update of HEAD.2724 */2725static intlock_ref_for_update(struct files_ref_store *refs,2726struct ref_update *update,2727struct ref_transaction *transaction,2728const char*head_ref,2729struct string_list *affected_refnames,2730struct strbuf *err)2731{2732struct strbuf referent = STRBUF_INIT;2733int mustexist = (update->flags & REF_HAVE_OLD) &&2734!is_null_oid(&update->old_oid);2735int ret;2736struct ref_lock *lock;27372738files_assert_main_repository(refs,"lock_ref_for_update");27392740if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2741 update->flags |= REF_DELETING;27422743if(head_ref) {2744 ret =split_head_update(update, transaction, head_ref,2745 affected_refnames, err);2746if(ret)2747return ret;2748}27492750 ret =lock_raw_ref(refs, update->refname, mustexist,2751 affected_refnames, NULL,2752&lock, &referent,2753&update->type, err);2754if(ret) {2755char*reason;27562757 reason =strbuf_detach(err, NULL);2758strbuf_addf(err,"cannot lock ref '%s':%s",2759original_update_refname(update), reason);2760free(reason);2761return ret;2762}27632764 update->backend_data = lock;27652766if(update->type & REF_ISSYMREF) {2767if(update->flags & REF_NODEREF) {2768/*2769 * We won't be reading the referent as part of2770 * the transaction, so we have to read it here2771 * to record and possibly check old_sha1:2772 */2773if(refs_read_ref_full(&refs->base,2774 referent.buf,0,2775 lock->old_oid.hash, NULL)) {2776if(update->flags & REF_HAVE_OLD) {2777strbuf_addf(err,"cannot lock ref '%s': "2778"error reading reference",2779original_update_refname(update));2780return-1;2781}2782}else if(check_old_oid(update, &lock->old_oid, err)) {2783return TRANSACTION_GENERIC_ERROR;2784}2785}else{2786/*2787 * Create a new update for the reference this2788 * symref is pointing at. Also, we will record2789 * and verify old_sha1 for this update as part2790 * of processing the split-off update, so we2791 * don't have to do it here.2792 */2793 ret =split_symref_update(refs, update,2794 referent.buf, transaction,2795 affected_refnames, err);2796if(ret)2797return ret;2798}2799}else{2800struct ref_update *parent_update;28012802if(check_old_oid(update, &lock->old_oid, err))2803return TRANSACTION_GENERIC_ERROR;28042805/*2806 * If this update is happening indirectly because of a2807 * symref update, record the old SHA-1 in the parent2808 * update:2809 */2810for(parent_update = update->parent_update;2811 parent_update;2812 parent_update = parent_update->parent_update) {2813struct ref_lock *parent_lock = parent_update->backend_data;2814oidcpy(&parent_lock->old_oid, &lock->old_oid);2815}2816}28172818if((update->flags & REF_HAVE_NEW) &&2819!(update->flags & REF_DELETING) &&2820!(update->flags & REF_LOG_ONLY)) {2821if(!(update->type & REF_ISSYMREF) &&2822!oidcmp(&lock->old_oid, &update->new_oid)) {2823/*2824 * The reference already has the desired2825 * value, so we don't need to write it.2826 */2827}else if(write_ref_to_lockfile(lock, &update->new_oid,2828 err)) {2829char*write_err =strbuf_detach(err, NULL);28302831/*2832 * The lock was freed upon failure of2833 * write_ref_to_lockfile():2834 */2835 update->backend_data = NULL;2836strbuf_addf(err,2837"cannot update ref '%s':%s",2838 update->refname, write_err);2839free(write_err);2840return TRANSACTION_GENERIC_ERROR;2841}else{2842 update->flags |= REF_NEEDS_COMMIT;2843}2844}2845if(!(update->flags & REF_NEEDS_COMMIT)) {2846/*2847 * We didn't call write_ref_to_lockfile(), so2848 * the lockfile is still open. Close it to2849 * free up the file descriptor:2850 */2851if(close_ref(lock)) {2852strbuf_addf(err,"couldn't close '%s.lock'",2853 update->refname);2854return TRANSACTION_GENERIC_ERROR;2855}2856}2857return0;2858}28592860/*2861 * Unlock any references in `transaction` that are still locked, and2862 * mark the transaction closed.2863 */2864static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2865{2866size_t i;28672868for(i =0; i < transaction->nr; i++) {2869struct ref_update *update = transaction->updates[i];2870struct ref_lock *lock = update->backend_data;28712872if(lock) {2873unlock_ref(lock);2874 update->backend_data = NULL;2875}2876}28772878 transaction->state = REF_TRANSACTION_CLOSED;2879}28802881static intfiles_transaction_prepare(struct ref_store *ref_store,2882struct ref_transaction *transaction,2883struct strbuf *err)2884{2885struct files_ref_store *refs =2886files_downcast(ref_store, REF_STORE_WRITE,2887"ref_transaction_prepare");2888size_t i;2889int ret =0;2890struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2891char*head_ref = NULL;2892int head_type;2893struct object_id head_oid;28942895assert(err);28962897if(!transaction->nr)2898goto cleanup;28992900/*2901 * Fail if a refname appears more than once in the2902 * transaction. (If we end up splitting up any updates using2903 * split_symref_update() or split_head_update(), those2904 * functions will check that the new updates don't have the2905 * same refname as any existing ones.)2906 */2907for(i =0; i < transaction->nr; i++) {2908struct ref_update *update = transaction->updates[i];2909struct string_list_item *item =2910string_list_append(&affected_refnames, update->refname);29112912/*2913 * We store a pointer to update in item->util, but at2914 * the moment we never use the value of this field2915 * except to check whether it is non-NULL.2916 */2917 item->util = update;2918}2919string_list_sort(&affected_refnames);2920if(ref_update_reject_duplicates(&affected_refnames, err)) {2921 ret = TRANSACTION_GENERIC_ERROR;2922goto cleanup;2923}29242925/*2926 * Special hack: If a branch is updated directly and HEAD2927 * points to it (may happen on the remote side of a push2928 * for example) then logically the HEAD reflog should be2929 * updated too.2930 *2931 * A generic solution would require reverse symref lookups,2932 * but finding all symrefs pointing to a given branch would be2933 * rather costly for this rare event (the direct update of a2934 * branch) to be worth it. So let's cheat and check with HEAD2935 * only, which should cover 99% of all usage scenarios (even2936 * 100% of the default ones).2937 *2938 * So if HEAD is a symbolic reference, then record the name of2939 * the reference that it points to. If we see an update of2940 * head_ref within the transaction, then split_head_update()2941 * arranges for the reflog of HEAD to be updated, too.2942 */2943 head_ref =refs_resolve_refdup(ref_store,"HEAD",2944 RESOLVE_REF_NO_RECURSE,2945 head_oid.hash, &head_type);29462947if(head_ref && !(head_type & REF_ISSYMREF)) {2948free(head_ref);2949 head_ref = NULL;2950}29512952/*2953 * Acquire all locks, verify old values if provided, check2954 * that new values are valid, and write new values to the2955 * lockfiles, ready to be activated. Only keep one lockfile2956 * open at a time to avoid running out of file descriptors.2957 * Note that lock_ref_for_update() might append more updates2958 * to the transaction.2959 */2960for(i =0; i < transaction->nr; i++) {2961struct ref_update *update = transaction->updates[i];29622963 ret =lock_ref_for_update(refs, update, transaction,2964 head_ref, &affected_refnames, err);2965if(ret)2966break;2967}29682969cleanup:2970free(head_ref);2971string_list_clear(&affected_refnames,0);29722973if(ret)2974files_transaction_cleanup(transaction);2975else2976 transaction->state = REF_TRANSACTION_PREPARED;29772978return ret;2979}29802981static intfiles_transaction_finish(struct ref_store *ref_store,2982struct ref_transaction *transaction,2983struct strbuf *err)2984{2985struct files_ref_store *refs =2986files_downcast(ref_store,0,"ref_transaction_finish");2987size_t i;2988int ret =0;2989struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2990struct string_list_item *ref_to_delete;2991struct strbuf sb = STRBUF_INIT;29922993assert(err);29942995if(!transaction->nr) {2996 transaction->state = REF_TRANSACTION_CLOSED;2997return0;2998}29993000/* Perform updates first so live commits remain referenced */3001for(i =0; i < transaction->nr; i++) {3002struct ref_update *update = transaction->updates[i];3003struct ref_lock *lock = update->backend_data;30043005if(update->flags & REF_NEEDS_COMMIT ||3006 update->flags & REF_LOG_ONLY) {3007if(files_log_ref_write(refs,3008 lock->ref_name,3009&lock->old_oid,3010&update->new_oid,3011 update->msg, update->flags,3012 err)) {3013char*old_msg =strbuf_detach(err, NULL);30143015strbuf_addf(err,"cannot update the ref '%s':%s",3016 lock->ref_name, old_msg);3017free(old_msg);3018unlock_ref(lock);3019 update->backend_data = NULL;3020 ret = TRANSACTION_GENERIC_ERROR;3021goto cleanup;3022}3023}3024if(update->flags & REF_NEEDS_COMMIT) {3025clear_loose_ref_cache(refs);3026if(commit_ref(lock)) {3027strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3028unlock_ref(lock);3029 update->backend_data = NULL;3030 ret = TRANSACTION_GENERIC_ERROR;3031goto cleanup;3032}3033}3034}3035/* Perform deletes now that updates are safely completed */3036for(i =0; i < transaction->nr; i++) {3037struct ref_update *update = transaction->updates[i];3038struct ref_lock *lock = update->backend_data;30393040if(update->flags & REF_DELETING &&3041!(update->flags & REF_LOG_ONLY)) {3042if(!(update->type & REF_ISPACKED) ||3043 update->type & REF_ISSYMREF) {3044/* It is a loose reference. */3045strbuf_reset(&sb);3046files_ref_path(refs, &sb, lock->ref_name);3047if(unlink_or_msg(sb.buf, err)) {3048 ret = TRANSACTION_GENERIC_ERROR;3049goto cleanup;3050}3051 update->flags |= REF_DELETED_LOOSE;3052}30533054if(!(update->flags & REF_ISPRUNING))3055string_list_append(&refs_to_delete,3056 lock->ref_name);3057}3058}30593060if(repack_without_refs(refs, &refs_to_delete, err)) {3061 ret = TRANSACTION_GENERIC_ERROR;3062goto cleanup;3063}30643065/* Delete the reflogs of any references that were deleted: */3066for_each_string_list_item(ref_to_delete, &refs_to_delete) {3067strbuf_reset(&sb);3068files_reflog_path(refs, &sb, ref_to_delete->string);3069if(!unlink_or_warn(sb.buf))3070try_remove_empty_parents(refs, ref_to_delete->string,3071 REMOVE_EMPTY_PARENTS_REFLOG);3072}30733074clear_loose_ref_cache(refs);30753076cleanup:3077files_transaction_cleanup(transaction);30783079for(i =0; i < transaction->nr; i++) {3080struct ref_update *update = transaction->updates[i];30813082if(update->flags & REF_DELETED_LOOSE) {3083/*3084 * The loose reference was deleted. Delete any3085 * empty parent directories. (Note that this3086 * can only work because we have already3087 * removed the lockfile.)3088 */3089try_remove_empty_parents(refs, update->refname,3090 REMOVE_EMPTY_PARENTS_REF);3091}3092}30933094strbuf_release(&sb);3095string_list_clear(&refs_to_delete,0);3096return ret;3097}30983099static intfiles_transaction_abort(struct ref_store *ref_store,3100struct ref_transaction *transaction,3101struct strbuf *err)3102{3103files_transaction_cleanup(transaction);3104return0;3105}31063107static intref_present(const char*refname,3108const struct object_id *oid,int flags,void*cb_data)3109{3110struct string_list *affected_refnames = cb_data;31113112returnstring_list_has_string(affected_refnames, refname);3113}31143115static intfiles_initial_transaction_commit(struct ref_store *ref_store,3116struct ref_transaction *transaction,3117struct strbuf *err)3118{3119struct files_ref_store *refs =3120files_downcast(ref_store, REF_STORE_WRITE,3121"initial_ref_transaction_commit");3122size_t i;3123int ret =0;3124struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31253126assert(err);31273128if(transaction->state != REF_TRANSACTION_OPEN)3129die("BUG: commit called for transaction that is not open");31303131/* Fail if a refname appears more than once in the transaction: */3132for(i =0; i < transaction->nr; i++)3133string_list_append(&affected_refnames,3134 transaction->updates[i]->refname);3135string_list_sort(&affected_refnames);3136if(ref_update_reject_duplicates(&affected_refnames, err)) {3137 ret = TRANSACTION_GENERIC_ERROR;3138goto cleanup;3139}31403141/*3142 * It's really undefined to call this function in an active3143 * repository or when there are existing references: we are3144 * only locking and changing packed-refs, so (1) any3145 * simultaneous processes might try to change a reference at3146 * the same time we do, and (2) any existing loose versions of3147 * the references that we are setting would have precedence3148 * over our values. But some remote helpers create the remote3149 * "HEAD" and "master" branches before calling this function,3150 * so here we really only check that none of the references3151 * that we are creating already exists.3152 */3153if(refs_for_each_rawref(&refs->base, ref_present,3154&affected_refnames))3155die("BUG: initial ref transaction called with existing refs");31563157for(i =0; i < transaction->nr; i++) {3158struct ref_update *update = transaction->updates[i];31593160if((update->flags & REF_HAVE_OLD) &&3161!is_null_oid(&update->old_oid))3162die("BUG: initial ref transaction with old_sha1 set");3163if(refs_verify_refname_available(&refs->base, update->refname,3164&affected_refnames, NULL,3165 err)) {3166 ret = TRANSACTION_NAME_CONFLICT;3167goto cleanup;3168}3169}31703171if(lock_packed_refs(refs,0)) {3172strbuf_addf(err,"unable to lock packed-refs file:%s",3173strerror(errno));3174 ret = TRANSACTION_GENERIC_ERROR;3175goto cleanup;3176}31773178for(i =0; i < transaction->nr; i++) {3179struct ref_update *update = transaction->updates[i];31803181if((update->flags & REF_HAVE_NEW) &&3182!is_null_oid(&update->new_oid))3183add_packed_ref(refs, update->refname,3184&update->new_oid);3185}31863187if(commit_packed_refs(refs)) {3188strbuf_addf(err,"unable to commit packed-refs file:%s",3189strerror(errno));3190 ret = TRANSACTION_GENERIC_ERROR;3191goto cleanup;3192}31933194cleanup:3195 transaction->state = REF_TRANSACTION_CLOSED;3196string_list_clear(&affected_refnames,0);3197return ret;3198}31993200struct expire_reflog_cb {3201unsigned int flags;3202 reflog_expiry_should_prune_fn *should_prune_fn;3203void*policy_cb;3204FILE*newlog;3205struct object_id last_kept_oid;3206};32073208static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3209const char*email, timestamp_t timestamp,int tz,3210const char*message,void*cb_data)3211{3212struct expire_reflog_cb *cb = cb_data;3213struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32143215if(cb->flags & EXPIRE_REFLOGS_REWRITE)3216 ooid = &cb->last_kept_oid;32173218if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3219 message, policy_cb)) {3220if(!cb->newlog)3221printf("would prune%s", message);3222else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3223printf("prune%s", message);3224}else{3225if(cb->newlog) {3226fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3227oid_to_hex(ooid),oid_to_hex(noid),3228 email, timestamp, tz, message);3229oidcpy(&cb->last_kept_oid, noid);3230}3231if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3232printf("keep%s", message);3233}3234return0;3235}32363237static intfiles_reflog_expire(struct ref_store *ref_store,3238const char*refname,const unsigned char*sha1,3239unsigned int flags,3240 reflog_expiry_prepare_fn prepare_fn,3241 reflog_expiry_should_prune_fn should_prune_fn,3242 reflog_expiry_cleanup_fn cleanup_fn,3243void*policy_cb_data)3244{3245struct files_ref_store *refs =3246files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3247static struct lock_file reflog_lock;3248struct expire_reflog_cb cb;3249struct ref_lock *lock;3250struct strbuf log_file_sb = STRBUF_INIT;3251char*log_file;3252int status =0;3253int type;3254struct strbuf err = STRBUF_INIT;3255struct object_id oid;32563257memset(&cb,0,sizeof(cb));3258 cb.flags = flags;3259 cb.policy_cb = policy_cb_data;3260 cb.should_prune_fn = should_prune_fn;32613262/*3263 * The reflog file is locked by holding the lock on the3264 * reference itself, plus we might need to update the3265 * reference if --updateref was specified:3266 */3267 lock =lock_ref_sha1_basic(refs, refname, sha1,3268 NULL, NULL, REF_NODEREF,3269&type, &err);3270if(!lock) {3271error("cannot lock ref '%s':%s", refname, err.buf);3272strbuf_release(&err);3273return-1;3274}3275if(!refs_reflog_exists(ref_store, refname)) {3276unlock_ref(lock);3277return0;3278}32793280files_reflog_path(refs, &log_file_sb, refname);3281 log_file =strbuf_detach(&log_file_sb, NULL);3282if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3283/*3284 * Even though holding $GIT_DIR/logs/$reflog.lock has3285 * no locking implications, we use the lock_file3286 * machinery here anyway because it does a lot of the3287 * work we need, including cleaning up if the program3288 * exits unexpectedly.3289 */3290if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3291struct strbuf err = STRBUF_INIT;3292unable_to_lock_message(log_file, errno, &err);3293error("%s", err.buf);3294strbuf_release(&err);3295goto failure;3296}3297 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3298if(!cb.newlog) {3299error("cannot fdopen%s(%s)",3300get_lock_file_path(&reflog_lock),strerror(errno));3301goto failure;3302}3303}33043305hashcpy(oid.hash, sha1);33063307(*prepare_fn)(refname, &oid, cb.policy_cb);3308refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3309(*cleanup_fn)(cb.policy_cb);33103311if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3312/*3313 * It doesn't make sense to adjust a reference pointed3314 * to by a symbolic ref based on expiring entries in3315 * the symbolic reference's reflog. Nor can we update3316 * a reference if there are no remaining reflog3317 * entries.3318 */3319int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3320!(type & REF_ISSYMREF) &&3321!is_null_oid(&cb.last_kept_oid);33223323if(close_lock_file(&reflog_lock)) {3324 status |=error("couldn't write%s:%s", log_file,3325strerror(errno));3326}else if(update &&3327(write_in_full(get_lock_file_fd(lock->lk),3328oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3329write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3330close_ref(lock) <0)) {3331 status |=error("couldn't write%s",3332get_lock_file_path(lock->lk));3333rollback_lock_file(&reflog_lock);3334}else if(commit_lock_file(&reflog_lock)) {3335 status |=error("unable to write reflog '%s' (%s)",3336 log_file,strerror(errno));3337}else if(update &&commit_ref(lock)) {3338 status |=error("couldn't set%s", lock->ref_name);3339}3340}3341free(log_file);3342unlock_ref(lock);3343return status;33443345 failure:3346rollback_lock_file(&reflog_lock);3347free(log_file);3348unlock_ref(lock);3349return-1;3350}33513352static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3353{3354struct files_ref_store *refs =3355files_downcast(ref_store, REF_STORE_WRITE,"init_db");3356struct strbuf sb = STRBUF_INIT;33573358/*3359 * Create .git/refs/{heads,tags}3360 */3361files_ref_path(refs, &sb,"refs/heads");3362safe_create_dir(sb.buf,1);33633364strbuf_reset(&sb);3365files_ref_path(refs, &sb,"refs/tags");3366safe_create_dir(sb.buf,1);33673368strbuf_release(&sb);3369return0;3370}33713372struct ref_storage_be refs_be_files = {3373 NULL,3374"files",3375 files_ref_store_create,3376 files_init_db,3377 files_transaction_prepare,3378 files_transaction_finish,3379 files_transaction_abort,3380 files_initial_transaction_commit,33813382 files_pack_refs,3383 files_peel_ref,3384 files_create_symref,3385 files_delete_refs,3386 files_rename_ref,33873388 files_ref_iterator_begin,3389 files_read_raw_ref,33903391 files_reflog_iterator_begin,3392 files_for_each_reflog_ent,3393 files_for_each_reflog_ent_reverse,3394 files_reflog_exists,3395 files_create_reflog,3396 files_delete_reflog,3397 files_reflog_expire3398};