1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35/* 36 * Return true if the reference described by entry can be resolved to 37 * an object in the database; otherwise, emit a warning and return 38 * false. 39 */ 40static intentry_resolves_to_object(struct ref_entry *entry) 41{ 42returnref_resolves_to_object(entry->name, 43&entry->u.value.oid, entry->flag); 44} 45 46struct packed_ref_cache { 47struct ref_cache *cache; 48 49/* 50 * Count of references to the data structure in this instance, 51 * including the pointer from files_ref_store::packed if any. 52 * The data will not be freed as long as the reference count 53 * is nonzero. 54 */ 55unsigned int referrers; 56 57/* 58 * Iff the packed-refs file associated with this instance is 59 * currently locked for writing, this points at the associated 60 * lock (which is owned by somebody else). The referrer count 61 * is also incremented when the file is locked and decremented 62 * when it is unlocked. 63 */ 64struct lock_file *lock; 65 66/* The metadata from when this packed-refs cache was read */ 67struct stat_validity validity; 68}; 69 70/* 71 * Future: need to be in "struct repository" 72 * when doing a full libification. 73 */ 74struct files_ref_store { 75struct ref_store base; 76unsigned int store_flags; 77 78char*gitdir; 79char*gitcommondir; 80char*packed_refs_path; 81 82struct ref_cache *loose; 83struct packed_ref_cache *packed; 84}; 85 86/* Lock used for the main packed-refs file: */ 87static struct lock_file packlock; 88 89/* 90 * Increment the reference count of *packed_refs. 91 */ 92static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 93{ 94 packed_refs->referrers++; 95} 96 97/* 98 * Decrease the reference count of *packed_refs. If it goes to zero, 99 * free *packed_refs and return true; otherwise return false. 100 */ 101static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 102{ 103if(!--packed_refs->referrers) { 104free_ref_cache(packed_refs->cache); 105stat_validity_clear(&packed_refs->validity); 106free(packed_refs); 107return1; 108}else{ 109return0; 110} 111} 112 113static voidclear_packed_ref_cache(struct files_ref_store *refs) 114{ 115if(refs->packed) { 116struct packed_ref_cache *packed_refs = refs->packed; 117 118if(packed_refs->lock) 119die("internal error: packed-ref cache cleared while locked"); 120 refs->packed = NULL; 121release_packed_ref_cache(packed_refs); 122} 123} 124 125static voidclear_loose_ref_cache(struct files_ref_store *refs) 126{ 127if(refs->loose) { 128free_ref_cache(refs->loose); 129 refs->loose = NULL; 130} 131} 132 133/* 134 * Create a new submodule ref cache and add it to the internal 135 * set of caches. 136 */ 137static struct ref_store *files_ref_store_create(const char*gitdir, 138unsigned int flags) 139{ 140struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 141struct ref_store *ref_store = (struct ref_store *)refs; 142struct strbuf sb = STRBUF_INIT; 143 144base_ref_store_init(ref_store, &refs_be_files); 145 refs->store_flags = flags; 146 147 refs->gitdir =xstrdup(gitdir); 148get_common_dir_noenv(&sb, gitdir); 149 refs->gitcommondir =strbuf_detach(&sb, NULL); 150strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 151 refs->packed_refs_path =strbuf_detach(&sb, NULL); 152 153return ref_store; 154} 155 156/* 157 * Die if refs is not the main ref store. caller is used in any 158 * necessary error messages. 159 */ 160static voidfiles_assert_main_repository(struct files_ref_store *refs, 161const char*caller) 162{ 163if(refs->store_flags & REF_STORE_MAIN) 164return; 165 166die("BUG: operation%sonly allowed for main ref store", caller); 167} 168 169/* 170 * Downcast ref_store to files_ref_store. Die if ref_store is not a 171 * files_ref_store. required_flags is compared with ref_store's 172 * store_flags to ensure the ref_store has all required capabilities. 173 * "caller" is used in any necessary error messages. 174 */ 175static struct files_ref_store *files_downcast(struct ref_store *ref_store, 176unsigned int required_flags, 177const char*caller) 178{ 179struct files_ref_store *refs; 180 181if(ref_store->be != &refs_be_files) 182die("BUG: ref_store is type\"%s\"not\"files\"in%s", 183 ref_store->be->name, caller); 184 185 refs = (struct files_ref_store *)ref_store; 186 187if((refs->store_flags & required_flags) != required_flags) 188die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 189 caller, required_flags, refs->store_flags); 190 191return refs; 192} 193 194/* The length of a peeled reference line in packed-refs, including EOL: */ 195#define PEELED_LINE_LENGTH 42 196 197/* 198 * The packed-refs header line that we write out. Perhaps other 199 * traits will be added later. The trailing space is required. 200 */ 201static const char PACKED_REFS_HEADER[] = 202"# pack-refs with: peeled fully-peeled\n"; 203 204/* 205 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 206 * Return a pointer to the refname within the line (null-terminated), 207 * or NULL if there was a problem. 208 */ 209static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 210{ 211const char*ref; 212 213/* 214 * 42: the answer to everything. 215 * 216 * In this case, it happens to be the answer to 217 * 40 (length of sha1 hex representation) 218 * +1 (space in between hex and name) 219 * +1 (newline at the end of the line) 220 */ 221if(line->len <=42) 222return NULL; 223 224if(get_sha1_hex(line->buf, sha1) <0) 225return NULL; 226if(!isspace(line->buf[40])) 227return NULL; 228 229 ref = line->buf +41; 230if(isspace(*ref)) 231return NULL; 232 233if(line->buf[line->len -1] !='\n') 234return NULL; 235 line->buf[--line->len] =0; 236 237return ref; 238} 239 240/* 241 * Read f, which is a packed-refs file, into dir. 242 * 243 * A comment line of the form "# pack-refs with: " may contain zero or 244 * more traits. We interpret the traits as follows: 245 * 246 * No traits: 247 * 248 * Probably no references are peeled. But if the file contains a 249 * peeled value for a reference, we will use it. 250 * 251 * peeled: 252 * 253 * References under "refs/tags/", if they *can* be peeled, *are* 254 * peeled in this file. References outside of "refs/tags/" are 255 * probably not peeled even if they could have been, but if we find 256 * a peeled value for such a reference we will use it. 257 * 258 * fully-peeled: 259 * 260 * All references in the file that can be peeled are peeled. 261 * Inversely (and this is more important), any references in the 262 * file for which no peeled value is recorded is not peelable. This 263 * trait should typically be written alongside "peeled" for 264 * compatibility with older clients, but we do not require it 265 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 266 */ 267static voidread_packed_refs(FILE*f,struct ref_dir *dir) 268{ 269struct ref_entry *last = NULL; 270struct strbuf line = STRBUF_INIT; 271enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 272 273while(strbuf_getwholeline(&line, f,'\n') != EOF) { 274unsigned char sha1[20]; 275const char*refname; 276const char*traits; 277 278if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 279if(strstr(traits," fully-peeled ")) 280 peeled = PEELED_FULLY; 281else if(strstr(traits," peeled ")) 282 peeled = PEELED_TAGS; 283/* perhaps other traits later as well */ 284continue; 285} 286 287 refname =parse_ref_line(&line, sha1); 288if(refname) { 289int flag = REF_ISPACKED; 290 291if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 292if(!refname_is_safe(refname)) 293die("packed refname is dangerous:%s", refname); 294hashclr(sha1); 295 flag |= REF_BAD_NAME | REF_ISBROKEN; 296} 297 last =create_ref_entry(refname, sha1, flag,0); 298if(peeled == PEELED_FULLY || 299(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 300 last->flag |= REF_KNOWS_PEELED; 301add_ref_entry(dir, last); 302continue; 303} 304if(last && 305 line.buf[0] =='^'&& 306 line.len == PEELED_LINE_LENGTH && 307 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 308!get_sha1_hex(line.buf +1, sha1)) { 309hashcpy(last->u.value.peeled.hash, sha1); 310/* 311 * Regardless of what the file header said, 312 * we definitely know the value of *this* 313 * reference: 314 */ 315 last->flag |= REF_KNOWS_PEELED; 316} 317} 318 319strbuf_release(&line); 320} 321 322static const char*files_packed_refs_path(struct files_ref_store *refs) 323{ 324return refs->packed_refs_path; 325} 326 327static voidfiles_reflog_path(struct files_ref_store *refs, 328struct strbuf *sb, 329const char*refname) 330{ 331if(!refname) { 332/* 333 * FIXME: of course this is wrong in multi worktree 334 * setting. To be fixed real soon. 335 */ 336strbuf_addf(sb,"%s/logs", refs->gitcommondir); 337return; 338} 339 340switch(ref_type(refname)) { 341case REF_TYPE_PER_WORKTREE: 342case REF_TYPE_PSEUDOREF: 343strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 344break; 345case REF_TYPE_NORMAL: 346strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 347break; 348default: 349die("BUG: unknown ref type%dof ref%s", 350ref_type(refname), refname); 351} 352} 353 354static voidfiles_ref_path(struct files_ref_store *refs, 355struct strbuf *sb, 356const char*refname) 357{ 358switch(ref_type(refname)) { 359case REF_TYPE_PER_WORKTREE: 360case REF_TYPE_PSEUDOREF: 361strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 362break; 363case REF_TYPE_NORMAL: 364strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 365break; 366default: 367die("BUG: unknown ref type%dof ref%s", 368ref_type(refname), refname); 369} 370} 371 372/* 373 * Get the packed_ref_cache for the specified files_ref_store, 374 * creating it if necessary. 375 */ 376static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 377{ 378const char*packed_refs_file =files_packed_refs_path(refs); 379 380if(refs->packed && 381!stat_validity_check(&refs->packed->validity, packed_refs_file)) 382clear_packed_ref_cache(refs); 383 384if(!refs->packed) { 385FILE*f; 386 387 refs->packed =xcalloc(1,sizeof(*refs->packed)); 388acquire_packed_ref_cache(refs->packed); 389 refs->packed->cache =create_ref_cache(refs); 390 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 391 f =fopen(packed_refs_file,"r"); 392if(f) { 393stat_validity_update(&refs->packed->validity,fileno(f)); 394read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 395fclose(f); 396} 397} 398return refs->packed; 399} 400 401static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 402{ 403returnget_ref_dir(packed_ref_cache->cache->root); 404} 405 406static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 407{ 408returnget_packed_ref_dir(get_packed_ref_cache(refs)); 409} 410 411/* 412 * Add a reference to the in-memory packed reference cache. This may 413 * only be called while the packed-refs file is locked (see 414 * lock_packed_refs()). To actually write the packed-refs file, call 415 * commit_packed_refs(). 416 */ 417static voidadd_packed_ref(struct files_ref_store *refs, 418const char*refname,const unsigned char*sha1) 419{ 420struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 421 422if(!packed_ref_cache->lock) 423die("internal error: packed refs not locked"); 424add_ref_entry(get_packed_ref_dir(packed_ref_cache), 425create_ref_entry(refname, sha1, REF_ISPACKED,1)); 426} 427 428/* 429 * Read the loose references from the namespace dirname into dir 430 * (without recursing). dirname must end with '/'. dir must be the 431 * directory entry corresponding to dirname. 432 */ 433voidread_loose_refs(const char*dirname,struct ref_dir *dir) 434{ 435struct files_ref_store *refs = dir->cache->ref_store; 436DIR*d; 437struct dirent *de; 438int dirnamelen =strlen(dirname); 439struct strbuf refname; 440struct strbuf path = STRBUF_INIT; 441size_t path_baselen; 442 443files_ref_path(refs, &path, dirname); 444 path_baselen = path.len; 445 446 d =opendir(path.buf); 447if(!d) { 448strbuf_release(&path); 449return; 450} 451 452strbuf_init(&refname, dirnamelen +257); 453strbuf_add(&refname, dirname, dirnamelen); 454 455while((de =readdir(d)) != NULL) { 456unsigned char sha1[20]; 457struct stat st; 458int flag; 459 460if(de->d_name[0] =='.') 461continue; 462if(ends_with(de->d_name,".lock")) 463continue; 464strbuf_addstr(&refname, de->d_name); 465strbuf_addstr(&path, de->d_name); 466if(stat(path.buf, &st) <0) { 467;/* silently ignore */ 468}else if(S_ISDIR(st.st_mode)) { 469strbuf_addch(&refname,'/'); 470add_entry_to_dir(dir, 471create_dir_entry(dir->cache, refname.buf, 472 refname.len,1)); 473}else{ 474if(!refs_resolve_ref_unsafe(&refs->base, 475 refname.buf, 476 RESOLVE_REF_READING, 477 sha1, &flag)) { 478hashclr(sha1); 479 flag |= REF_ISBROKEN; 480}else if(is_null_sha1(sha1)) { 481/* 482 * It is so astronomically unlikely 483 * that NULL_SHA1 is the SHA-1 of an 484 * actual object that we consider its 485 * appearance in a loose reference 486 * file to be repo corruption 487 * (probably due to a software bug). 488 */ 489 flag |= REF_ISBROKEN; 490} 491 492if(check_refname_format(refname.buf, 493 REFNAME_ALLOW_ONELEVEL)) { 494if(!refname_is_safe(refname.buf)) 495die("loose refname is dangerous:%s", refname.buf); 496hashclr(sha1); 497 flag |= REF_BAD_NAME | REF_ISBROKEN; 498} 499add_entry_to_dir(dir, 500create_ref_entry(refname.buf, sha1, flag,0)); 501} 502strbuf_setlen(&refname, dirnamelen); 503strbuf_setlen(&path, path_baselen); 504} 505strbuf_release(&refname); 506strbuf_release(&path); 507closedir(d); 508} 509 510static struct ref_dir *get_loose_refs(struct files_ref_store *refs) 511{ 512if(!refs->loose) { 513/* 514 * Mark the top-level directory complete because we 515 * are about to read the only subdirectory that can 516 * hold references: 517 */ 518 refs->loose =create_ref_cache(refs); 519 520/* We're going to fill the top level ourselves: */ 521 refs->loose->root->flag &= ~REF_INCOMPLETE; 522 523/* 524 * Add an incomplete entry for "refs/" (to be filled 525 * lazily): 526 */ 527add_entry_to_dir(get_ref_dir(refs->loose->root), 528create_dir_entry(refs->loose,"refs/",5,1)); 529} 530returnget_ref_dir(refs->loose->root); 531} 532 533/* 534 * Return the ref_entry for the given refname from the packed 535 * references. If it does not exist, return NULL. 536 */ 537static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 538const char*refname) 539{ 540returnfind_ref_entry(get_packed_refs(refs), refname); 541} 542 543/* 544 * A loose ref file doesn't exist; check for a packed ref. 545 */ 546static intresolve_packed_ref(struct files_ref_store *refs, 547const char*refname, 548unsigned char*sha1,unsigned int*flags) 549{ 550struct ref_entry *entry; 551 552/* 553 * The loose reference file does not exist; check for a packed 554 * reference. 555 */ 556 entry =get_packed_ref(refs, refname); 557if(entry) { 558hashcpy(sha1, entry->u.value.oid.hash); 559*flags |= REF_ISPACKED; 560return0; 561} 562/* refname is not a packed reference. */ 563return-1; 564} 565 566static intfiles_read_raw_ref(struct ref_store *ref_store, 567const char*refname,unsigned char*sha1, 568struct strbuf *referent,unsigned int*type) 569{ 570struct files_ref_store *refs = 571files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 572struct strbuf sb_contents = STRBUF_INIT; 573struct strbuf sb_path = STRBUF_INIT; 574const char*path; 575const char*buf; 576struct stat st; 577int fd; 578int ret = -1; 579int save_errno; 580int remaining_retries =3; 581 582*type =0; 583strbuf_reset(&sb_path); 584 585files_ref_path(refs, &sb_path, refname); 586 587 path = sb_path.buf; 588 589stat_ref: 590/* 591 * We might have to loop back here to avoid a race 592 * condition: first we lstat() the file, then we try 593 * to read it as a link or as a file. But if somebody 594 * changes the type of the file (file <-> directory 595 * <-> symlink) between the lstat() and reading, then 596 * we don't want to report that as an error but rather 597 * try again starting with the lstat(). 598 * 599 * We'll keep a count of the retries, though, just to avoid 600 * any confusing situation sending us into an infinite loop. 601 */ 602 603if(remaining_retries-- <=0) 604goto out; 605 606if(lstat(path, &st) <0) { 607if(errno != ENOENT) 608goto out; 609if(resolve_packed_ref(refs, refname, sha1, type)) { 610 errno = ENOENT; 611goto out; 612} 613 ret =0; 614goto out; 615} 616 617/* Follow "normalized" - ie "refs/.." symlinks by hand */ 618if(S_ISLNK(st.st_mode)) { 619strbuf_reset(&sb_contents); 620if(strbuf_readlink(&sb_contents, path,0) <0) { 621if(errno == ENOENT || errno == EINVAL) 622/* inconsistent with lstat; retry */ 623goto stat_ref; 624else 625goto out; 626} 627if(starts_with(sb_contents.buf,"refs/") && 628!check_refname_format(sb_contents.buf,0)) { 629strbuf_swap(&sb_contents, referent); 630*type |= REF_ISSYMREF; 631 ret =0; 632goto out; 633} 634/* 635 * It doesn't look like a refname; fall through to just 636 * treating it like a non-symlink, and reading whatever it 637 * points to. 638 */ 639} 640 641/* Is it a directory? */ 642if(S_ISDIR(st.st_mode)) { 643/* 644 * Even though there is a directory where the loose 645 * ref is supposed to be, there could still be a 646 * packed ref: 647 */ 648if(resolve_packed_ref(refs, refname, sha1, type)) { 649 errno = EISDIR; 650goto out; 651} 652 ret =0; 653goto out; 654} 655 656/* 657 * Anything else, just open it and try to use it as 658 * a ref 659 */ 660 fd =open(path, O_RDONLY); 661if(fd <0) { 662if(errno == ENOENT && !S_ISLNK(st.st_mode)) 663/* inconsistent with lstat; retry */ 664goto stat_ref; 665else 666goto out; 667} 668strbuf_reset(&sb_contents); 669if(strbuf_read(&sb_contents, fd,256) <0) { 670int save_errno = errno; 671close(fd); 672 errno = save_errno; 673goto out; 674} 675close(fd); 676strbuf_rtrim(&sb_contents); 677 buf = sb_contents.buf; 678if(starts_with(buf,"ref:")) { 679 buf +=4; 680while(isspace(*buf)) 681 buf++; 682 683strbuf_reset(referent); 684strbuf_addstr(referent, buf); 685*type |= REF_ISSYMREF; 686 ret =0; 687goto out; 688} 689 690/* 691 * Please note that FETCH_HEAD has additional 692 * data after the sha. 693 */ 694if(get_sha1_hex(buf, sha1) || 695(buf[40] !='\0'&& !isspace(buf[40]))) { 696*type |= REF_ISBROKEN; 697 errno = EINVAL; 698goto out; 699} 700 701 ret =0; 702 703out: 704 save_errno = errno; 705strbuf_release(&sb_path); 706strbuf_release(&sb_contents); 707 errno = save_errno; 708return ret; 709} 710 711static voidunlock_ref(struct ref_lock *lock) 712{ 713/* Do not free lock->lk -- atexit() still looks at them */ 714if(lock->lk) 715rollback_lock_file(lock->lk); 716free(lock->ref_name); 717free(lock); 718} 719 720/* 721 * Lock refname, without following symrefs, and set *lock_p to point 722 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 723 * and type similarly to read_raw_ref(). 724 * 725 * The caller must verify that refname is a "safe" reference name (in 726 * the sense of refname_is_safe()) before calling this function. 727 * 728 * If the reference doesn't already exist, verify that refname doesn't 729 * have a D/F conflict with any existing references. extras and skip 730 * are passed to refs_verify_refname_available() for this check. 731 * 732 * If mustexist is not set and the reference is not found or is 733 * broken, lock the reference anyway but clear sha1. 734 * 735 * Return 0 on success. On failure, write an error message to err and 736 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 737 * 738 * Implementation note: This function is basically 739 * 740 * lock reference 741 * read_raw_ref() 742 * 743 * but it includes a lot more code to 744 * - Deal with possible races with other processes 745 * - Avoid calling refs_verify_refname_available() when it can be 746 * avoided, namely if we were successfully able to read the ref 747 * - Generate informative error messages in the case of failure 748 */ 749static intlock_raw_ref(struct files_ref_store *refs, 750const char*refname,int mustexist, 751const struct string_list *extras, 752const struct string_list *skip, 753struct ref_lock **lock_p, 754struct strbuf *referent, 755unsigned int*type, 756struct strbuf *err) 757{ 758struct ref_lock *lock; 759struct strbuf ref_file = STRBUF_INIT; 760int attempts_remaining =3; 761int ret = TRANSACTION_GENERIC_ERROR; 762 763assert(err); 764files_assert_main_repository(refs,"lock_raw_ref"); 765 766*type =0; 767 768/* First lock the file so it can't change out from under us. */ 769 770*lock_p = lock =xcalloc(1,sizeof(*lock)); 771 772 lock->ref_name =xstrdup(refname); 773files_ref_path(refs, &ref_file, refname); 774 775retry: 776switch(safe_create_leading_directories(ref_file.buf)) { 777case SCLD_OK: 778break;/* success */ 779case SCLD_EXISTS: 780/* 781 * Suppose refname is "refs/foo/bar". We just failed 782 * to create the containing directory, "refs/foo", 783 * because there was a non-directory in the way. This 784 * indicates a D/F conflict, probably because of 785 * another reference such as "refs/foo". There is no 786 * reason to expect this error to be transitory. 787 */ 788if(refs_verify_refname_available(&refs->base, refname, 789 extras, skip, err)) { 790if(mustexist) { 791/* 792 * To the user the relevant error is 793 * that the "mustexist" reference is 794 * missing: 795 */ 796strbuf_reset(err); 797strbuf_addf(err,"unable to resolve reference '%s'", 798 refname); 799}else{ 800/* 801 * The error message set by 802 * refs_verify_refname_available() is 803 * OK. 804 */ 805 ret = TRANSACTION_NAME_CONFLICT; 806} 807}else{ 808/* 809 * The file that is in the way isn't a loose 810 * reference. Report it as a low-level 811 * failure. 812 */ 813strbuf_addf(err,"unable to create lock file%s.lock; " 814"non-directory in the way", 815 ref_file.buf); 816} 817goto error_return; 818case SCLD_VANISHED: 819/* Maybe another process was tidying up. Try again. */ 820if(--attempts_remaining >0) 821goto retry; 822/* fall through */ 823default: 824strbuf_addf(err,"unable to create directory for%s", 825 ref_file.buf); 826goto error_return; 827} 828 829if(!lock->lk) 830 lock->lk =xcalloc(1,sizeof(struct lock_file)); 831 832if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 833if(errno == ENOENT && --attempts_remaining >0) { 834/* 835 * Maybe somebody just deleted one of the 836 * directories leading to ref_file. Try 837 * again: 838 */ 839goto retry; 840}else{ 841unable_to_lock_message(ref_file.buf, errno, err); 842goto error_return; 843} 844} 845 846/* 847 * Now we hold the lock and can read the reference without 848 * fear that its value will change. 849 */ 850 851if(files_read_raw_ref(&refs->base, refname, 852 lock->old_oid.hash, referent, type)) { 853if(errno == ENOENT) { 854if(mustexist) { 855/* Garden variety missing reference. */ 856strbuf_addf(err,"unable to resolve reference '%s'", 857 refname); 858goto error_return; 859}else{ 860/* 861 * Reference is missing, but that's OK. We 862 * know that there is not a conflict with 863 * another loose reference because 864 * (supposing that we are trying to lock 865 * reference "refs/foo/bar"): 866 * 867 * - We were successfully able to create 868 * the lockfile refs/foo/bar.lock, so we 869 * know there cannot be a loose reference 870 * named "refs/foo". 871 * 872 * - We got ENOENT and not EISDIR, so we 873 * know that there cannot be a loose 874 * reference named "refs/foo/bar/baz". 875 */ 876} 877}else if(errno == EISDIR) { 878/* 879 * There is a directory in the way. It might have 880 * contained references that have been deleted. If 881 * we don't require that the reference already 882 * exists, try to remove the directory so that it 883 * doesn't cause trouble when we want to rename the 884 * lockfile into place later. 885 */ 886if(mustexist) { 887/* Garden variety missing reference. */ 888strbuf_addf(err,"unable to resolve reference '%s'", 889 refname); 890goto error_return; 891}else if(remove_dir_recursively(&ref_file, 892 REMOVE_DIR_EMPTY_ONLY)) { 893if(refs_verify_refname_available( 894&refs->base, refname, 895 extras, skip, err)) { 896/* 897 * The error message set by 898 * verify_refname_available() is OK. 899 */ 900 ret = TRANSACTION_NAME_CONFLICT; 901goto error_return; 902}else{ 903/* 904 * We can't delete the directory, 905 * but we also don't know of any 906 * references that it should 907 * contain. 908 */ 909strbuf_addf(err,"there is a non-empty directory '%s' " 910"blocking reference '%s'", 911 ref_file.buf, refname); 912goto error_return; 913} 914} 915}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 916strbuf_addf(err,"unable to resolve reference '%s': " 917"reference broken", refname); 918goto error_return; 919}else{ 920strbuf_addf(err,"unable to resolve reference '%s':%s", 921 refname,strerror(errno)); 922goto error_return; 923} 924 925/* 926 * If the ref did not exist and we are creating it, 927 * make sure there is no existing ref that conflicts 928 * with refname: 929 */ 930if(refs_verify_refname_available( 931&refs->base, refname, 932 extras, skip, err)) 933goto error_return; 934} 935 936 ret =0; 937goto out; 938 939error_return: 940unlock_ref(lock); 941*lock_p = NULL; 942 943out: 944strbuf_release(&ref_file); 945return ret; 946} 947 948static intfiles_peel_ref(struct ref_store *ref_store, 949const char*refname,unsigned char*sha1) 950{ 951struct files_ref_store *refs = 952files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 953"peel_ref"); 954int flag; 955unsigned char base[20]; 956 957if(current_ref_iter && current_ref_iter->refname == refname) { 958struct object_id peeled; 959 960if(ref_iterator_peel(current_ref_iter, &peeled)) 961return-1; 962hashcpy(sha1, peeled.hash); 963return0; 964} 965 966if(refs_read_ref_full(ref_store, refname, 967 RESOLVE_REF_READING, base, &flag)) 968return-1; 969 970/* 971 * If the reference is packed, read its ref_entry from the 972 * cache in the hope that we already know its peeled value. 973 * We only try this optimization on packed references because 974 * (a) forcing the filling of the loose reference cache could 975 * be expensive and (b) loose references anyway usually do not 976 * have REF_KNOWS_PEELED. 977 */ 978if(flag & REF_ISPACKED) { 979struct ref_entry *r =get_packed_ref(refs, refname); 980if(r) { 981if(peel_entry(r,0)) 982return-1; 983hashcpy(sha1, r->u.value.peeled.hash); 984return0; 985} 986} 987 988returnpeel_object(base, sha1); 989} 990 991struct files_ref_iterator { 992struct ref_iterator base; 993 994struct packed_ref_cache *packed_ref_cache; 995struct ref_iterator *iter0; 996unsigned int flags; 997}; 998 999static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1000{1001struct files_ref_iterator *iter =1002(struct files_ref_iterator *)ref_iterator;1003int ok;10041005while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1006if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1007ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1008continue;10091010if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1011!ref_resolves_to_object(iter->iter0->refname,1012 iter->iter0->oid,1013 iter->iter0->flags))1014continue;10151016 iter->base.refname = iter->iter0->refname;1017 iter->base.oid = iter->iter0->oid;1018 iter->base.flags = iter->iter0->flags;1019return ITER_OK;1020}10211022 iter->iter0 = NULL;1023if(ref_iterator_abort(ref_iterator) != ITER_DONE)1024 ok = ITER_ERROR;10251026return ok;1027}10281029static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1030struct object_id *peeled)1031{1032struct files_ref_iterator *iter =1033(struct files_ref_iterator *)ref_iterator;10341035returnref_iterator_peel(iter->iter0, peeled);1036}10371038static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1039{1040struct files_ref_iterator *iter =1041(struct files_ref_iterator *)ref_iterator;1042int ok = ITER_DONE;10431044if(iter->iter0)1045 ok =ref_iterator_abort(iter->iter0);10461047release_packed_ref_cache(iter->packed_ref_cache);1048base_ref_iterator_free(ref_iterator);1049return ok;1050}10511052static struct ref_iterator_vtable files_ref_iterator_vtable = {1053 files_ref_iterator_advance,1054 files_ref_iterator_peel,1055 files_ref_iterator_abort1056};10571058static struct ref_iterator *files_ref_iterator_begin(1059struct ref_store *ref_store,1060const char*prefix,unsigned int flags)1061{1062struct files_ref_store *refs;1063struct ref_dir *loose_dir, *packed_dir;1064struct ref_iterator *loose_iter, *packed_iter;1065struct files_ref_iterator *iter;1066struct ref_iterator *ref_iterator;10671068if(ref_paranoia <0)1069 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1070if(ref_paranoia)1071 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10721073 refs =files_downcast(ref_store,1074 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1075"ref_iterator_begin");10761077 iter =xcalloc(1,sizeof(*iter));1078 ref_iterator = &iter->base;1079base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10801081/*1082 * We must make sure that all loose refs are read before1083 * accessing the packed-refs file; this avoids a race1084 * condition if loose refs are migrated to the packed-refs1085 * file by a simultaneous process, but our in-memory view is1086 * from before the migration. We ensure this as follows:1087 * First, we call prime_ref_dir(), which pre-reads the loose1088 * references for the subtree into the cache. (If they've1089 * already been read, that's OK; we only need to guarantee1090 * that they're read before the packed refs, not *how much*1091 * before.) After that, we call get_packed_ref_cache(), which1092 * internally checks whether the packed-ref cache is up to1093 * date with what is on disk, and re-reads it if not.1094 */10951096 loose_dir =get_loose_refs(refs);10971098if(prefix && *prefix)1099 loose_dir =find_containing_dir(loose_dir, prefix,0);11001101if(loose_dir) {1102prime_ref_dir(loose_dir);1103 loose_iter =cache_ref_iterator_begin(loose_dir);1104}else{1105/* There's nothing to iterate over. */1106 loose_iter =empty_ref_iterator_begin();1107}11081109 iter->packed_ref_cache =get_packed_ref_cache(refs);1110acquire_packed_ref_cache(iter->packed_ref_cache);1111 packed_dir =get_packed_ref_dir(iter->packed_ref_cache);11121113if(prefix && *prefix)1114 packed_dir =find_containing_dir(packed_dir, prefix,0);11151116if(packed_dir) {1117 packed_iter =cache_ref_iterator_begin(packed_dir);1118}else{1119/* There's nothing to iterate over. */1120 packed_iter =empty_ref_iterator_begin();1121}11221123 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1124 iter->flags = flags;11251126return ref_iterator;1127}11281129/*1130 * Verify that the reference locked by lock has the value old_sha1.1131 * Fail if the reference doesn't exist and mustexist is set. Return 01132 * on success. On error, write an error message to err, set errno, and1133 * return a negative value.1134 */1135static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1136const unsigned char*old_sha1,int mustexist,1137struct strbuf *err)1138{1139assert(err);11401141if(refs_read_ref_full(ref_store, lock->ref_name,1142 mustexist ? RESOLVE_REF_READING :0,1143 lock->old_oid.hash, NULL)) {1144if(old_sha1) {1145int save_errno = errno;1146strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1147 errno = save_errno;1148return-1;1149}else{1150oidclr(&lock->old_oid);1151return0;1152}1153}1154if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1155strbuf_addf(err,"ref '%s' is at%sbut expected%s",1156 lock->ref_name,1157oid_to_hex(&lock->old_oid),1158sha1_to_hex(old_sha1));1159 errno = EBUSY;1160return-1;1161}1162return0;1163}11641165static intremove_empty_directories(struct strbuf *path)1166{1167/*1168 * we want to create a file but there is a directory there;1169 * if that is an empty directory (or a directory that contains1170 * only empty directories), remove them.1171 */1172returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1173}11741175static intcreate_reflock(const char*path,void*cb)1176{1177struct lock_file *lk = cb;11781179returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1180}11811182/*1183 * Locks a ref returning the lock on success and NULL on failure.1184 * On failure errno is set to something meaningful.1185 */1186static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1187const char*refname,1188const unsigned char*old_sha1,1189const struct string_list *extras,1190const struct string_list *skip,1191unsigned int flags,int*type,1192struct strbuf *err)1193{1194struct strbuf ref_file = STRBUF_INIT;1195struct ref_lock *lock;1196int last_errno =0;1197int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1198int resolve_flags = RESOLVE_REF_NO_RECURSE;1199int resolved;12001201files_assert_main_repository(refs,"lock_ref_sha1_basic");1202assert(err);12031204 lock =xcalloc(1,sizeof(struct ref_lock));12051206if(mustexist)1207 resolve_flags |= RESOLVE_REF_READING;1208if(flags & REF_DELETING)1209 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12101211files_ref_path(refs, &ref_file, refname);1212 resolved = !!refs_resolve_ref_unsafe(&refs->base,1213 refname, resolve_flags,1214 lock->old_oid.hash, type);1215if(!resolved && errno == EISDIR) {1216/*1217 * we are trying to lock foo but we used to1218 * have foo/bar which now does not exist;1219 * it is normal for the empty directory 'foo'1220 * to remain.1221 */1222if(remove_empty_directories(&ref_file)) {1223 last_errno = errno;1224if(!refs_verify_refname_available(1225&refs->base,1226 refname, extras, skip, err))1227strbuf_addf(err,"there are still refs under '%s'",1228 refname);1229goto error_return;1230}1231 resolved = !!refs_resolve_ref_unsafe(&refs->base,1232 refname, resolve_flags,1233 lock->old_oid.hash, type);1234}1235if(!resolved) {1236 last_errno = errno;1237if(last_errno != ENOTDIR ||1238!refs_verify_refname_available(&refs->base, refname,1239 extras, skip, err))1240strbuf_addf(err,"unable to resolve reference '%s':%s",1241 refname,strerror(last_errno));12421243goto error_return;1244}12451246/*1247 * If the ref did not exist and we are creating it, make sure1248 * there is no existing packed ref whose name begins with our1249 * refname, nor a packed ref whose name is a proper prefix of1250 * our refname.1251 */1252if(is_null_oid(&lock->old_oid) &&1253refs_verify_refname_available(&refs->base, refname,1254 extras, skip, err)) {1255 last_errno = ENOTDIR;1256goto error_return;1257}12581259 lock->lk =xcalloc(1,sizeof(struct lock_file));12601261 lock->ref_name =xstrdup(refname);12621263if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1264 last_errno = errno;1265unable_to_lock_message(ref_file.buf, errno, err);1266goto error_return;1267}12681269if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1270 last_errno = errno;1271goto error_return;1272}1273goto out;12741275 error_return:1276unlock_ref(lock);1277 lock = NULL;12781279 out:1280strbuf_release(&ref_file);1281 errno = last_errno;1282return lock;1283}12841285/*1286 * Write an entry to the packed-refs file for the specified refname.1287 * If peeled is non-NULL, write it as the entry's peeled value.1288 */1289static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1290unsigned char*peeled)1291{1292fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1293if(peeled)1294fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1295}12961297/*1298 * An each_ref_entry_fn that writes the entry to a packed-refs file.1299 */1300static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1301{1302enum peel_status peel_status =peel_entry(entry,0);13031304if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1305error("internal error:%sis not a valid packed reference!",1306 entry->name);1307write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1308 peel_status == PEEL_PEELED ?1309 entry->u.value.peeled.hash : NULL);1310return0;1311}13121313/*1314 * Lock the packed-refs file for writing. Flags is passed to1315 * hold_lock_file_for_update(). Return 0 on success. On errors, set1316 * errno appropriately and return a nonzero value.1317 */1318static intlock_packed_refs(struct files_ref_store *refs,int flags)1319{1320static int timeout_configured =0;1321static int timeout_value =1000;1322struct packed_ref_cache *packed_ref_cache;13231324files_assert_main_repository(refs,"lock_packed_refs");13251326if(!timeout_configured) {1327git_config_get_int("core.packedrefstimeout", &timeout_value);1328 timeout_configured =1;1329}13301331if(hold_lock_file_for_update_timeout(1332&packlock,files_packed_refs_path(refs),1333 flags, timeout_value) <0)1334return-1;1335/*1336 * Get the current packed-refs while holding the lock. If the1337 * packed-refs file has been modified since we last read it,1338 * this will automatically invalidate the cache and re-read1339 * the packed-refs file.1340 */1341 packed_ref_cache =get_packed_ref_cache(refs);1342 packed_ref_cache->lock = &packlock;1343/* Increment the reference count to prevent it from being freed: */1344acquire_packed_ref_cache(packed_ref_cache);1345return0;1346}13471348/*1349 * Write the current version of the packed refs cache from memory to1350 * disk. The packed-refs file must already be locked for writing (see1351 * lock_packed_refs()). Return zero on success. On errors, set errno1352 * and return a nonzero value1353 */1354static intcommit_packed_refs(struct files_ref_store *refs)1355{1356struct packed_ref_cache *packed_ref_cache =1357get_packed_ref_cache(refs);1358int error =0;1359int save_errno =0;1360FILE*out;13611362files_assert_main_repository(refs,"commit_packed_refs");13631364if(!packed_ref_cache->lock)1365die("internal error: packed-refs not locked");13661367 out =fdopen_lock_file(packed_ref_cache->lock,"w");1368if(!out)1369die_errno("unable to fdopen packed-refs descriptor");13701371fprintf_or_die(out,"%s", PACKED_REFS_HEADER);1372do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),13730, write_packed_entry_fn, out);13741375if(commit_lock_file(packed_ref_cache->lock)) {1376 save_errno = errno;1377 error = -1;1378}1379 packed_ref_cache->lock = NULL;1380release_packed_ref_cache(packed_ref_cache);1381 errno = save_errno;1382return error;1383}13841385/*1386 * Rollback the lockfile for the packed-refs file, and discard the1387 * in-memory packed reference cache. (The packed-refs file will be1388 * read anew if it is needed again after this function is called.)1389 */1390static voidrollback_packed_refs(struct files_ref_store *refs)1391{1392struct packed_ref_cache *packed_ref_cache =1393get_packed_ref_cache(refs);13941395files_assert_main_repository(refs,"rollback_packed_refs");13961397if(!packed_ref_cache->lock)1398die("internal error: packed-refs not locked");1399rollback_lock_file(packed_ref_cache->lock);1400 packed_ref_cache->lock = NULL;1401release_packed_ref_cache(packed_ref_cache);1402clear_packed_ref_cache(refs);1403}14041405struct ref_to_prune {1406struct ref_to_prune *next;1407unsigned char sha1[20];1408char name[FLEX_ARRAY];1409};14101411struct pack_refs_cb_data {1412unsigned int flags;1413struct ref_dir *packed_refs;1414struct ref_to_prune *ref_to_prune;1415};14161417/*1418 * An each_ref_entry_fn that is run over loose references only. If1419 * the loose reference can be packed, add an entry in the packed ref1420 * cache. If the reference should be pruned, also add it to1421 * ref_to_prune in the pack_refs_cb_data.1422 */1423static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)1424{1425struct pack_refs_cb_data *cb = cb_data;1426enum peel_status peel_status;1427struct ref_entry *packed_entry;1428int is_tag_ref =starts_with(entry->name,"refs/tags/");14291430/* Do not pack per-worktree refs: */1431if(ref_type(entry->name) != REF_TYPE_NORMAL)1432return0;14331434/* ALWAYS pack tags */1435if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)1436return0;14371438/* Do not pack symbolic or broken refs: */1439if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))1440return0;14411442/* Add a packed ref cache entry equivalent to the loose entry. */1443 peel_status =peel_entry(entry,1);1444if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1445die("internal error peeling reference%s(%s)",1446 entry->name,oid_to_hex(&entry->u.value.oid));1447 packed_entry =find_ref_entry(cb->packed_refs, entry->name);1448if(packed_entry) {1449/* Overwrite existing packed entry with info from loose entry */1450 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;1451oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);1452}else{1453 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,1454 REF_ISPACKED | REF_KNOWS_PEELED,0);1455add_ref_entry(cb->packed_refs, packed_entry);1456}1457oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);14581459/* Schedule the loose reference for pruning if requested. */1460if((cb->flags & PACK_REFS_PRUNE)) {1461struct ref_to_prune *n;1462FLEX_ALLOC_STR(n, name, entry->name);1463hashcpy(n->sha1, entry->u.value.oid.hash);1464 n->next = cb->ref_to_prune;1465 cb->ref_to_prune = n;1466}1467return0;1468}14691470enum{1471 REMOVE_EMPTY_PARENTS_REF =0x01,1472 REMOVE_EMPTY_PARENTS_REFLOG =0x021473};14741475/*1476 * Remove empty parent directories associated with the specified1477 * reference and/or its reflog, but spare [logs/]refs/ and immediate1478 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1479 * REMOVE_EMPTY_PARENTS_REFLOG.1480 */1481static voidtry_remove_empty_parents(struct files_ref_store *refs,1482const char*refname,1483unsigned int flags)1484{1485struct strbuf buf = STRBUF_INIT;1486struct strbuf sb = STRBUF_INIT;1487char*p, *q;1488int i;14891490strbuf_addstr(&buf, refname);1491 p = buf.buf;1492for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1493while(*p && *p !='/')1494 p++;1495/* tolerate duplicate slashes; see check_refname_format() */1496while(*p =='/')1497 p++;1498}1499 q = buf.buf + buf.len;1500while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1501while(q > p && *q !='/')1502 q--;1503while(q > p && *(q-1) =='/')1504 q--;1505if(q == p)1506break;1507strbuf_setlen(&buf, q - buf.buf);15081509strbuf_reset(&sb);1510files_ref_path(refs, &sb, buf.buf);1511if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1512 flags &= ~REMOVE_EMPTY_PARENTS_REF;15131514strbuf_reset(&sb);1515files_reflog_path(refs, &sb, buf.buf);1516if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1517 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1518}1519strbuf_release(&buf);1520strbuf_release(&sb);1521}15221523/* make sure nobody touched the ref, and unlink */1524static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1525{1526struct ref_transaction *transaction;1527struct strbuf err = STRBUF_INIT;15281529if(check_refname_format(r->name,0))1530return;15311532 transaction =ref_store_transaction_begin(&refs->base, &err);1533if(!transaction ||1534ref_transaction_delete(transaction, r->name, r->sha1,1535 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1536ref_transaction_commit(transaction, &err)) {1537ref_transaction_free(transaction);1538error("%s", err.buf);1539strbuf_release(&err);1540return;1541}1542ref_transaction_free(transaction);1543strbuf_release(&err);1544}15451546static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1547{1548while(r) {1549prune_ref(refs, r);1550 r = r->next;1551}1552}15531554static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1555{1556struct files_ref_store *refs =1557files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1558"pack_refs");1559struct pack_refs_cb_data cbdata;15601561memset(&cbdata,0,sizeof(cbdata));1562 cbdata.flags = flags;15631564lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1565 cbdata.packed_refs =get_packed_refs(refs);15661567do_for_each_entry_in_dir(get_loose_refs(refs),0,1568 pack_if_possible_fn, &cbdata);15691570if(commit_packed_refs(refs))1571die_errno("unable to overwrite old ref-pack file");15721573prune_refs(refs, cbdata.ref_to_prune);1574return0;1575}15761577/*1578 * Rewrite the packed-refs file, omitting any refs listed in1579 * 'refnames'. On error, leave packed-refs unchanged, write an error1580 * message to 'err', and return a nonzero value.1581 *1582 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1583 */1584static intrepack_without_refs(struct files_ref_store *refs,1585struct string_list *refnames,struct strbuf *err)1586{1587struct ref_dir *packed;1588struct string_list_item *refname;1589int ret, needs_repacking =0, removed =0;15901591files_assert_main_repository(refs,"repack_without_refs");1592assert(err);15931594/* Look for a packed ref */1595for_each_string_list_item(refname, refnames) {1596if(get_packed_ref(refs, refname->string)) {1597 needs_repacking =1;1598break;1599}1600}16011602/* Avoid locking if we have nothing to do */1603if(!needs_repacking)1604return0;/* no refname exists in packed refs */16051606if(lock_packed_refs(refs,0)) {1607unable_to_lock_message(files_packed_refs_path(refs), errno, err);1608return-1;1609}1610 packed =get_packed_refs(refs);16111612/* Remove refnames from the cache */1613for_each_string_list_item(refname, refnames)1614if(remove_entry_from_dir(packed, refname->string) != -1)1615 removed =1;1616if(!removed) {1617/*1618 * All packed entries disappeared while we were1619 * acquiring the lock.1620 */1621rollback_packed_refs(refs);1622return0;1623}16241625/* Write what remains */1626 ret =commit_packed_refs(refs);1627if(ret)1628strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1629strerror(errno));1630return ret;1631}16321633static intfiles_delete_refs(struct ref_store *ref_store,1634struct string_list *refnames,unsigned int flags)1635{1636struct files_ref_store *refs =1637files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1638struct strbuf err = STRBUF_INIT;1639int i, result =0;16401641if(!refnames->nr)1642return0;16431644 result =repack_without_refs(refs, refnames, &err);1645if(result) {1646/*1647 * If we failed to rewrite the packed-refs file, then1648 * it is unsafe to try to remove loose refs, because1649 * doing so might expose an obsolete packed value for1650 * a reference that might even point at an object that1651 * has been garbage collected.1652 */1653if(refnames->nr ==1)1654error(_("could not delete reference%s:%s"),1655 refnames->items[0].string, err.buf);1656else1657error(_("could not delete references:%s"), err.buf);16581659goto out;1660}16611662for(i =0; i < refnames->nr; i++) {1663const char*refname = refnames->items[i].string;16641665if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))1666 result |=error(_("could not remove reference%s"), refname);1667}16681669out:1670strbuf_release(&err);1671return result;1672}16731674/*1675 * People using contrib's git-new-workdir have .git/logs/refs ->1676 * /some/other/path/.git/logs/refs, and that may live on another device.1677 *1678 * IOW, to avoid cross device rename errors, the temporary renamed log must1679 * live into logs/refs.1680 */1681#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16821683struct rename_cb {1684const char*tmp_renamed_log;1685int true_errno;1686};16871688static intrename_tmp_log_callback(const char*path,void*cb_data)1689{1690struct rename_cb *cb = cb_data;16911692if(rename(cb->tmp_renamed_log, path)) {1693/*1694 * rename(a, b) when b is an existing directory ought1695 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1696 * Sheesh. Record the true errno for error reporting,1697 * but report EISDIR to raceproof_create_file() so1698 * that it knows to retry.1699 */1700 cb->true_errno = errno;1701if(errno == ENOTDIR)1702 errno = EISDIR;1703return-1;1704}else{1705return0;1706}1707}17081709static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1710{1711struct strbuf path = STRBUF_INIT;1712struct strbuf tmp = STRBUF_INIT;1713struct rename_cb cb;1714int ret;17151716files_reflog_path(refs, &path, newrefname);1717files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1718 cb.tmp_renamed_log = tmp.buf;1719 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1720if(ret) {1721if(errno == EISDIR)1722error("directory not empty:%s", path.buf);1723else1724error("unable to move logfile%sto%s:%s",1725 tmp.buf, path.buf,1726strerror(cb.true_errno));1727}17281729strbuf_release(&path);1730strbuf_release(&tmp);1731return ret;1732}17331734static intwrite_ref_to_lockfile(struct ref_lock *lock,1735const unsigned char*sha1,struct strbuf *err);1736static intcommit_ref_update(struct files_ref_store *refs,1737struct ref_lock *lock,1738const unsigned char*sha1,const char*logmsg,1739struct strbuf *err);17401741static intfiles_rename_ref(struct ref_store *ref_store,1742const char*oldrefname,const char*newrefname,1743const char*logmsg)1744{1745struct files_ref_store *refs =1746files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1747unsigned char sha1[20], orig_sha1[20];1748int flag =0, logmoved =0;1749struct ref_lock *lock;1750struct stat loginfo;1751struct strbuf sb_oldref = STRBUF_INIT;1752struct strbuf sb_newref = STRBUF_INIT;1753struct strbuf tmp_renamed_log = STRBUF_INIT;1754int log, ret;1755struct strbuf err = STRBUF_INIT;17561757files_reflog_path(refs, &sb_oldref, oldrefname);1758files_reflog_path(refs, &sb_newref, newrefname);1759files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17601761 log = !lstat(sb_oldref.buf, &loginfo);1762if(log &&S_ISLNK(loginfo.st_mode)) {1763 ret =error("reflog for%sis a symlink", oldrefname);1764goto out;1765}17661767if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1768 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1769 orig_sha1, &flag)) {1770 ret =error("refname%snot found", oldrefname);1771goto out;1772}17731774if(flag & REF_ISSYMREF) {1775 ret =error("refname%sis a symbolic ref, renaming it is not supported",1776 oldrefname);1777goto out;1778}1779if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1780 ret =1;1781goto out;1782}17831784if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1785 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1786 oldrefname,strerror(errno));1787goto out;1788}17891790if(refs_delete_ref(&refs->base, logmsg, oldrefname,1791 orig_sha1, REF_NODEREF)) {1792error("unable to delete old%s", oldrefname);1793goto rollback;1794}17951796/*1797 * Since we are doing a shallow lookup, sha1 is not the1798 * correct value to pass to delete_ref as old_sha1. But that1799 * doesn't matter, because an old_sha1 check wouldn't add to1800 * the safety anyway; we want to delete the reference whatever1801 * its current value.1802 */1803if(!refs_read_ref_full(&refs->base, newrefname,1804 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1805 sha1, NULL) &&1806refs_delete_ref(&refs->base, NULL, newrefname,1807 NULL, REF_NODEREF)) {1808if(errno == EISDIR) {1809struct strbuf path = STRBUF_INIT;1810int result;18111812files_ref_path(refs, &path, newrefname);1813 result =remove_empty_directories(&path);1814strbuf_release(&path);18151816if(result) {1817error("Directory not empty:%s", newrefname);1818goto rollback;1819}1820}else{1821error("unable to delete existing%s", newrefname);1822goto rollback;1823}1824}18251826if(log &&rename_tmp_log(refs, newrefname))1827goto rollback;18281829 logmoved = log;18301831 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1832 REF_NODEREF, NULL, &err);1833if(!lock) {1834error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1835strbuf_release(&err);1836goto rollback;1837}1838hashcpy(lock->old_oid.hash, orig_sha1);18391840if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1841commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {1842error("unable to write current sha1 into%s:%s", newrefname, err.buf);1843strbuf_release(&err);1844goto rollback;1845}18461847 ret =0;1848goto out;18491850 rollback:1851 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1852 REF_NODEREF, NULL, &err);1853if(!lock) {1854error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1855strbuf_release(&err);1856goto rollbacklog;1857}18581859 flag = log_all_ref_updates;1860 log_all_ref_updates = LOG_REFS_NONE;1861if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1862commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {1863error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1864strbuf_release(&err);1865}1866 log_all_ref_updates = flag;18671868 rollbacklog:1869if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1870error("unable to restore logfile%sfrom%s:%s",1871 oldrefname, newrefname,strerror(errno));1872if(!logmoved && log &&1873rename(tmp_renamed_log.buf, sb_oldref.buf))1874error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1875 oldrefname,strerror(errno));1876 ret =1;1877 out:1878strbuf_release(&sb_newref);1879strbuf_release(&sb_oldref);1880strbuf_release(&tmp_renamed_log);18811882return ret;1883}18841885static intclose_ref(struct ref_lock *lock)1886{1887if(close_lock_file(lock->lk))1888return-1;1889return0;1890}18911892static intcommit_ref(struct ref_lock *lock)1893{1894char*path =get_locked_file_path(lock->lk);1895struct stat st;18961897if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1898/*1899 * There is a directory at the path we want to rename1900 * the lockfile to. Hopefully it is empty; try to1901 * delete it.1902 */1903size_t len =strlen(path);1904struct strbuf sb_path = STRBUF_INIT;19051906strbuf_attach(&sb_path, path, len, len);19071908/*1909 * If this fails, commit_lock_file() will also fail1910 * and will report the problem.1911 */1912remove_empty_directories(&sb_path);1913strbuf_release(&sb_path);1914}else{1915free(path);1916}19171918if(commit_lock_file(lock->lk))1919return-1;1920return0;1921}19221923static intopen_or_create_logfile(const char*path,void*cb)1924{1925int*fd = cb;19261927*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1928return(*fd <0) ? -1:0;1929}19301931/*1932 * Create a reflog for a ref. If force_create = 0, only create the1933 * reflog for certain refs (those for which should_autocreate_reflog1934 * returns non-zero). Otherwise, create it regardless of the reference1935 * name. If the logfile already existed or was created, return 0 and1936 * set *logfd to the file descriptor opened for appending to the file.1937 * If no logfile exists and we decided not to create one, return 0 and1938 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1939 * return -1.1940 */1941static intlog_ref_setup(struct files_ref_store *refs,1942const char*refname,int force_create,1943int*logfd,struct strbuf *err)1944{1945struct strbuf logfile_sb = STRBUF_INIT;1946char*logfile;19471948files_reflog_path(refs, &logfile_sb, refname);1949 logfile =strbuf_detach(&logfile_sb, NULL);19501951if(force_create ||should_autocreate_reflog(refname)) {1952if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1953if(errno == ENOENT)1954strbuf_addf(err,"unable to create directory for '%s': "1955"%s", logfile,strerror(errno));1956else if(errno == EISDIR)1957strbuf_addf(err,"there are still logs under '%s'",1958 logfile);1959else1960strbuf_addf(err,"unable to append to '%s':%s",1961 logfile,strerror(errno));19621963goto error;1964}1965}else{1966*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1967if(*logfd <0) {1968if(errno == ENOENT || errno == EISDIR) {1969/*1970 * The logfile doesn't already exist,1971 * but that is not an error; it only1972 * means that we won't write log1973 * entries to it.1974 */1975;1976}else{1977strbuf_addf(err,"unable to append to '%s':%s",1978 logfile,strerror(errno));1979goto error;1980}1981}1982}19831984if(*logfd >=0)1985adjust_shared_perm(logfile);19861987free(logfile);1988return0;19891990error:1991free(logfile);1992return-1;1993}19941995static intfiles_create_reflog(struct ref_store *ref_store,1996const char*refname,int force_create,1997struct strbuf *err)1998{1999struct files_ref_store *refs =2000files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2001int fd;20022003if(log_ref_setup(refs, refname, force_create, &fd, err))2004return-1;20052006if(fd >=0)2007close(fd);20082009return0;2010}20112012static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2013const unsigned char*new_sha1,2014const char*committer,const char*msg)2015{2016int msglen, written;2017unsigned maxlen, len;2018char*logrec;20192020 msglen = msg ?strlen(msg) :0;2021 maxlen =strlen(committer) + msglen +100;2022 logrec =xmalloc(maxlen);2023 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2024sha1_to_hex(old_sha1),2025sha1_to_hex(new_sha1),2026 committer);2027if(msglen)2028 len +=copy_reflog_msg(logrec + len -1, msg) -1;20292030 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2031free(logrec);2032if(written != len)2033return-1;20342035return0;2036}20372038static intfiles_log_ref_write(struct files_ref_store *refs,2039const char*refname,const unsigned char*old_sha1,2040const unsigned char*new_sha1,const char*msg,2041int flags,struct strbuf *err)2042{2043int logfd, result;20442045if(log_all_ref_updates == LOG_REFS_UNSET)2046 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20472048 result =log_ref_setup(refs, refname,2049 flags & REF_FORCE_CREATE_REFLOG,2050&logfd, err);20512052if(result)2053return result;20542055if(logfd <0)2056return0;2057 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2058git_committer_info(0), msg);2059if(result) {2060struct strbuf sb = STRBUF_INIT;2061int save_errno = errno;20622063files_reflog_path(refs, &sb, refname);2064strbuf_addf(err,"unable to append to '%s':%s",2065 sb.buf,strerror(save_errno));2066strbuf_release(&sb);2067close(logfd);2068return-1;2069}2070if(close(logfd)) {2071struct strbuf sb = STRBUF_INIT;2072int save_errno = errno;20732074files_reflog_path(refs, &sb, refname);2075strbuf_addf(err,"unable to append to '%s':%s",2076 sb.buf,strerror(save_errno));2077strbuf_release(&sb);2078return-1;2079}2080return0;2081}20822083/*2084 * Write sha1 into the open lockfile, then close the lockfile. On2085 * errors, rollback the lockfile, fill in *err and2086 * return -1.2087 */2088static intwrite_ref_to_lockfile(struct ref_lock *lock,2089const unsigned char*sha1,struct strbuf *err)2090{2091static char term ='\n';2092struct object *o;2093int fd;20942095 o =parse_object(sha1);2096if(!o) {2097strbuf_addf(err,2098"trying to write ref '%s' with nonexistent object%s",2099 lock->ref_name,sha1_to_hex(sha1));2100unlock_ref(lock);2101return-1;2102}2103if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2104strbuf_addf(err,2105"trying to write non-commit object%sto branch '%s'",2106sha1_to_hex(sha1), lock->ref_name);2107unlock_ref(lock);2108return-1;2109}2110 fd =get_lock_file_fd(lock->lk);2111if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2112write_in_full(fd, &term,1) !=1||2113close_ref(lock) <0) {2114strbuf_addf(err,2115"couldn't write '%s'",get_lock_file_path(lock->lk));2116unlock_ref(lock);2117return-1;2118}2119return0;2120}21212122/*2123 * Commit a change to a loose reference that has already been written2124 * to the loose reference lockfile. Also update the reflogs if2125 * necessary, using the specified lockmsg (which can be NULL).2126 */2127static intcommit_ref_update(struct files_ref_store *refs,2128struct ref_lock *lock,2129const unsigned char*sha1,const char*logmsg,2130struct strbuf *err)2131{2132files_assert_main_repository(refs,"commit_ref_update");21332134clear_loose_ref_cache(refs);2135if(files_log_ref_write(refs, lock->ref_name,2136 lock->old_oid.hash, sha1,2137 logmsg,0, err)) {2138char*old_msg =strbuf_detach(err, NULL);2139strbuf_addf(err,"cannot update the ref '%s':%s",2140 lock->ref_name, old_msg);2141free(old_msg);2142unlock_ref(lock);2143return-1;2144}21452146if(strcmp(lock->ref_name,"HEAD") !=0) {2147/*2148 * Special hack: If a branch is updated directly and HEAD2149 * points to it (may happen on the remote side of a push2150 * for example) then logically the HEAD reflog should be2151 * updated too.2152 * A generic solution implies reverse symref information,2153 * but finding all symrefs pointing to the given branch2154 * would be rather costly for this rare event (the direct2155 * update of a branch) to be worth it. So let's cheat and2156 * check with HEAD only which should cover 99% of all usage2157 * scenarios (even 100% of the default ones).2158 */2159unsigned char head_sha1[20];2160int head_flag;2161const char*head_ref;21622163 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2164 RESOLVE_REF_READING,2165 head_sha1, &head_flag);2166if(head_ref && (head_flag & REF_ISSYMREF) &&2167!strcmp(head_ref, lock->ref_name)) {2168struct strbuf log_err = STRBUF_INIT;2169if(files_log_ref_write(refs,"HEAD",2170 lock->old_oid.hash, sha1,2171 logmsg,0, &log_err)) {2172error("%s", log_err.buf);2173strbuf_release(&log_err);2174}2175}2176}21772178if(commit_ref(lock)) {2179strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2180unlock_ref(lock);2181return-1;2182}21832184unlock_ref(lock);2185return0;2186}21872188static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2189{2190int ret = -1;2191#ifndef NO_SYMLINK_HEAD2192char*ref_path =get_locked_file_path(lock->lk);2193unlink(ref_path);2194 ret =symlink(target, ref_path);2195free(ref_path);21962197if(ret)2198fprintf(stderr,"no symlink - falling back to symbolic ref\n");2199#endif2200return ret;2201}22022203static voidupdate_symref_reflog(struct files_ref_store *refs,2204struct ref_lock *lock,const char*refname,2205const char*target,const char*logmsg)2206{2207struct strbuf err = STRBUF_INIT;2208unsigned char new_sha1[20];2209if(logmsg &&2210!refs_read_ref_full(&refs->base, target,2211 RESOLVE_REF_READING, new_sha1, NULL) &&2212files_log_ref_write(refs, refname, lock->old_oid.hash,2213 new_sha1, logmsg,0, &err)) {2214error("%s", err.buf);2215strbuf_release(&err);2216}2217}22182219static intcreate_symref_locked(struct files_ref_store *refs,2220struct ref_lock *lock,const char*refname,2221const char*target,const char*logmsg)2222{2223if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2224update_symref_reflog(refs, lock, refname, target, logmsg);2225return0;2226}22272228if(!fdopen_lock_file(lock->lk,"w"))2229returnerror("unable to fdopen%s:%s",2230 lock->lk->tempfile.filename.buf,strerror(errno));22312232update_symref_reflog(refs, lock, refname, target, logmsg);22332234/* no error check; commit_ref will check ferror */2235fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2236if(commit_ref(lock) <0)2237returnerror("unable to write symref for%s:%s", refname,2238strerror(errno));2239return0;2240}22412242static intfiles_create_symref(struct ref_store *ref_store,2243const char*refname,const char*target,2244const char*logmsg)2245{2246struct files_ref_store *refs =2247files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2248struct strbuf err = STRBUF_INIT;2249struct ref_lock *lock;2250int ret;22512252 lock =lock_ref_sha1_basic(refs, refname, NULL,2253 NULL, NULL, REF_NODEREF, NULL,2254&err);2255if(!lock) {2256error("%s", err.buf);2257strbuf_release(&err);2258return-1;2259}22602261 ret =create_symref_locked(refs, lock, refname, target, logmsg);2262unlock_ref(lock);2263return ret;2264}22652266intset_worktree_head_symref(const char*gitdir,const char*target,const char*logmsg)2267{2268/*2269 * FIXME: this obviously will not work well for future refs2270 * backends. This function needs to die.2271 */2272struct files_ref_store *refs =2273files_downcast(get_main_ref_store(),2274 REF_STORE_WRITE,2275"set_head_symref");22762277static struct lock_file head_lock;2278struct ref_lock *lock;2279struct strbuf head_path = STRBUF_INIT;2280const char*head_rel;2281int ret;22822283strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2284if(hold_lock_file_for_update(&head_lock, head_path.buf,2285 LOCK_NO_DEREF) <0) {2286struct strbuf err = STRBUF_INIT;2287unable_to_lock_message(head_path.buf, errno, &err);2288error("%s", err.buf);2289strbuf_release(&err);2290strbuf_release(&head_path);2291return-1;2292}22932294/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2295 linked trees */2296 head_rel =remove_leading_path(head_path.buf,2297absolute_path(get_git_common_dir()));2298/* to make use of create_symref_locked(), initialize ref_lock */2299 lock =xcalloc(1,sizeof(struct ref_lock));2300 lock->lk = &head_lock;2301 lock->ref_name =xstrdup(head_rel);23022303 ret =create_symref_locked(refs, lock, head_rel, target, logmsg);23042305unlock_ref(lock);/* will free lock */2306strbuf_release(&head_path);2307return ret;2308}23092310static intfiles_reflog_exists(struct ref_store *ref_store,2311const char*refname)2312{2313struct files_ref_store *refs =2314files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2315struct strbuf sb = STRBUF_INIT;2316struct stat st;2317int ret;23182319files_reflog_path(refs, &sb, refname);2320 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2321strbuf_release(&sb);2322return ret;2323}23242325static intfiles_delete_reflog(struct ref_store *ref_store,2326const char*refname)2327{2328struct files_ref_store *refs =2329files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2330struct strbuf sb = STRBUF_INIT;2331int ret;23322333files_reflog_path(refs, &sb, refname);2334 ret =remove_path(sb.buf);2335strbuf_release(&sb);2336return ret;2337}23382339static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2340{2341struct object_id ooid, noid;2342char*email_end, *message;2343unsigned long timestamp;2344int tz;2345const char*p = sb->buf;23462347/* old SP new SP name <email> SP time TAB msg LF */2348if(!sb->len || sb->buf[sb->len -1] !='\n'||2349parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2350parse_oid_hex(p, &noid, &p) || *p++ !=' '||2351!(email_end =strchr(p,'>')) ||2352 email_end[1] !=' '||2353!(timestamp =strtoul(email_end +2, &message,10)) ||2354!message || message[0] !=' '||2355(message[1] !='+'&& message[1] !='-') ||2356!isdigit(message[2]) || !isdigit(message[3]) ||2357!isdigit(message[4]) || !isdigit(message[5]))2358return0;/* corrupt? */2359 email_end[1] ='\0';2360 tz =strtol(message +1, NULL,10);2361if(message[6] !='\t')2362 message +=6;2363else2364 message +=7;2365returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2366}23672368static char*find_beginning_of_line(char*bob,char*scan)2369{2370while(bob < scan && *(--scan) !='\n')2371;/* keep scanning backwards */2372/*2373 * Return either beginning of the buffer, or LF at the end of2374 * the previous line.2375 */2376return scan;2377}23782379static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2380const char*refname,2381 each_reflog_ent_fn fn,2382void*cb_data)2383{2384struct files_ref_store *refs =2385files_downcast(ref_store, REF_STORE_READ,2386"for_each_reflog_ent_reverse");2387struct strbuf sb = STRBUF_INIT;2388FILE*logfp;2389long pos;2390int ret =0, at_tail =1;23912392files_reflog_path(refs, &sb, refname);2393 logfp =fopen(sb.buf,"r");2394strbuf_release(&sb);2395if(!logfp)2396return-1;23972398/* Jump to the end */2399if(fseek(logfp,0, SEEK_END) <0)2400returnerror("cannot seek back reflog for%s:%s",2401 refname,strerror(errno));2402 pos =ftell(logfp);2403while(!ret &&0< pos) {2404int cnt;2405size_t nread;2406char buf[BUFSIZ];2407char*endp, *scanp;24082409/* Fill next block from the end */2410 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2411if(fseek(logfp, pos - cnt, SEEK_SET))2412returnerror("cannot seek back reflog for%s:%s",2413 refname,strerror(errno));2414 nread =fread(buf, cnt,1, logfp);2415if(nread !=1)2416returnerror("cannot read%dbytes from reflog for%s:%s",2417 cnt, refname,strerror(errno));2418 pos -= cnt;24192420 scanp = endp = buf + cnt;2421if(at_tail && scanp[-1] =='\n')2422/* Looking at the final LF at the end of the file */2423 scanp--;2424 at_tail =0;24252426while(buf < scanp) {2427/*2428 * terminating LF of the previous line, or the beginning2429 * of the buffer.2430 */2431char*bp;24322433 bp =find_beginning_of_line(buf, scanp);24342435if(*bp =='\n') {2436/*2437 * The newline is the end of the previous line,2438 * so we know we have complete line starting2439 * at (bp + 1). Prefix it onto any prior data2440 * we collected for the line and process it.2441 */2442strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2443 scanp = bp;2444 endp = bp +1;2445 ret =show_one_reflog_ent(&sb, fn, cb_data);2446strbuf_reset(&sb);2447if(ret)2448break;2449}else if(!pos) {2450/*2451 * We are at the start of the buffer, and the2452 * start of the file; there is no previous2453 * line, and we have everything for this one.2454 * Process it, and we can end the loop.2455 */2456strbuf_splice(&sb,0,0, buf, endp - buf);2457 ret =show_one_reflog_ent(&sb, fn, cb_data);2458strbuf_reset(&sb);2459break;2460}24612462if(bp == buf) {2463/*2464 * We are at the start of the buffer, and there2465 * is more file to read backwards. Which means2466 * we are in the middle of a line. Note that we2467 * may get here even if *bp was a newline; that2468 * just means we are at the exact end of the2469 * previous line, rather than some spot in the2470 * middle.2471 *2472 * Save away what we have to be combined with2473 * the data from the next read.2474 */2475strbuf_splice(&sb,0,0, buf, endp - buf);2476break;2477}2478}24792480}2481if(!ret && sb.len)2482die("BUG: reverse reflog parser had leftover data");24832484fclose(logfp);2485strbuf_release(&sb);2486return ret;2487}24882489static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2490const char*refname,2491 each_reflog_ent_fn fn,void*cb_data)2492{2493struct files_ref_store *refs =2494files_downcast(ref_store, REF_STORE_READ,2495"for_each_reflog_ent");2496FILE*logfp;2497struct strbuf sb = STRBUF_INIT;2498int ret =0;24992500files_reflog_path(refs, &sb, refname);2501 logfp =fopen(sb.buf,"r");2502strbuf_release(&sb);2503if(!logfp)2504return-1;25052506while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2507 ret =show_one_reflog_ent(&sb, fn, cb_data);2508fclose(logfp);2509strbuf_release(&sb);2510return ret;2511}25122513struct files_reflog_iterator {2514struct ref_iterator base;25152516struct ref_store *ref_store;2517struct dir_iterator *dir_iterator;2518struct object_id oid;2519};25202521static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2522{2523struct files_reflog_iterator *iter =2524(struct files_reflog_iterator *)ref_iterator;2525struct dir_iterator *diter = iter->dir_iterator;2526int ok;25272528while((ok =dir_iterator_advance(diter)) == ITER_OK) {2529int flags;25302531if(!S_ISREG(diter->st.st_mode))2532continue;2533if(diter->basename[0] =='.')2534continue;2535if(ends_with(diter->basename,".lock"))2536continue;25372538if(refs_read_ref_full(iter->ref_store,2539 diter->relative_path,0,2540 iter->oid.hash, &flags)) {2541error("bad ref for%s", diter->path.buf);2542continue;2543}25442545 iter->base.refname = diter->relative_path;2546 iter->base.oid = &iter->oid;2547 iter->base.flags = flags;2548return ITER_OK;2549}25502551 iter->dir_iterator = NULL;2552if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2553 ok = ITER_ERROR;2554return ok;2555}25562557static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2558struct object_id *peeled)2559{2560die("BUG: ref_iterator_peel() called for reflog_iterator");2561}25622563static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2564{2565struct files_reflog_iterator *iter =2566(struct files_reflog_iterator *)ref_iterator;2567int ok = ITER_DONE;25682569if(iter->dir_iterator)2570 ok =dir_iterator_abort(iter->dir_iterator);25712572base_ref_iterator_free(ref_iterator);2573return ok;2574}25752576static struct ref_iterator_vtable files_reflog_iterator_vtable = {2577 files_reflog_iterator_advance,2578 files_reflog_iterator_peel,2579 files_reflog_iterator_abort2580};25812582static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2583{2584struct files_ref_store *refs =2585files_downcast(ref_store, REF_STORE_READ,2586"reflog_iterator_begin");2587struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2588struct ref_iterator *ref_iterator = &iter->base;2589struct strbuf sb = STRBUF_INIT;25902591base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2592files_reflog_path(refs, &sb, NULL);2593 iter->dir_iterator =dir_iterator_begin(sb.buf);2594 iter->ref_store = ref_store;2595strbuf_release(&sb);2596return ref_iterator;2597}25982599static intref_update_reject_duplicates(struct string_list *refnames,2600struct strbuf *err)2601{2602int i, n = refnames->nr;26032604assert(err);26052606for(i =1; i < n; i++)2607if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2608strbuf_addf(err,2609"multiple updates for ref '%s' not allowed.",2610 refnames->items[i].string);2611return1;2612}2613return0;2614}26152616/*2617 * If update is a direct update of head_ref (the reference pointed to2618 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2619 */2620static intsplit_head_update(struct ref_update *update,2621struct ref_transaction *transaction,2622const char*head_ref,2623struct string_list *affected_refnames,2624struct strbuf *err)2625{2626struct string_list_item *item;2627struct ref_update *new_update;26282629if((update->flags & REF_LOG_ONLY) ||2630(update->flags & REF_ISPRUNING) ||2631(update->flags & REF_UPDATE_VIA_HEAD))2632return0;26332634if(strcmp(update->refname, head_ref))2635return0;26362637/*2638 * First make sure that HEAD is not already in the2639 * transaction. This insertion is O(N) in the transaction2640 * size, but it happens at most once per transaction.2641 */2642 item =string_list_insert(affected_refnames,"HEAD");2643if(item->util) {2644/* An entry already existed */2645strbuf_addf(err,2646"multiple updates for 'HEAD' (including one "2647"via its referent '%s') are not allowed",2648 update->refname);2649return TRANSACTION_NAME_CONFLICT;2650}26512652 new_update =ref_transaction_add_update(2653 transaction,"HEAD",2654 update->flags | REF_LOG_ONLY | REF_NODEREF,2655 update->new_sha1, update->old_sha1,2656 update->msg);26572658 item->util = new_update;26592660return0;2661}26622663/*2664 * update is for a symref that points at referent and doesn't have2665 * REF_NODEREF set. Split it into two updates:2666 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2667 * - A new, separate update for the referent reference2668 * Note that the new update will itself be subject to splitting when2669 * the iteration gets to it.2670 */2671static intsplit_symref_update(struct files_ref_store *refs,2672struct ref_update *update,2673const char*referent,2674struct ref_transaction *transaction,2675struct string_list *affected_refnames,2676struct strbuf *err)2677{2678struct string_list_item *item;2679struct ref_update *new_update;2680unsigned int new_flags;26812682/*2683 * First make sure that referent is not already in the2684 * transaction. This insertion is O(N) in the transaction2685 * size, but it happens at most once per symref in a2686 * transaction.2687 */2688 item =string_list_insert(affected_refnames, referent);2689if(item->util) {2690/* An entry already existed */2691strbuf_addf(err,2692"multiple updates for '%s' (including one "2693"via symref '%s') are not allowed",2694 referent, update->refname);2695return TRANSACTION_NAME_CONFLICT;2696}26972698 new_flags = update->flags;2699if(!strcmp(update->refname,"HEAD")) {2700/*2701 * Record that the new update came via HEAD, so that2702 * when we process it, split_head_update() doesn't try2703 * to add another reflog update for HEAD. Note that2704 * this bit will be propagated if the new_update2705 * itself needs to be split.2706 */2707 new_flags |= REF_UPDATE_VIA_HEAD;2708}27092710 new_update =ref_transaction_add_update(2711 transaction, referent, new_flags,2712 update->new_sha1, update->old_sha1,2713 update->msg);27142715 new_update->parent_update = update;27162717/*2718 * Change the symbolic ref update to log only. Also, it2719 * doesn't need to check its old SHA-1 value, as that will be2720 * done when new_update is processed.2721 */2722 update->flags |= REF_LOG_ONLY | REF_NODEREF;2723 update->flags &= ~REF_HAVE_OLD;27242725 item->util = new_update;27262727return0;2728}27292730/*2731 * Return the refname under which update was originally requested.2732 */2733static const char*original_update_refname(struct ref_update *update)2734{2735while(update->parent_update)2736 update = update->parent_update;27372738return update->refname;2739}27402741/*2742 * Check whether the REF_HAVE_OLD and old_oid values stored in update2743 * are consistent with oid, which is the reference's current value. If2744 * everything is OK, return 0; otherwise, write an error message to2745 * err and return -1.2746 */2747static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2748struct strbuf *err)2749{2750if(!(update->flags & REF_HAVE_OLD) ||2751!hashcmp(oid->hash, update->old_sha1))2752return0;27532754if(is_null_sha1(update->old_sha1))2755strbuf_addf(err,"cannot lock ref '%s': "2756"reference already exists",2757original_update_refname(update));2758else if(is_null_oid(oid))2759strbuf_addf(err,"cannot lock ref '%s': "2760"reference is missing but expected%s",2761original_update_refname(update),2762sha1_to_hex(update->old_sha1));2763else2764strbuf_addf(err,"cannot lock ref '%s': "2765"is at%sbut expected%s",2766original_update_refname(update),2767oid_to_hex(oid),2768sha1_to_hex(update->old_sha1));27692770return-1;2771}27722773/*2774 * Prepare for carrying out update:2775 * - Lock the reference referred to by update.2776 * - Read the reference under lock.2777 * - Check that its old SHA-1 value (if specified) is correct, and in2778 * any case record it in update->lock->old_oid for later use when2779 * writing the reflog.2780 * - If it is a symref update without REF_NODEREF, split it up into a2781 * REF_LOG_ONLY update of the symref and add a separate update for2782 * the referent to transaction.2783 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2784 * update of HEAD.2785 */2786static intlock_ref_for_update(struct files_ref_store *refs,2787struct ref_update *update,2788struct ref_transaction *transaction,2789const char*head_ref,2790struct string_list *affected_refnames,2791struct strbuf *err)2792{2793struct strbuf referent = STRBUF_INIT;2794int mustexist = (update->flags & REF_HAVE_OLD) &&2795!is_null_sha1(update->old_sha1);2796int ret;2797struct ref_lock *lock;27982799files_assert_main_repository(refs,"lock_ref_for_update");28002801if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))2802 update->flags |= REF_DELETING;28032804if(head_ref) {2805 ret =split_head_update(update, transaction, head_ref,2806 affected_refnames, err);2807if(ret)2808return ret;2809}28102811 ret =lock_raw_ref(refs, update->refname, mustexist,2812 affected_refnames, NULL,2813&lock, &referent,2814&update->type, err);2815if(ret) {2816char*reason;28172818 reason =strbuf_detach(err, NULL);2819strbuf_addf(err,"cannot lock ref '%s':%s",2820original_update_refname(update), reason);2821free(reason);2822return ret;2823}28242825 update->backend_data = lock;28262827if(update->type & REF_ISSYMREF) {2828if(update->flags & REF_NODEREF) {2829/*2830 * We won't be reading the referent as part of2831 * the transaction, so we have to read it here2832 * to record and possibly check old_sha1:2833 */2834if(refs_read_ref_full(&refs->base,2835 referent.buf,0,2836 lock->old_oid.hash, NULL)) {2837if(update->flags & REF_HAVE_OLD) {2838strbuf_addf(err,"cannot lock ref '%s': "2839"error reading reference",2840original_update_refname(update));2841return-1;2842}2843}else if(check_old_oid(update, &lock->old_oid, err)) {2844return TRANSACTION_GENERIC_ERROR;2845}2846}else{2847/*2848 * Create a new update for the reference this2849 * symref is pointing at. Also, we will record2850 * and verify old_sha1 for this update as part2851 * of processing the split-off update, so we2852 * don't have to do it here.2853 */2854 ret =split_symref_update(refs, update,2855 referent.buf, transaction,2856 affected_refnames, err);2857if(ret)2858return ret;2859}2860}else{2861struct ref_update *parent_update;28622863if(check_old_oid(update, &lock->old_oid, err))2864return TRANSACTION_GENERIC_ERROR;28652866/*2867 * If this update is happening indirectly because of a2868 * symref update, record the old SHA-1 in the parent2869 * update:2870 */2871for(parent_update = update->parent_update;2872 parent_update;2873 parent_update = parent_update->parent_update) {2874struct ref_lock *parent_lock = parent_update->backend_data;2875oidcpy(&parent_lock->old_oid, &lock->old_oid);2876}2877}28782879if((update->flags & REF_HAVE_NEW) &&2880!(update->flags & REF_DELETING) &&2881!(update->flags & REF_LOG_ONLY)) {2882if(!(update->type & REF_ISSYMREF) &&2883!hashcmp(lock->old_oid.hash, update->new_sha1)) {2884/*2885 * The reference already has the desired2886 * value, so we don't need to write it.2887 */2888}else if(write_ref_to_lockfile(lock, update->new_sha1,2889 err)) {2890char*write_err =strbuf_detach(err, NULL);28912892/*2893 * The lock was freed upon failure of2894 * write_ref_to_lockfile():2895 */2896 update->backend_data = NULL;2897strbuf_addf(err,2898"cannot update ref '%s':%s",2899 update->refname, write_err);2900free(write_err);2901return TRANSACTION_GENERIC_ERROR;2902}else{2903 update->flags |= REF_NEEDS_COMMIT;2904}2905}2906if(!(update->flags & REF_NEEDS_COMMIT)) {2907/*2908 * We didn't call write_ref_to_lockfile(), so2909 * the lockfile is still open. Close it to2910 * free up the file descriptor:2911 */2912if(close_ref(lock)) {2913strbuf_addf(err,"couldn't close '%s.lock'",2914 update->refname);2915return TRANSACTION_GENERIC_ERROR;2916}2917}2918return0;2919}29202921static intfiles_transaction_commit(struct ref_store *ref_store,2922struct ref_transaction *transaction,2923struct strbuf *err)2924{2925struct files_ref_store *refs =2926files_downcast(ref_store, REF_STORE_WRITE,2927"ref_transaction_commit");2928int ret =0, i;2929struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2930struct string_list_item *ref_to_delete;2931struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2932char*head_ref = NULL;2933int head_type;2934struct object_id head_oid;2935struct strbuf sb = STRBUF_INIT;29362937assert(err);29382939if(transaction->state != REF_TRANSACTION_OPEN)2940die("BUG: commit called for transaction that is not open");29412942if(!transaction->nr) {2943 transaction->state = REF_TRANSACTION_CLOSED;2944return0;2945}29462947/*2948 * Fail if a refname appears more than once in the2949 * transaction. (If we end up splitting up any updates using2950 * split_symref_update() or split_head_update(), those2951 * functions will check that the new updates don't have the2952 * same refname as any existing ones.)2953 */2954for(i =0; i < transaction->nr; i++) {2955struct ref_update *update = transaction->updates[i];2956struct string_list_item *item =2957string_list_append(&affected_refnames, update->refname);29582959/*2960 * We store a pointer to update in item->util, but at2961 * the moment we never use the value of this field2962 * except to check whether it is non-NULL.2963 */2964 item->util = update;2965}2966string_list_sort(&affected_refnames);2967if(ref_update_reject_duplicates(&affected_refnames, err)) {2968 ret = TRANSACTION_GENERIC_ERROR;2969goto cleanup;2970}29712972/*2973 * Special hack: If a branch is updated directly and HEAD2974 * points to it (may happen on the remote side of a push2975 * for example) then logically the HEAD reflog should be2976 * updated too.2977 *2978 * A generic solution would require reverse symref lookups,2979 * but finding all symrefs pointing to a given branch would be2980 * rather costly for this rare event (the direct update of a2981 * branch) to be worth it. So let's cheat and check with HEAD2982 * only, which should cover 99% of all usage scenarios (even2983 * 100% of the default ones).2984 *2985 * So if HEAD is a symbolic reference, then record the name of2986 * the reference that it points to. If we see an update of2987 * head_ref within the transaction, then split_head_update()2988 * arranges for the reflog of HEAD to be updated, too.2989 */2990 head_ref =refs_resolve_refdup(ref_store,"HEAD",2991 RESOLVE_REF_NO_RECURSE,2992 head_oid.hash, &head_type);29932994if(head_ref && !(head_type & REF_ISSYMREF)) {2995free(head_ref);2996 head_ref = NULL;2997}29982999/*3000 * Acquire all locks, verify old values if provided, check3001 * that new values are valid, and write new values to the3002 * lockfiles, ready to be activated. Only keep one lockfile3003 * open at a time to avoid running out of file descriptors.3004 */3005for(i =0; i < transaction->nr; i++) {3006struct ref_update *update = transaction->updates[i];30073008 ret =lock_ref_for_update(refs, update, transaction,3009 head_ref, &affected_refnames, err);3010if(ret)3011goto cleanup;3012}30133014/* Perform updates first so live commits remain referenced */3015for(i =0; i < transaction->nr; i++) {3016struct ref_update *update = transaction->updates[i];3017struct ref_lock *lock = update->backend_data;30183019if(update->flags & REF_NEEDS_COMMIT ||3020 update->flags & REF_LOG_ONLY) {3021if(files_log_ref_write(refs,3022 lock->ref_name,3023 lock->old_oid.hash,3024 update->new_sha1,3025 update->msg, update->flags,3026 err)) {3027char*old_msg =strbuf_detach(err, NULL);30283029strbuf_addf(err,"cannot update the ref '%s':%s",3030 lock->ref_name, old_msg);3031free(old_msg);3032unlock_ref(lock);3033 update->backend_data = NULL;3034 ret = TRANSACTION_GENERIC_ERROR;3035goto cleanup;3036}3037}3038if(update->flags & REF_NEEDS_COMMIT) {3039clear_loose_ref_cache(refs);3040if(commit_ref(lock)) {3041strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3042unlock_ref(lock);3043 update->backend_data = NULL;3044 ret = TRANSACTION_GENERIC_ERROR;3045goto cleanup;3046}3047}3048}3049/* Perform deletes now that updates are safely completed */3050for(i =0; i < transaction->nr; i++) {3051struct ref_update *update = transaction->updates[i];3052struct ref_lock *lock = update->backend_data;30533054if(update->flags & REF_DELETING &&3055!(update->flags & REF_LOG_ONLY)) {3056if(!(update->type & REF_ISPACKED) ||3057 update->type & REF_ISSYMREF) {3058/* It is a loose reference. */3059strbuf_reset(&sb);3060files_ref_path(refs, &sb, lock->ref_name);3061if(unlink_or_msg(sb.buf, err)) {3062 ret = TRANSACTION_GENERIC_ERROR;3063goto cleanup;3064}3065 update->flags |= REF_DELETED_LOOSE;3066}30673068if(!(update->flags & REF_ISPRUNING))3069string_list_append(&refs_to_delete,3070 lock->ref_name);3071}3072}30733074if(repack_without_refs(refs, &refs_to_delete, err)) {3075 ret = TRANSACTION_GENERIC_ERROR;3076goto cleanup;3077}30783079/* Delete the reflogs of any references that were deleted: */3080for_each_string_list_item(ref_to_delete, &refs_to_delete) {3081strbuf_reset(&sb);3082files_reflog_path(refs, &sb, ref_to_delete->string);3083if(!unlink_or_warn(sb.buf))3084try_remove_empty_parents(refs, ref_to_delete->string,3085 REMOVE_EMPTY_PARENTS_REFLOG);3086}30873088clear_loose_ref_cache(refs);30893090cleanup:3091strbuf_release(&sb);3092 transaction->state = REF_TRANSACTION_CLOSED;30933094for(i =0; i < transaction->nr; i++) {3095struct ref_update *update = transaction->updates[i];3096struct ref_lock *lock = update->backend_data;30973098if(lock)3099unlock_ref(lock);31003101if(update->flags & REF_DELETED_LOOSE) {3102/*3103 * The loose reference was deleted. Delete any3104 * empty parent directories. (Note that this3105 * can only work because we have already3106 * removed the lockfile.)3107 */3108try_remove_empty_parents(refs, update->refname,3109 REMOVE_EMPTY_PARENTS_REF);3110}3111}31123113string_list_clear(&refs_to_delete,0);3114free(head_ref);3115string_list_clear(&affected_refnames,0);31163117return ret;3118}31193120static intref_present(const char*refname,3121const struct object_id *oid,int flags,void*cb_data)3122{3123struct string_list *affected_refnames = cb_data;31243125returnstring_list_has_string(affected_refnames, refname);3126}31273128static intfiles_initial_transaction_commit(struct ref_store *ref_store,3129struct ref_transaction *transaction,3130struct strbuf *err)3131{3132struct files_ref_store *refs =3133files_downcast(ref_store, REF_STORE_WRITE,3134"initial_ref_transaction_commit");3135int ret =0, i;3136struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31373138assert(err);31393140if(transaction->state != REF_TRANSACTION_OPEN)3141die("BUG: commit called for transaction that is not open");31423143/* Fail if a refname appears more than once in the transaction: */3144for(i =0; i < transaction->nr; i++)3145string_list_append(&affected_refnames,3146 transaction->updates[i]->refname);3147string_list_sort(&affected_refnames);3148if(ref_update_reject_duplicates(&affected_refnames, err)) {3149 ret = TRANSACTION_GENERIC_ERROR;3150goto cleanup;3151}31523153/*3154 * It's really undefined to call this function in an active3155 * repository or when there are existing references: we are3156 * only locking and changing packed-refs, so (1) any3157 * simultaneous processes might try to change a reference at3158 * the same time we do, and (2) any existing loose versions of3159 * the references that we are setting would have precedence3160 * over our values. But some remote helpers create the remote3161 * "HEAD" and "master" branches before calling this function,3162 * so here we really only check that none of the references3163 * that we are creating already exists.3164 */3165if(refs_for_each_rawref(&refs->base, ref_present,3166&affected_refnames))3167die("BUG: initial ref transaction called with existing refs");31683169for(i =0; i < transaction->nr; i++) {3170struct ref_update *update = transaction->updates[i];31713172if((update->flags & REF_HAVE_OLD) &&3173!is_null_sha1(update->old_sha1))3174die("BUG: initial ref transaction with old_sha1 set");3175if(refs_verify_refname_available(&refs->base, update->refname,3176&affected_refnames, NULL,3177 err)) {3178 ret = TRANSACTION_NAME_CONFLICT;3179goto cleanup;3180}3181}31823183if(lock_packed_refs(refs,0)) {3184strbuf_addf(err,"unable to lock packed-refs file:%s",3185strerror(errno));3186 ret = TRANSACTION_GENERIC_ERROR;3187goto cleanup;3188}31893190for(i =0; i < transaction->nr; i++) {3191struct ref_update *update = transaction->updates[i];31923193if((update->flags & REF_HAVE_NEW) &&3194!is_null_sha1(update->new_sha1))3195add_packed_ref(refs, update->refname, update->new_sha1);3196}31973198if(commit_packed_refs(refs)) {3199strbuf_addf(err,"unable to commit packed-refs file:%s",3200strerror(errno));3201 ret = TRANSACTION_GENERIC_ERROR;3202goto cleanup;3203}32043205cleanup:3206 transaction->state = REF_TRANSACTION_CLOSED;3207string_list_clear(&affected_refnames,0);3208return ret;3209}32103211struct expire_reflog_cb {3212unsigned int flags;3213 reflog_expiry_should_prune_fn *should_prune_fn;3214void*policy_cb;3215FILE*newlog;3216struct object_id last_kept_oid;3217};32183219static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3220const char*email,unsigned long timestamp,int tz,3221const char*message,void*cb_data)3222{3223struct expire_reflog_cb *cb = cb_data;3224struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32253226if(cb->flags & EXPIRE_REFLOGS_REWRITE)3227 ooid = &cb->last_kept_oid;32283229if((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,3230 message, policy_cb)) {3231if(!cb->newlog)3232printf("would prune%s", message);3233else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3234printf("prune%s", message);3235}else{3236if(cb->newlog) {3237fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3238oid_to_hex(ooid),oid_to_hex(noid),3239 email, timestamp, tz, message);3240oidcpy(&cb->last_kept_oid, noid);3241}3242if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3243printf("keep%s", message);3244}3245return0;3246}32473248static intfiles_reflog_expire(struct ref_store *ref_store,3249const char*refname,const unsigned char*sha1,3250unsigned int flags,3251 reflog_expiry_prepare_fn prepare_fn,3252 reflog_expiry_should_prune_fn should_prune_fn,3253 reflog_expiry_cleanup_fn cleanup_fn,3254void*policy_cb_data)3255{3256struct files_ref_store *refs =3257files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3258static struct lock_file reflog_lock;3259struct expire_reflog_cb cb;3260struct ref_lock *lock;3261struct strbuf log_file_sb = STRBUF_INIT;3262char*log_file;3263int status =0;3264int type;3265struct strbuf err = STRBUF_INIT;32663267memset(&cb,0,sizeof(cb));3268 cb.flags = flags;3269 cb.policy_cb = policy_cb_data;3270 cb.should_prune_fn = should_prune_fn;32713272/*3273 * The reflog file is locked by holding the lock on the3274 * reference itself, plus we might need to update the3275 * reference if --updateref was specified:3276 */3277 lock =lock_ref_sha1_basic(refs, refname, sha1,3278 NULL, NULL, REF_NODEREF,3279&type, &err);3280if(!lock) {3281error("cannot lock ref '%s':%s", refname, err.buf);3282strbuf_release(&err);3283return-1;3284}3285if(!refs_reflog_exists(ref_store, refname)) {3286unlock_ref(lock);3287return0;3288}32893290files_reflog_path(refs, &log_file_sb, refname);3291 log_file =strbuf_detach(&log_file_sb, NULL);3292if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3293/*3294 * Even though holding $GIT_DIR/logs/$reflog.lock has3295 * no locking implications, we use the lock_file3296 * machinery here anyway because it does a lot of the3297 * work we need, including cleaning up if the program3298 * exits unexpectedly.3299 */3300if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3301struct strbuf err = STRBUF_INIT;3302unable_to_lock_message(log_file, errno, &err);3303error("%s", err.buf);3304strbuf_release(&err);3305goto failure;3306}3307 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3308if(!cb.newlog) {3309error("cannot fdopen%s(%s)",3310get_lock_file_path(&reflog_lock),strerror(errno));3311goto failure;3312}3313}33143315(*prepare_fn)(refname, sha1, cb.policy_cb);3316refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3317(*cleanup_fn)(cb.policy_cb);33183319if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3320/*3321 * It doesn't make sense to adjust a reference pointed3322 * to by a symbolic ref based on expiring entries in3323 * the symbolic reference's reflog. Nor can we update3324 * a reference if there are no remaining reflog3325 * entries.3326 */3327int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3328!(type & REF_ISSYMREF) &&3329!is_null_oid(&cb.last_kept_oid);33303331if(close_lock_file(&reflog_lock)) {3332 status |=error("couldn't write%s:%s", log_file,3333strerror(errno));3334}else if(update &&3335(write_in_full(get_lock_file_fd(lock->lk),3336oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3337write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3338close_ref(lock) <0)) {3339 status |=error("couldn't write%s",3340get_lock_file_path(lock->lk));3341rollback_lock_file(&reflog_lock);3342}else if(commit_lock_file(&reflog_lock)) {3343 status |=error("unable to write reflog '%s' (%s)",3344 log_file,strerror(errno));3345}else if(update &&commit_ref(lock)) {3346 status |=error("couldn't set%s", lock->ref_name);3347}3348}3349free(log_file);3350unlock_ref(lock);3351return status;33523353 failure:3354rollback_lock_file(&reflog_lock);3355free(log_file);3356unlock_ref(lock);3357return-1;3358}33593360static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3361{3362struct files_ref_store *refs =3363files_downcast(ref_store, REF_STORE_WRITE,"init_db");3364struct strbuf sb = STRBUF_INIT;33653366/*3367 * Create .git/refs/{heads,tags}3368 */3369files_ref_path(refs, &sb,"refs/heads");3370safe_create_dir(sb.buf,1);33713372strbuf_reset(&sb);3373files_ref_path(refs, &sb,"refs/tags");3374safe_create_dir(sb.buf,1);33753376strbuf_release(&sb);3377return0;3378}33793380struct ref_storage_be refs_be_files = {3381 NULL,3382"files",3383 files_ref_store_create,3384 files_init_db,3385 files_transaction_commit,3386 files_initial_transaction_commit,33873388 files_pack_refs,3389 files_peel_ref,3390 files_create_symref,3391 files_delete_refs,3392 files_rename_ref,33933394 files_ref_iterator_begin,3395 files_read_raw_ref,33963397 files_reflog_iterator_begin,3398 files_for_each_reflog_ent,3399 files_for_each_reflog_ent_reverse,3400 files_reflog_exists,3401 files_create_reflog,3402 files_delete_reflog,3403 files_reflog_expire3404};