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->base, NULL); 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 */ 433static voidloose_fill_ref_dir(struct ref_store *ref_store, 434struct ref_dir *dir,const char*dirname) 435{ 436struct files_ref_store *refs = 437files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 438DIR*d; 439struct dirent *de; 440int dirnamelen =strlen(dirname); 441struct strbuf refname; 442struct strbuf path = STRBUF_INIT; 443size_t path_baselen; 444 445files_ref_path(refs, &path, dirname); 446 path_baselen = path.len; 447 448 d =opendir(path.buf); 449if(!d) { 450strbuf_release(&path); 451return; 452} 453 454strbuf_init(&refname, dirnamelen +257); 455strbuf_add(&refname, dirname, dirnamelen); 456 457while((de =readdir(d)) != NULL) { 458unsigned char sha1[20]; 459struct stat st; 460int flag; 461 462if(de->d_name[0] =='.') 463continue; 464if(ends_with(de->d_name,".lock")) 465continue; 466strbuf_addstr(&refname, de->d_name); 467strbuf_addstr(&path, de->d_name); 468if(stat(path.buf, &st) <0) { 469;/* silently ignore */ 470}else if(S_ISDIR(st.st_mode)) { 471strbuf_addch(&refname,'/'); 472add_entry_to_dir(dir, 473create_dir_entry(dir->cache, refname.buf, 474 refname.len,1)); 475}else{ 476if(!refs_resolve_ref_unsafe(&refs->base, 477 refname.buf, 478 RESOLVE_REF_READING, 479 sha1, &flag)) { 480hashclr(sha1); 481 flag |= REF_ISBROKEN; 482}else if(is_null_sha1(sha1)) { 483/* 484 * It is so astronomically unlikely 485 * that NULL_SHA1 is the SHA-1 of an 486 * actual object that we consider its 487 * appearance in a loose reference 488 * file to be repo corruption 489 * (probably due to a software bug). 490 */ 491 flag |= REF_ISBROKEN; 492} 493 494if(check_refname_format(refname.buf, 495 REFNAME_ALLOW_ONELEVEL)) { 496if(!refname_is_safe(refname.buf)) 497die("loose refname is dangerous:%s", refname.buf); 498hashclr(sha1); 499 flag |= REF_BAD_NAME | REF_ISBROKEN; 500} 501add_entry_to_dir(dir, 502create_ref_entry(refname.buf, sha1, flag,0)); 503} 504strbuf_setlen(&refname, dirnamelen); 505strbuf_setlen(&path, path_baselen); 506} 507strbuf_release(&refname); 508strbuf_release(&path); 509closedir(d); 510 511/* 512 * Manually add refs/bisect, which, being per-worktree, might 513 * not appear in the directory listing for refs/ in the main 514 * repo. 515 */ 516if(!strcmp(dirname,"refs/")) { 517int pos =search_ref_dir(dir,"refs/bisect/",12); 518 519if(pos <0) { 520struct ref_entry *child_entry =create_dir_entry( 521 dir->cache,"refs/bisect/",12,1); 522add_entry_to_dir(dir, child_entry); 523} 524} 525} 526 527static struct ref_dir *get_loose_refs(struct files_ref_store *refs) 528{ 529if(!refs->loose) { 530/* 531 * Mark the top-level directory complete because we 532 * are about to read the only subdirectory that can 533 * hold references: 534 */ 535 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 536 537/* We're going to fill the top level ourselves: */ 538 refs->loose->root->flag &= ~REF_INCOMPLETE; 539 540/* 541 * Add an incomplete entry for "refs/" (to be filled 542 * lazily): 543 */ 544add_entry_to_dir(get_ref_dir(refs->loose->root), 545create_dir_entry(refs->loose,"refs/",5,1)); 546} 547returnget_ref_dir(refs->loose->root); 548} 549 550/* 551 * Return the ref_entry for the given refname from the packed 552 * references. If it does not exist, return NULL. 553 */ 554static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 555const char*refname) 556{ 557returnfind_ref_entry(get_packed_refs(refs), refname); 558} 559 560/* 561 * A loose ref file doesn't exist; check for a packed ref. 562 */ 563static intresolve_packed_ref(struct files_ref_store *refs, 564const char*refname, 565unsigned char*sha1,unsigned int*flags) 566{ 567struct ref_entry *entry; 568 569/* 570 * The loose reference file does not exist; check for a packed 571 * reference. 572 */ 573 entry =get_packed_ref(refs, refname); 574if(entry) { 575hashcpy(sha1, entry->u.value.oid.hash); 576*flags |= REF_ISPACKED; 577return0; 578} 579/* refname is not a packed reference. */ 580return-1; 581} 582 583static intfiles_read_raw_ref(struct ref_store *ref_store, 584const char*refname,unsigned char*sha1, 585struct strbuf *referent,unsigned int*type) 586{ 587struct files_ref_store *refs = 588files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 589struct strbuf sb_contents = STRBUF_INIT; 590struct strbuf sb_path = STRBUF_INIT; 591const char*path; 592const char*buf; 593struct stat st; 594int fd; 595int ret = -1; 596int save_errno; 597int remaining_retries =3; 598 599*type =0; 600strbuf_reset(&sb_path); 601 602files_ref_path(refs, &sb_path, refname); 603 604 path = sb_path.buf; 605 606stat_ref: 607/* 608 * We might have to loop back here to avoid a race 609 * condition: first we lstat() the file, then we try 610 * to read it as a link or as a file. But if somebody 611 * changes the type of the file (file <-> directory 612 * <-> symlink) between the lstat() and reading, then 613 * we don't want to report that as an error but rather 614 * try again starting with the lstat(). 615 * 616 * We'll keep a count of the retries, though, just to avoid 617 * any confusing situation sending us into an infinite loop. 618 */ 619 620if(remaining_retries-- <=0) 621goto out; 622 623if(lstat(path, &st) <0) { 624if(errno != ENOENT) 625goto out; 626if(resolve_packed_ref(refs, refname, sha1, type)) { 627 errno = ENOENT; 628goto out; 629} 630 ret =0; 631goto out; 632} 633 634/* Follow "normalized" - ie "refs/.." symlinks by hand */ 635if(S_ISLNK(st.st_mode)) { 636strbuf_reset(&sb_contents); 637if(strbuf_readlink(&sb_contents, path,0) <0) { 638if(errno == ENOENT || errno == EINVAL) 639/* inconsistent with lstat; retry */ 640goto stat_ref; 641else 642goto out; 643} 644if(starts_with(sb_contents.buf,"refs/") && 645!check_refname_format(sb_contents.buf,0)) { 646strbuf_swap(&sb_contents, referent); 647*type |= REF_ISSYMREF; 648 ret =0; 649goto out; 650} 651/* 652 * It doesn't look like a refname; fall through to just 653 * treating it like a non-symlink, and reading whatever it 654 * points to. 655 */ 656} 657 658/* Is it a directory? */ 659if(S_ISDIR(st.st_mode)) { 660/* 661 * Even though there is a directory where the loose 662 * ref is supposed to be, there could still be a 663 * packed ref: 664 */ 665if(resolve_packed_ref(refs, refname, sha1, type)) { 666 errno = EISDIR; 667goto out; 668} 669 ret =0; 670goto out; 671} 672 673/* 674 * Anything else, just open it and try to use it as 675 * a ref 676 */ 677 fd =open(path, O_RDONLY); 678if(fd <0) { 679if(errno == ENOENT && !S_ISLNK(st.st_mode)) 680/* inconsistent with lstat; retry */ 681goto stat_ref; 682else 683goto out; 684} 685strbuf_reset(&sb_contents); 686if(strbuf_read(&sb_contents, fd,256) <0) { 687int save_errno = errno; 688close(fd); 689 errno = save_errno; 690goto out; 691} 692close(fd); 693strbuf_rtrim(&sb_contents); 694 buf = sb_contents.buf; 695if(starts_with(buf,"ref:")) { 696 buf +=4; 697while(isspace(*buf)) 698 buf++; 699 700strbuf_reset(referent); 701strbuf_addstr(referent, buf); 702*type |= REF_ISSYMREF; 703 ret =0; 704goto out; 705} 706 707/* 708 * Please note that FETCH_HEAD has additional 709 * data after the sha. 710 */ 711if(get_sha1_hex(buf, sha1) || 712(buf[40] !='\0'&& !isspace(buf[40]))) { 713*type |= REF_ISBROKEN; 714 errno = EINVAL; 715goto out; 716} 717 718 ret =0; 719 720out: 721 save_errno = errno; 722strbuf_release(&sb_path); 723strbuf_release(&sb_contents); 724 errno = save_errno; 725return ret; 726} 727 728static voidunlock_ref(struct ref_lock *lock) 729{ 730/* Do not free lock->lk -- atexit() still looks at them */ 731if(lock->lk) 732rollback_lock_file(lock->lk); 733free(lock->ref_name); 734free(lock); 735} 736 737/* 738 * Lock refname, without following symrefs, and set *lock_p to point 739 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 740 * and type similarly to read_raw_ref(). 741 * 742 * The caller must verify that refname is a "safe" reference name (in 743 * the sense of refname_is_safe()) before calling this function. 744 * 745 * If the reference doesn't already exist, verify that refname doesn't 746 * have a D/F conflict with any existing references. extras and skip 747 * are passed to refs_verify_refname_available() for this check. 748 * 749 * If mustexist is not set and the reference is not found or is 750 * broken, lock the reference anyway but clear sha1. 751 * 752 * Return 0 on success. On failure, write an error message to err and 753 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 754 * 755 * Implementation note: This function is basically 756 * 757 * lock reference 758 * read_raw_ref() 759 * 760 * but it includes a lot more code to 761 * - Deal with possible races with other processes 762 * - Avoid calling refs_verify_refname_available() when it can be 763 * avoided, namely if we were successfully able to read the ref 764 * - Generate informative error messages in the case of failure 765 */ 766static intlock_raw_ref(struct files_ref_store *refs, 767const char*refname,int mustexist, 768const struct string_list *extras, 769const struct string_list *skip, 770struct ref_lock **lock_p, 771struct strbuf *referent, 772unsigned int*type, 773struct strbuf *err) 774{ 775struct ref_lock *lock; 776struct strbuf ref_file = STRBUF_INIT; 777int attempts_remaining =3; 778int ret = TRANSACTION_GENERIC_ERROR; 779 780assert(err); 781files_assert_main_repository(refs,"lock_raw_ref"); 782 783*type =0; 784 785/* First lock the file so it can't change out from under us. */ 786 787*lock_p = lock =xcalloc(1,sizeof(*lock)); 788 789 lock->ref_name =xstrdup(refname); 790files_ref_path(refs, &ref_file, refname); 791 792retry: 793switch(safe_create_leading_directories(ref_file.buf)) { 794case SCLD_OK: 795break;/* success */ 796case SCLD_EXISTS: 797/* 798 * Suppose refname is "refs/foo/bar". We just failed 799 * to create the containing directory, "refs/foo", 800 * because there was a non-directory in the way. This 801 * indicates a D/F conflict, probably because of 802 * another reference such as "refs/foo". There is no 803 * reason to expect this error to be transitory. 804 */ 805if(refs_verify_refname_available(&refs->base, refname, 806 extras, skip, err)) { 807if(mustexist) { 808/* 809 * To the user the relevant error is 810 * that the "mustexist" reference is 811 * missing: 812 */ 813strbuf_reset(err); 814strbuf_addf(err,"unable to resolve reference '%s'", 815 refname); 816}else{ 817/* 818 * The error message set by 819 * refs_verify_refname_available() is 820 * OK. 821 */ 822 ret = TRANSACTION_NAME_CONFLICT; 823} 824}else{ 825/* 826 * The file that is in the way isn't a loose 827 * reference. Report it as a low-level 828 * failure. 829 */ 830strbuf_addf(err,"unable to create lock file%s.lock; " 831"non-directory in the way", 832 ref_file.buf); 833} 834goto error_return; 835case SCLD_VANISHED: 836/* Maybe another process was tidying up. Try again. */ 837if(--attempts_remaining >0) 838goto retry; 839/* fall through */ 840default: 841strbuf_addf(err,"unable to create directory for%s", 842 ref_file.buf); 843goto error_return; 844} 845 846if(!lock->lk) 847 lock->lk =xcalloc(1,sizeof(struct lock_file)); 848 849if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 850if(errno == ENOENT && --attempts_remaining >0) { 851/* 852 * Maybe somebody just deleted one of the 853 * directories leading to ref_file. Try 854 * again: 855 */ 856goto retry; 857}else{ 858unable_to_lock_message(ref_file.buf, errno, err); 859goto error_return; 860} 861} 862 863/* 864 * Now we hold the lock and can read the reference without 865 * fear that its value will change. 866 */ 867 868if(files_read_raw_ref(&refs->base, refname, 869 lock->old_oid.hash, referent, type)) { 870if(errno == ENOENT) { 871if(mustexist) { 872/* Garden variety missing reference. */ 873strbuf_addf(err,"unable to resolve reference '%s'", 874 refname); 875goto error_return; 876}else{ 877/* 878 * Reference is missing, but that's OK. We 879 * know that there is not a conflict with 880 * another loose reference because 881 * (supposing that we are trying to lock 882 * reference "refs/foo/bar"): 883 * 884 * - We were successfully able to create 885 * the lockfile refs/foo/bar.lock, so we 886 * know there cannot be a loose reference 887 * named "refs/foo". 888 * 889 * - We got ENOENT and not EISDIR, so we 890 * know that there cannot be a loose 891 * reference named "refs/foo/bar/baz". 892 */ 893} 894}else if(errno == EISDIR) { 895/* 896 * There is a directory in the way. It might have 897 * contained references that have been deleted. If 898 * we don't require that the reference already 899 * exists, try to remove the directory so that it 900 * doesn't cause trouble when we want to rename the 901 * lockfile into place later. 902 */ 903if(mustexist) { 904/* Garden variety missing reference. */ 905strbuf_addf(err,"unable to resolve reference '%s'", 906 refname); 907goto error_return; 908}else if(remove_dir_recursively(&ref_file, 909 REMOVE_DIR_EMPTY_ONLY)) { 910if(refs_verify_refname_available( 911&refs->base, refname, 912 extras, skip, err)) { 913/* 914 * The error message set by 915 * verify_refname_available() is OK. 916 */ 917 ret = TRANSACTION_NAME_CONFLICT; 918goto error_return; 919}else{ 920/* 921 * We can't delete the directory, 922 * but we also don't know of any 923 * references that it should 924 * contain. 925 */ 926strbuf_addf(err,"there is a non-empty directory '%s' " 927"blocking reference '%s'", 928 ref_file.buf, refname); 929goto error_return; 930} 931} 932}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 933strbuf_addf(err,"unable to resolve reference '%s': " 934"reference broken", refname); 935goto error_return; 936}else{ 937strbuf_addf(err,"unable to resolve reference '%s':%s", 938 refname,strerror(errno)); 939goto error_return; 940} 941 942/* 943 * If the ref did not exist and we are creating it, 944 * make sure there is no existing ref that conflicts 945 * with refname: 946 */ 947if(refs_verify_refname_available( 948&refs->base, refname, 949 extras, skip, err)) 950goto error_return; 951} 952 953 ret =0; 954goto out; 955 956error_return: 957unlock_ref(lock); 958*lock_p = NULL; 959 960out: 961strbuf_release(&ref_file); 962return ret; 963} 964 965static intfiles_peel_ref(struct ref_store *ref_store, 966const char*refname,unsigned char*sha1) 967{ 968struct files_ref_store *refs = 969files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 970"peel_ref"); 971int flag; 972unsigned char base[20]; 973 974if(current_ref_iter && current_ref_iter->refname == refname) { 975struct object_id peeled; 976 977if(ref_iterator_peel(current_ref_iter, &peeled)) 978return-1; 979hashcpy(sha1, peeled.hash); 980return0; 981} 982 983if(refs_read_ref_full(ref_store, refname, 984 RESOLVE_REF_READING, base, &flag)) 985return-1; 986 987/* 988 * If the reference is packed, read its ref_entry from the 989 * cache in the hope that we already know its peeled value. 990 * We only try this optimization on packed references because 991 * (a) forcing the filling of the loose reference cache could 992 * be expensive and (b) loose references anyway usually do not 993 * have REF_KNOWS_PEELED. 994 */ 995if(flag & REF_ISPACKED) { 996struct ref_entry *r =get_packed_ref(refs, refname); 997if(r) { 998if(peel_entry(r,0)) 999return-1;1000hashcpy(sha1, r->u.value.peeled.hash);1001return0;1002}1003}10041005returnpeel_object(base, sha1);1006}10071008struct files_ref_iterator {1009struct ref_iterator base;10101011struct packed_ref_cache *packed_ref_cache;1012struct ref_iterator *iter0;1013unsigned int flags;1014};10151016static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1017{1018struct files_ref_iterator *iter =1019(struct files_ref_iterator *)ref_iterator;1020int ok;10211022while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1023if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1024ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1025continue;10261027if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1028!ref_resolves_to_object(iter->iter0->refname,1029 iter->iter0->oid,1030 iter->iter0->flags))1031continue;10321033 iter->base.refname = iter->iter0->refname;1034 iter->base.oid = iter->iter0->oid;1035 iter->base.flags = iter->iter0->flags;1036return ITER_OK;1037}10381039 iter->iter0 = NULL;1040if(ref_iterator_abort(ref_iterator) != ITER_DONE)1041 ok = ITER_ERROR;10421043return ok;1044}10451046static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1047struct object_id *peeled)1048{1049struct files_ref_iterator *iter =1050(struct files_ref_iterator *)ref_iterator;10511052returnref_iterator_peel(iter->iter0, peeled);1053}10541055static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1056{1057struct files_ref_iterator *iter =1058(struct files_ref_iterator *)ref_iterator;1059int ok = ITER_DONE;10601061if(iter->iter0)1062 ok =ref_iterator_abort(iter->iter0);10631064release_packed_ref_cache(iter->packed_ref_cache);1065base_ref_iterator_free(ref_iterator);1066return ok;1067}10681069static struct ref_iterator_vtable files_ref_iterator_vtable = {1070 files_ref_iterator_advance,1071 files_ref_iterator_peel,1072 files_ref_iterator_abort1073};10741075static struct ref_iterator *files_ref_iterator_begin(1076struct ref_store *ref_store,1077const char*prefix,unsigned int flags)1078{1079struct files_ref_store *refs;1080struct ref_dir *loose_dir, *packed_dir;1081struct ref_iterator *loose_iter, *packed_iter;1082struct files_ref_iterator *iter;1083struct ref_iterator *ref_iterator;10841085if(ref_paranoia <0)1086 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1087if(ref_paranoia)1088 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10891090 refs =files_downcast(ref_store,1091 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1092"ref_iterator_begin");10931094 iter =xcalloc(1,sizeof(*iter));1095 ref_iterator = &iter->base;1096base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10971098/*1099 * We must make sure that all loose refs are read before1100 * accessing the packed-refs file; this avoids a race1101 * condition if loose refs are migrated to the packed-refs1102 * file by a simultaneous process, but our in-memory view is1103 * from before the migration. We ensure this as follows:1104 * First, we call prime_ref_dir(), which pre-reads the loose1105 * references for the subtree into the cache. (If they've1106 * already been read, that's OK; we only need to guarantee1107 * that they're read before the packed refs, not *how much*1108 * before.) After that, we call get_packed_ref_cache(), which1109 * internally checks whether the packed-ref cache is up to1110 * date with what is on disk, and re-reads it if not.1111 */11121113 loose_dir =get_loose_refs(refs);11141115if(prefix && *prefix)1116 loose_dir =find_containing_dir(loose_dir, prefix,0);11171118if(loose_dir) {1119prime_ref_dir(loose_dir);1120 loose_iter =cache_ref_iterator_begin(loose_dir);1121}else{1122/* There's nothing to iterate over. */1123 loose_iter =empty_ref_iterator_begin();1124}11251126 iter->packed_ref_cache =get_packed_ref_cache(refs);1127acquire_packed_ref_cache(iter->packed_ref_cache);1128 packed_dir =get_packed_ref_dir(iter->packed_ref_cache);11291130if(prefix && *prefix)1131 packed_dir =find_containing_dir(packed_dir, prefix,0);11321133if(packed_dir) {1134 packed_iter =cache_ref_iterator_begin(packed_dir);1135}else{1136/* There's nothing to iterate over. */1137 packed_iter =empty_ref_iterator_begin();1138}11391140 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1141 iter->flags = flags;11421143return ref_iterator;1144}11451146/*1147 * Verify that the reference locked by lock has the value old_sha1.1148 * Fail if the reference doesn't exist and mustexist is set. Return 01149 * on success. On error, write an error message to err, set errno, and1150 * return a negative value.1151 */1152static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1153const unsigned char*old_sha1,int mustexist,1154struct strbuf *err)1155{1156assert(err);11571158if(refs_read_ref_full(ref_store, lock->ref_name,1159 mustexist ? RESOLVE_REF_READING :0,1160 lock->old_oid.hash, NULL)) {1161if(old_sha1) {1162int save_errno = errno;1163strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1164 errno = save_errno;1165return-1;1166}else{1167oidclr(&lock->old_oid);1168return0;1169}1170}1171if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1172strbuf_addf(err,"ref '%s' is at%sbut expected%s",1173 lock->ref_name,1174oid_to_hex(&lock->old_oid),1175sha1_to_hex(old_sha1));1176 errno = EBUSY;1177return-1;1178}1179return0;1180}11811182static intremove_empty_directories(struct strbuf *path)1183{1184/*1185 * we want to create a file but there is a directory there;1186 * if that is an empty directory (or a directory that contains1187 * only empty directories), remove them.1188 */1189returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1190}11911192static intcreate_reflock(const char*path,void*cb)1193{1194struct lock_file *lk = cb;11951196returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1197}11981199/*1200 * Locks a ref returning the lock on success and NULL on failure.1201 * On failure errno is set to something meaningful.1202 */1203static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1204const char*refname,1205const unsigned char*old_sha1,1206const struct string_list *extras,1207const struct string_list *skip,1208unsigned int flags,int*type,1209struct strbuf *err)1210{1211struct strbuf ref_file = STRBUF_INIT;1212struct ref_lock *lock;1213int last_errno =0;1214int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1215int resolve_flags = RESOLVE_REF_NO_RECURSE;1216int resolved;12171218files_assert_main_repository(refs,"lock_ref_sha1_basic");1219assert(err);12201221 lock =xcalloc(1,sizeof(struct ref_lock));12221223if(mustexist)1224 resolve_flags |= RESOLVE_REF_READING;1225if(flags & REF_DELETING)1226 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12271228files_ref_path(refs, &ref_file, refname);1229 resolved = !!refs_resolve_ref_unsafe(&refs->base,1230 refname, resolve_flags,1231 lock->old_oid.hash, type);1232if(!resolved && errno == EISDIR) {1233/*1234 * we are trying to lock foo but we used to1235 * have foo/bar which now does not exist;1236 * it is normal for the empty directory 'foo'1237 * to remain.1238 */1239if(remove_empty_directories(&ref_file)) {1240 last_errno = errno;1241if(!refs_verify_refname_available(1242&refs->base,1243 refname, extras, skip, err))1244strbuf_addf(err,"there are still refs under '%s'",1245 refname);1246goto error_return;1247}1248 resolved = !!refs_resolve_ref_unsafe(&refs->base,1249 refname, resolve_flags,1250 lock->old_oid.hash, type);1251}1252if(!resolved) {1253 last_errno = errno;1254if(last_errno != ENOTDIR ||1255!refs_verify_refname_available(&refs->base, refname,1256 extras, skip, err))1257strbuf_addf(err,"unable to resolve reference '%s':%s",1258 refname,strerror(last_errno));12591260goto error_return;1261}12621263/*1264 * If the ref did not exist and we are creating it, make sure1265 * there is no existing packed ref whose name begins with our1266 * refname, nor a packed ref whose name is a proper prefix of1267 * our refname.1268 */1269if(is_null_oid(&lock->old_oid) &&1270refs_verify_refname_available(&refs->base, refname,1271 extras, skip, err)) {1272 last_errno = ENOTDIR;1273goto error_return;1274}12751276 lock->lk =xcalloc(1,sizeof(struct lock_file));12771278 lock->ref_name =xstrdup(refname);12791280if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1281 last_errno = errno;1282unable_to_lock_message(ref_file.buf, errno, err);1283goto error_return;1284}12851286if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1287 last_errno = errno;1288goto error_return;1289}1290goto out;12911292 error_return:1293unlock_ref(lock);1294 lock = NULL;12951296 out:1297strbuf_release(&ref_file);1298 errno = last_errno;1299return lock;1300}13011302/*1303 * Write an entry to the packed-refs file for the specified refname.1304 * If peeled is non-NULL, write it as the entry's peeled value.1305 */1306static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1307unsigned char*peeled)1308{1309fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1310if(peeled)1311fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1312}13131314/*1315 * An each_ref_entry_fn that writes the entry to a packed-refs file.1316 */1317static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1318{1319enum peel_status peel_status =peel_entry(entry,0);13201321if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1322error("internal error:%sis not a valid packed reference!",1323 entry->name);1324write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1325 peel_status == PEEL_PEELED ?1326 entry->u.value.peeled.hash : NULL);1327return0;1328}13291330/*1331 * Lock the packed-refs file for writing. Flags is passed to1332 * hold_lock_file_for_update(). Return 0 on success. On errors, set1333 * errno appropriately and return a nonzero value.1334 */1335static intlock_packed_refs(struct files_ref_store *refs,int flags)1336{1337static int timeout_configured =0;1338static int timeout_value =1000;1339struct packed_ref_cache *packed_ref_cache;13401341files_assert_main_repository(refs,"lock_packed_refs");13421343if(!timeout_configured) {1344git_config_get_int("core.packedrefstimeout", &timeout_value);1345 timeout_configured =1;1346}13471348if(hold_lock_file_for_update_timeout(1349&packlock,files_packed_refs_path(refs),1350 flags, timeout_value) <0)1351return-1;1352/*1353 * Get the current packed-refs while holding the lock. If the1354 * packed-refs file has been modified since we last read it,1355 * this will automatically invalidate the cache and re-read1356 * the packed-refs file.1357 */1358 packed_ref_cache =get_packed_ref_cache(refs);1359 packed_ref_cache->lock = &packlock;1360/* Increment the reference count to prevent it from being freed: */1361acquire_packed_ref_cache(packed_ref_cache);1362return0;1363}13641365/*1366 * Write the current version of the packed refs cache from memory to1367 * disk. The packed-refs file must already be locked for writing (see1368 * lock_packed_refs()). Return zero on success. On errors, set errno1369 * and return a nonzero value1370 */1371static intcommit_packed_refs(struct files_ref_store *refs)1372{1373struct packed_ref_cache *packed_ref_cache =1374get_packed_ref_cache(refs);1375int error =0;1376int save_errno =0;1377FILE*out;13781379files_assert_main_repository(refs,"commit_packed_refs");13801381if(!packed_ref_cache->lock)1382die("internal error: packed-refs not locked");13831384 out =fdopen_lock_file(packed_ref_cache->lock,"w");1385if(!out)1386die_errno("unable to fdopen packed-refs descriptor");13871388fprintf_or_die(out,"%s", PACKED_REFS_HEADER);1389do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),1390 write_packed_entry_fn, out);13911392if(commit_lock_file(packed_ref_cache->lock)) {1393 save_errno = errno;1394 error = -1;1395}1396 packed_ref_cache->lock = NULL;1397release_packed_ref_cache(packed_ref_cache);1398 errno = save_errno;1399return error;1400}14011402/*1403 * Rollback the lockfile for the packed-refs file, and discard the1404 * in-memory packed reference cache. (The packed-refs file will be1405 * read anew if it is needed again after this function is called.)1406 */1407static voidrollback_packed_refs(struct files_ref_store *refs)1408{1409struct packed_ref_cache *packed_ref_cache =1410get_packed_ref_cache(refs);14111412files_assert_main_repository(refs,"rollback_packed_refs");14131414if(!packed_ref_cache->lock)1415die("internal error: packed-refs not locked");1416rollback_lock_file(packed_ref_cache->lock);1417 packed_ref_cache->lock = NULL;1418release_packed_ref_cache(packed_ref_cache);1419clear_packed_ref_cache(refs);1420}14211422struct ref_to_prune {1423struct ref_to_prune *next;1424unsigned char sha1[20];1425char name[FLEX_ARRAY];1426};14271428struct pack_refs_cb_data {1429unsigned int flags;1430struct ref_dir *packed_refs;1431struct ref_to_prune *ref_to_prune;1432};14331434/*1435 * An each_ref_entry_fn that is run over loose references only. If1436 * the loose reference can be packed, add an entry in the packed ref1437 * cache. If the reference should be pruned, also add it to1438 * ref_to_prune in the pack_refs_cb_data.1439 */1440static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)1441{1442struct pack_refs_cb_data *cb = cb_data;1443enum peel_status peel_status;1444struct ref_entry *packed_entry;1445int is_tag_ref =starts_with(entry->name,"refs/tags/");14461447/* Do not pack per-worktree refs: */1448if(ref_type(entry->name) != REF_TYPE_NORMAL)1449return0;14501451/* ALWAYS pack tags */1452if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)1453return0;14541455/* Do not pack symbolic or broken refs: */1456if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))1457return0;14581459/* Add a packed ref cache entry equivalent to the loose entry. */1460 peel_status =peel_entry(entry,1);1461if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1462die("internal error peeling reference%s(%s)",1463 entry->name,oid_to_hex(&entry->u.value.oid));1464 packed_entry =find_ref_entry(cb->packed_refs, entry->name);1465if(packed_entry) {1466/* Overwrite existing packed entry with info from loose entry */1467 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;1468oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);1469}else{1470 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,1471 REF_ISPACKED | REF_KNOWS_PEELED,0);1472add_ref_entry(cb->packed_refs, packed_entry);1473}1474oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);14751476/* Schedule the loose reference for pruning if requested. */1477if((cb->flags & PACK_REFS_PRUNE)) {1478struct ref_to_prune *n;1479FLEX_ALLOC_STR(n, name, entry->name);1480hashcpy(n->sha1, entry->u.value.oid.hash);1481 n->next = cb->ref_to_prune;1482 cb->ref_to_prune = n;1483}1484return0;1485}14861487enum{1488 REMOVE_EMPTY_PARENTS_REF =0x01,1489 REMOVE_EMPTY_PARENTS_REFLOG =0x021490};14911492/*1493 * Remove empty parent directories associated with the specified1494 * reference and/or its reflog, but spare [logs/]refs/ and immediate1495 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1496 * REMOVE_EMPTY_PARENTS_REFLOG.1497 */1498static voidtry_remove_empty_parents(struct files_ref_store *refs,1499const char*refname,1500unsigned int flags)1501{1502struct strbuf buf = STRBUF_INIT;1503struct strbuf sb = STRBUF_INIT;1504char*p, *q;1505int i;15061507strbuf_addstr(&buf, refname);1508 p = buf.buf;1509for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1510while(*p && *p !='/')1511 p++;1512/* tolerate duplicate slashes; see check_refname_format() */1513while(*p =='/')1514 p++;1515}1516 q = buf.buf + buf.len;1517while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1518while(q > p && *q !='/')1519 q--;1520while(q > p && *(q-1) =='/')1521 q--;1522if(q == p)1523break;1524strbuf_setlen(&buf, q - buf.buf);15251526strbuf_reset(&sb);1527files_ref_path(refs, &sb, buf.buf);1528if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1529 flags &= ~REMOVE_EMPTY_PARENTS_REF;15301531strbuf_reset(&sb);1532files_reflog_path(refs, &sb, buf.buf);1533if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1534 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1535}1536strbuf_release(&buf);1537strbuf_release(&sb);1538}15391540/* make sure nobody touched the ref, and unlink */1541static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1542{1543struct ref_transaction *transaction;1544struct strbuf err = STRBUF_INIT;15451546if(check_refname_format(r->name,0))1547return;15481549 transaction =ref_store_transaction_begin(&refs->base, &err);1550if(!transaction ||1551ref_transaction_delete(transaction, r->name, r->sha1,1552 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1553ref_transaction_commit(transaction, &err)) {1554ref_transaction_free(transaction);1555error("%s", err.buf);1556strbuf_release(&err);1557return;1558}1559ref_transaction_free(transaction);1560strbuf_release(&err);1561}15621563static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1564{1565while(r) {1566prune_ref(refs, r);1567 r = r->next;1568}1569}15701571static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1572{1573struct files_ref_store *refs =1574files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1575"pack_refs");1576struct pack_refs_cb_data cbdata;15771578memset(&cbdata,0,sizeof(cbdata));1579 cbdata.flags = flags;15801581lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1582 cbdata.packed_refs =get_packed_refs(refs);15831584do_for_each_entry_in_dir(get_loose_refs(refs),1585 pack_if_possible_fn, &cbdata);15861587if(commit_packed_refs(refs))1588die_errno("unable to overwrite old ref-pack file");15891590prune_refs(refs, cbdata.ref_to_prune);1591return0;1592}15931594/*1595 * Rewrite the packed-refs file, omitting any refs listed in1596 * 'refnames'. On error, leave packed-refs unchanged, write an error1597 * message to 'err', and return a nonzero value.1598 *1599 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1600 */1601static intrepack_without_refs(struct files_ref_store *refs,1602struct string_list *refnames,struct strbuf *err)1603{1604struct ref_dir *packed;1605struct string_list_item *refname;1606int ret, needs_repacking =0, removed =0;16071608files_assert_main_repository(refs,"repack_without_refs");1609assert(err);16101611/* Look for a packed ref */1612for_each_string_list_item(refname, refnames) {1613if(get_packed_ref(refs, refname->string)) {1614 needs_repacking =1;1615break;1616}1617}16181619/* Avoid locking if we have nothing to do */1620if(!needs_repacking)1621return0;/* no refname exists in packed refs */16221623if(lock_packed_refs(refs,0)) {1624unable_to_lock_message(files_packed_refs_path(refs), errno, err);1625return-1;1626}1627 packed =get_packed_refs(refs);16281629/* Remove refnames from the cache */1630for_each_string_list_item(refname, refnames)1631if(remove_entry_from_dir(packed, refname->string) != -1)1632 removed =1;1633if(!removed) {1634/*1635 * All packed entries disappeared while we were1636 * acquiring the lock.1637 */1638rollback_packed_refs(refs);1639return0;1640}16411642/* Write what remains */1643 ret =commit_packed_refs(refs);1644if(ret)1645strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1646strerror(errno));1647return ret;1648}16491650static intfiles_delete_refs(struct ref_store *ref_store,1651struct string_list *refnames,unsigned int flags)1652{1653struct files_ref_store *refs =1654files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1655struct strbuf err = STRBUF_INIT;1656int i, result =0;16571658if(!refnames->nr)1659return0;16601661 result =repack_without_refs(refs, refnames, &err);1662if(result) {1663/*1664 * If we failed to rewrite the packed-refs file, then1665 * it is unsafe to try to remove loose refs, because1666 * doing so might expose an obsolete packed value for1667 * a reference that might even point at an object that1668 * has been garbage collected.1669 */1670if(refnames->nr ==1)1671error(_("could not delete reference%s:%s"),1672 refnames->items[0].string, err.buf);1673else1674error(_("could not delete references:%s"), err.buf);16751676goto out;1677}16781679for(i =0; i < refnames->nr; i++) {1680const char*refname = refnames->items[i].string;16811682if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))1683 result |=error(_("could not remove reference%s"), refname);1684}16851686out:1687strbuf_release(&err);1688return result;1689}16901691/*1692 * People using contrib's git-new-workdir have .git/logs/refs ->1693 * /some/other/path/.git/logs/refs, and that may live on another device.1694 *1695 * IOW, to avoid cross device rename errors, the temporary renamed log must1696 * live into logs/refs.1697 */1698#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16991700struct rename_cb {1701const char*tmp_renamed_log;1702int true_errno;1703};17041705static intrename_tmp_log_callback(const char*path,void*cb_data)1706{1707struct rename_cb *cb = cb_data;17081709if(rename(cb->tmp_renamed_log, path)) {1710/*1711 * rename(a, b) when b is an existing directory ought1712 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1713 * Sheesh. Record the true errno for error reporting,1714 * but report EISDIR to raceproof_create_file() so1715 * that it knows to retry.1716 */1717 cb->true_errno = errno;1718if(errno == ENOTDIR)1719 errno = EISDIR;1720return-1;1721}else{1722return0;1723}1724}17251726static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1727{1728struct strbuf path = STRBUF_INIT;1729struct strbuf tmp = STRBUF_INIT;1730struct rename_cb cb;1731int ret;17321733files_reflog_path(refs, &path, newrefname);1734files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1735 cb.tmp_renamed_log = tmp.buf;1736 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1737if(ret) {1738if(errno == EISDIR)1739error("directory not empty:%s", path.buf);1740else1741error("unable to move logfile%sto%s:%s",1742 tmp.buf, path.buf,1743strerror(cb.true_errno));1744}17451746strbuf_release(&path);1747strbuf_release(&tmp);1748return ret;1749}17501751static intwrite_ref_to_lockfile(struct ref_lock *lock,1752const unsigned char*sha1,struct strbuf *err);1753static intcommit_ref_update(struct files_ref_store *refs,1754struct ref_lock *lock,1755const unsigned char*sha1,const char*logmsg,1756struct strbuf *err);17571758static intfiles_rename_ref(struct ref_store *ref_store,1759const char*oldrefname,const char*newrefname,1760const char*logmsg)1761{1762struct files_ref_store *refs =1763files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1764unsigned char sha1[20], orig_sha1[20];1765int flag =0, logmoved =0;1766struct ref_lock *lock;1767struct stat loginfo;1768struct strbuf sb_oldref = STRBUF_INIT;1769struct strbuf sb_newref = STRBUF_INIT;1770struct strbuf tmp_renamed_log = STRBUF_INIT;1771int log, ret;1772struct strbuf err = STRBUF_INIT;17731774files_reflog_path(refs, &sb_oldref, oldrefname);1775files_reflog_path(refs, &sb_newref, newrefname);1776files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17771778 log = !lstat(sb_oldref.buf, &loginfo);1779if(log &&S_ISLNK(loginfo.st_mode)) {1780 ret =error("reflog for%sis a symlink", oldrefname);1781goto out;1782}17831784if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1785 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1786 orig_sha1, &flag)) {1787 ret =error("refname%snot found", oldrefname);1788goto out;1789}17901791if(flag & REF_ISSYMREF) {1792 ret =error("refname%sis a symbolic ref, renaming it is not supported",1793 oldrefname);1794goto out;1795}1796if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1797 ret =1;1798goto out;1799}18001801if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1802 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1803 oldrefname,strerror(errno));1804goto out;1805}18061807if(refs_delete_ref(&refs->base, logmsg, oldrefname,1808 orig_sha1, REF_NODEREF)) {1809error("unable to delete old%s", oldrefname);1810goto rollback;1811}18121813/*1814 * Since we are doing a shallow lookup, sha1 is not the1815 * correct value to pass to delete_ref as old_sha1. But that1816 * doesn't matter, because an old_sha1 check wouldn't add to1817 * the safety anyway; we want to delete the reference whatever1818 * its current value.1819 */1820if(!refs_read_ref_full(&refs->base, newrefname,1821 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1822 sha1, NULL) &&1823refs_delete_ref(&refs->base, NULL, newrefname,1824 NULL, REF_NODEREF)) {1825if(errno == EISDIR) {1826struct strbuf path = STRBUF_INIT;1827int result;18281829files_ref_path(refs, &path, newrefname);1830 result =remove_empty_directories(&path);1831strbuf_release(&path);18321833if(result) {1834error("Directory not empty:%s", newrefname);1835goto rollback;1836}1837}else{1838error("unable to delete existing%s", newrefname);1839goto rollback;1840}1841}18421843if(log &&rename_tmp_log(refs, newrefname))1844goto rollback;18451846 logmoved = log;18471848 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1849 REF_NODEREF, NULL, &err);1850if(!lock) {1851error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1852strbuf_release(&err);1853goto rollback;1854}1855hashcpy(lock->old_oid.hash, orig_sha1);18561857if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1858commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {1859error("unable to write current sha1 into%s:%s", newrefname, err.buf);1860strbuf_release(&err);1861goto rollback;1862}18631864 ret =0;1865goto out;18661867 rollback:1868 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1869 REF_NODEREF, NULL, &err);1870if(!lock) {1871error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1872strbuf_release(&err);1873goto rollbacklog;1874}18751876 flag = log_all_ref_updates;1877 log_all_ref_updates = LOG_REFS_NONE;1878if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1879commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {1880error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1881strbuf_release(&err);1882}1883 log_all_ref_updates = flag;18841885 rollbacklog:1886if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1887error("unable to restore logfile%sfrom%s:%s",1888 oldrefname, newrefname,strerror(errno));1889if(!logmoved && log &&1890rename(tmp_renamed_log.buf, sb_oldref.buf))1891error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1892 oldrefname,strerror(errno));1893 ret =1;1894 out:1895strbuf_release(&sb_newref);1896strbuf_release(&sb_oldref);1897strbuf_release(&tmp_renamed_log);18981899return ret;1900}19011902static intclose_ref(struct ref_lock *lock)1903{1904if(close_lock_file(lock->lk))1905return-1;1906return0;1907}19081909static intcommit_ref(struct ref_lock *lock)1910{1911char*path =get_locked_file_path(lock->lk);1912struct stat st;19131914if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1915/*1916 * There is a directory at the path we want to rename1917 * the lockfile to. Hopefully it is empty; try to1918 * delete it.1919 */1920size_t len =strlen(path);1921struct strbuf sb_path = STRBUF_INIT;19221923strbuf_attach(&sb_path, path, len, len);19241925/*1926 * If this fails, commit_lock_file() will also fail1927 * and will report the problem.1928 */1929remove_empty_directories(&sb_path);1930strbuf_release(&sb_path);1931}else{1932free(path);1933}19341935if(commit_lock_file(lock->lk))1936return-1;1937return0;1938}19391940static intopen_or_create_logfile(const char*path,void*cb)1941{1942int*fd = cb;19431944*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1945return(*fd <0) ? -1:0;1946}19471948/*1949 * Create a reflog for a ref. If force_create = 0, only create the1950 * reflog for certain refs (those for which should_autocreate_reflog1951 * returns non-zero). Otherwise, create it regardless of the reference1952 * name. If the logfile already existed or was created, return 0 and1953 * set *logfd to the file descriptor opened for appending to the file.1954 * If no logfile exists and we decided not to create one, return 0 and1955 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1956 * return -1.1957 */1958static intlog_ref_setup(struct files_ref_store *refs,1959const char*refname,int force_create,1960int*logfd,struct strbuf *err)1961{1962struct strbuf logfile_sb = STRBUF_INIT;1963char*logfile;19641965files_reflog_path(refs, &logfile_sb, refname);1966 logfile =strbuf_detach(&logfile_sb, NULL);19671968if(force_create ||should_autocreate_reflog(refname)) {1969if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1970if(errno == ENOENT)1971strbuf_addf(err,"unable to create directory for '%s': "1972"%s", logfile,strerror(errno));1973else if(errno == EISDIR)1974strbuf_addf(err,"there are still logs under '%s'",1975 logfile);1976else1977strbuf_addf(err,"unable to append to '%s':%s",1978 logfile,strerror(errno));19791980goto error;1981}1982}else{1983*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1984if(*logfd <0) {1985if(errno == ENOENT || errno == EISDIR) {1986/*1987 * The logfile doesn't already exist,1988 * but that is not an error; it only1989 * means that we won't write log1990 * entries to it.1991 */1992;1993}else{1994strbuf_addf(err,"unable to append to '%s':%s",1995 logfile,strerror(errno));1996goto error;1997}1998}1999}20002001if(*logfd >=0)2002adjust_shared_perm(logfile);20032004free(logfile);2005return0;20062007error:2008free(logfile);2009return-1;2010}20112012static intfiles_create_reflog(struct ref_store *ref_store,2013const char*refname,int force_create,2014struct strbuf *err)2015{2016struct files_ref_store *refs =2017files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2018int fd;20192020if(log_ref_setup(refs, refname, force_create, &fd, err))2021return-1;20222023if(fd >=0)2024close(fd);20252026return0;2027}20282029static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2030const unsigned char*new_sha1,2031const char*committer,const char*msg)2032{2033int msglen, written;2034unsigned maxlen, len;2035char*logrec;20362037 msglen = msg ?strlen(msg) :0;2038 maxlen =strlen(committer) + msglen +100;2039 logrec =xmalloc(maxlen);2040 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2041sha1_to_hex(old_sha1),2042sha1_to_hex(new_sha1),2043 committer);2044if(msglen)2045 len +=copy_reflog_msg(logrec + len -1, msg) -1;20462047 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2048free(logrec);2049if(written != len)2050return-1;20512052return0;2053}20542055static intfiles_log_ref_write(struct files_ref_store *refs,2056const char*refname,const unsigned char*old_sha1,2057const unsigned char*new_sha1,const char*msg,2058int flags,struct strbuf *err)2059{2060int logfd, result;20612062if(log_all_ref_updates == LOG_REFS_UNSET)2063 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20642065 result =log_ref_setup(refs, refname,2066 flags & REF_FORCE_CREATE_REFLOG,2067&logfd, err);20682069if(result)2070return result;20712072if(logfd <0)2073return0;2074 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2075git_committer_info(0), msg);2076if(result) {2077struct strbuf sb = STRBUF_INIT;2078int save_errno = errno;20792080files_reflog_path(refs, &sb, refname);2081strbuf_addf(err,"unable to append to '%s':%s",2082 sb.buf,strerror(save_errno));2083strbuf_release(&sb);2084close(logfd);2085return-1;2086}2087if(close(logfd)) {2088struct strbuf sb = STRBUF_INIT;2089int save_errno = errno;20902091files_reflog_path(refs, &sb, refname);2092strbuf_addf(err,"unable to append to '%s':%s",2093 sb.buf,strerror(save_errno));2094strbuf_release(&sb);2095return-1;2096}2097return0;2098}20992100/*2101 * Write sha1 into the open lockfile, then close the lockfile. On2102 * errors, rollback the lockfile, fill in *err and2103 * return -1.2104 */2105static intwrite_ref_to_lockfile(struct ref_lock *lock,2106const unsigned char*sha1,struct strbuf *err)2107{2108static char term ='\n';2109struct object *o;2110int fd;21112112 o =parse_object(sha1);2113if(!o) {2114strbuf_addf(err,2115"trying to write ref '%s' with nonexistent object%s",2116 lock->ref_name,sha1_to_hex(sha1));2117unlock_ref(lock);2118return-1;2119}2120if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2121strbuf_addf(err,2122"trying to write non-commit object%sto branch '%s'",2123sha1_to_hex(sha1), lock->ref_name);2124unlock_ref(lock);2125return-1;2126}2127 fd =get_lock_file_fd(lock->lk);2128if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2129write_in_full(fd, &term,1) !=1||2130close_ref(lock) <0) {2131strbuf_addf(err,2132"couldn't write '%s'",get_lock_file_path(lock->lk));2133unlock_ref(lock);2134return-1;2135}2136return0;2137}21382139/*2140 * Commit a change to a loose reference that has already been written2141 * to the loose reference lockfile. Also update the reflogs if2142 * necessary, using the specified lockmsg (which can be NULL).2143 */2144static intcommit_ref_update(struct files_ref_store *refs,2145struct ref_lock *lock,2146const unsigned char*sha1,const char*logmsg,2147struct strbuf *err)2148{2149files_assert_main_repository(refs,"commit_ref_update");21502151clear_loose_ref_cache(refs);2152if(files_log_ref_write(refs, lock->ref_name,2153 lock->old_oid.hash, sha1,2154 logmsg,0, err)) {2155char*old_msg =strbuf_detach(err, NULL);2156strbuf_addf(err,"cannot update the ref '%s':%s",2157 lock->ref_name, old_msg);2158free(old_msg);2159unlock_ref(lock);2160return-1;2161}21622163if(strcmp(lock->ref_name,"HEAD") !=0) {2164/*2165 * Special hack: If a branch is updated directly and HEAD2166 * points to it (may happen on the remote side of a push2167 * for example) then logically the HEAD reflog should be2168 * updated too.2169 * A generic solution implies reverse symref information,2170 * but finding all symrefs pointing to the given branch2171 * would be rather costly for this rare event (the direct2172 * update of a branch) to be worth it. So let's cheat and2173 * check with HEAD only which should cover 99% of all usage2174 * scenarios (even 100% of the default ones).2175 */2176unsigned char head_sha1[20];2177int head_flag;2178const char*head_ref;21792180 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2181 RESOLVE_REF_READING,2182 head_sha1, &head_flag);2183if(head_ref && (head_flag & REF_ISSYMREF) &&2184!strcmp(head_ref, lock->ref_name)) {2185struct strbuf log_err = STRBUF_INIT;2186if(files_log_ref_write(refs,"HEAD",2187 lock->old_oid.hash, sha1,2188 logmsg,0, &log_err)) {2189error("%s", log_err.buf);2190strbuf_release(&log_err);2191}2192}2193}21942195if(commit_ref(lock)) {2196strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2197unlock_ref(lock);2198return-1;2199}22002201unlock_ref(lock);2202return0;2203}22042205static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2206{2207int ret = -1;2208#ifndef NO_SYMLINK_HEAD2209char*ref_path =get_locked_file_path(lock->lk);2210unlink(ref_path);2211 ret =symlink(target, ref_path);2212free(ref_path);22132214if(ret)2215fprintf(stderr,"no symlink - falling back to symbolic ref\n");2216#endif2217return ret;2218}22192220static voidupdate_symref_reflog(struct files_ref_store *refs,2221struct ref_lock *lock,const char*refname,2222const char*target,const char*logmsg)2223{2224struct strbuf err = STRBUF_INIT;2225unsigned char new_sha1[20];2226if(logmsg &&2227!refs_read_ref_full(&refs->base, target,2228 RESOLVE_REF_READING, new_sha1, NULL) &&2229files_log_ref_write(refs, refname, lock->old_oid.hash,2230 new_sha1, logmsg,0, &err)) {2231error("%s", err.buf);2232strbuf_release(&err);2233}2234}22352236static intcreate_symref_locked(struct files_ref_store *refs,2237struct ref_lock *lock,const char*refname,2238const char*target,const char*logmsg)2239{2240if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2241update_symref_reflog(refs, lock, refname, target, logmsg);2242return0;2243}22442245if(!fdopen_lock_file(lock->lk,"w"))2246returnerror("unable to fdopen%s:%s",2247 lock->lk->tempfile.filename.buf,strerror(errno));22482249update_symref_reflog(refs, lock, refname, target, logmsg);22502251/* no error check; commit_ref will check ferror */2252fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2253if(commit_ref(lock) <0)2254returnerror("unable to write symref for%s:%s", refname,2255strerror(errno));2256return0;2257}22582259static intfiles_create_symref(struct ref_store *ref_store,2260const char*refname,const char*target,2261const char*logmsg)2262{2263struct files_ref_store *refs =2264files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2265struct strbuf err = STRBUF_INIT;2266struct ref_lock *lock;2267int ret;22682269 lock =lock_ref_sha1_basic(refs, refname, NULL,2270 NULL, NULL, REF_NODEREF, NULL,2271&err);2272if(!lock) {2273error("%s", err.buf);2274strbuf_release(&err);2275return-1;2276}22772278 ret =create_symref_locked(refs, lock, refname, target, logmsg);2279unlock_ref(lock);2280return ret;2281}22822283intset_worktree_head_symref(const char*gitdir,const char*target,const char*logmsg)2284{2285/*2286 * FIXME: this obviously will not work well for future refs2287 * backends. This function needs to die.2288 */2289struct files_ref_store *refs =2290files_downcast(get_main_ref_store(),2291 REF_STORE_WRITE,2292"set_head_symref");22932294static struct lock_file head_lock;2295struct ref_lock *lock;2296struct strbuf head_path = STRBUF_INIT;2297const char*head_rel;2298int ret;22992300strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2301if(hold_lock_file_for_update(&head_lock, head_path.buf,2302 LOCK_NO_DEREF) <0) {2303struct strbuf err = STRBUF_INIT;2304unable_to_lock_message(head_path.buf, errno, &err);2305error("%s", err.buf);2306strbuf_release(&err);2307strbuf_release(&head_path);2308return-1;2309}23102311/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2312 linked trees */2313 head_rel =remove_leading_path(head_path.buf,2314absolute_path(get_git_common_dir()));2315/* to make use of create_symref_locked(), initialize ref_lock */2316 lock =xcalloc(1,sizeof(struct ref_lock));2317 lock->lk = &head_lock;2318 lock->ref_name =xstrdup(head_rel);23192320 ret =create_symref_locked(refs, lock, head_rel, target, logmsg);23212322unlock_ref(lock);/* will free lock */2323strbuf_release(&head_path);2324return ret;2325}23262327static intfiles_reflog_exists(struct ref_store *ref_store,2328const char*refname)2329{2330struct files_ref_store *refs =2331files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2332struct strbuf sb = STRBUF_INIT;2333struct stat st;2334int ret;23352336files_reflog_path(refs, &sb, refname);2337 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2338strbuf_release(&sb);2339return ret;2340}23412342static intfiles_delete_reflog(struct ref_store *ref_store,2343const char*refname)2344{2345struct files_ref_store *refs =2346files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2347struct strbuf sb = STRBUF_INIT;2348int ret;23492350files_reflog_path(refs, &sb, refname);2351 ret =remove_path(sb.buf);2352strbuf_release(&sb);2353return ret;2354}23552356static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2357{2358struct object_id ooid, noid;2359char*email_end, *message;2360unsigned long timestamp;2361int tz;2362const char*p = sb->buf;23632364/* old SP new SP name <email> SP time TAB msg LF */2365if(!sb->len || sb->buf[sb->len -1] !='\n'||2366parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2367parse_oid_hex(p, &noid, &p) || *p++ !=' '||2368!(email_end =strchr(p,'>')) ||2369 email_end[1] !=' '||2370!(timestamp =strtoul(email_end +2, &message,10)) ||2371!message || message[0] !=' '||2372(message[1] !='+'&& message[1] !='-') ||2373!isdigit(message[2]) || !isdigit(message[3]) ||2374!isdigit(message[4]) || !isdigit(message[5]))2375return0;/* corrupt? */2376 email_end[1] ='\0';2377 tz =strtol(message +1, NULL,10);2378if(message[6] !='\t')2379 message +=6;2380else2381 message +=7;2382returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2383}23842385static char*find_beginning_of_line(char*bob,char*scan)2386{2387while(bob < scan && *(--scan) !='\n')2388;/* keep scanning backwards */2389/*2390 * Return either beginning of the buffer, or LF at the end of2391 * the previous line.2392 */2393return scan;2394}23952396static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2397const char*refname,2398 each_reflog_ent_fn fn,2399void*cb_data)2400{2401struct files_ref_store *refs =2402files_downcast(ref_store, REF_STORE_READ,2403"for_each_reflog_ent_reverse");2404struct strbuf sb = STRBUF_INIT;2405FILE*logfp;2406long pos;2407int ret =0, at_tail =1;24082409files_reflog_path(refs, &sb, refname);2410 logfp =fopen(sb.buf,"r");2411strbuf_release(&sb);2412if(!logfp)2413return-1;24142415/* Jump to the end */2416if(fseek(logfp,0, SEEK_END) <0)2417returnerror("cannot seek back reflog for%s:%s",2418 refname,strerror(errno));2419 pos =ftell(logfp);2420while(!ret &&0< pos) {2421int cnt;2422size_t nread;2423char buf[BUFSIZ];2424char*endp, *scanp;24252426/* Fill next block from the end */2427 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2428if(fseek(logfp, pos - cnt, SEEK_SET))2429returnerror("cannot seek back reflog for%s:%s",2430 refname,strerror(errno));2431 nread =fread(buf, cnt,1, logfp);2432if(nread !=1)2433returnerror("cannot read%dbytes from reflog for%s:%s",2434 cnt, refname,strerror(errno));2435 pos -= cnt;24362437 scanp = endp = buf + cnt;2438if(at_tail && scanp[-1] =='\n')2439/* Looking at the final LF at the end of the file */2440 scanp--;2441 at_tail =0;24422443while(buf < scanp) {2444/*2445 * terminating LF of the previous line, or the beginning2446 * of the buffer.2447 */2448char*bp;24492450 bp =find_beginning_of_line(buf, scanp);24512452if(*bp =='\n') {2453/*2454 * The newline is the end of the previous line,2455 * so we know we have complete line starting2456 * at (bp + 1). Prefix it onto any prior data2457 * we collected for the line and process it.2458 */2459strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2460 scanp = bp;2461 endp = bp +1;2462 ret =show_one_reflog_ent(&sb, fn, cb_data);2463strbuf_reset(&sb);2464if(ret)2465break;2466}else if(!pos) {2467/*2468 * We are at the start of the buffer, and the2469 * start of the file; there is no previous2470 * line, and we have everything for this one.2471 * Process it, and we can end the loop.2472 */2473strbuf_splice(&sb,0,0, buf, endp - buf);2474 ret =show_one_reflog_ent(&sb, fn, cb_data);2475strbuf_reset(&sb);2476break;2477}24782479if(bp == buf) {2480/*2481 * We are at the start of the buffer, and there2482 * is more file to read backwards. Which means2483 * we are in the middle of a line. Note that we2484 * may get here even if *bp was a newline; that2485 * just means we are at the exact end of the2486 * previous line, rather than some spot in the2487 * middle.2488 *2489 * Save away what we have to be combined with2490 * the data from the next read.2491 */2492strbuf_splice(&sb,0,0, buf, endp - buf);2493break;2494}2495}24962497}2498if(!ret && sb.len)2499die("BUG: reverse reflog parser had leftover data");25002501fclose(logfp);2502strbuf_release(&sb);2503return ret;2504}25052506static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2507const char*refname,2508 each_reflog_ent_fn fn,void*cb_data)2509{2510struct files_ref_store *refs =2511files_downcast(ref_store, REF_STORE_READ,2512"for_each_reflog_ent");2513FILE*logfp;2514struct strbuf sb = STRBUF_INIT;2515int ret =0;25162517files_reflog_path(refs, &sb, refname);2518 logfp =fopen(sb.buf,"r");2519strbuf_release(&sb);2520if(!logfp)2521return-1;25222523while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2524 ret =show_one_reflog_ent(&sb, fn, cb_data);2525fclose(logfp);2526strbuf_release(&sb);2527return ret;2528}25292530struct files_reflog_iterator {2531struct ref_iterator base;25322533struct ref_store *ref_store;2534struct dir_iterator *dir_iterator;2535struct object_id oid;2536};25372538static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2539{2540struct files_reflog_iterator *iter =2541(struct files_reflog_iterator *)ref_iterator;2542struct dir_iterator *diter = iter->dir_iterator;2543int ok;25442545while((ok =dir_iterator_advance(diter)) == ITER_OK) {2546int flags;25472548if(!S_ISREG(diter->st.st_mode))2549continue;2550if(diter->basename[0] =='.')2551continue;2552if(ends_with(diter->basename,".lock"))2553continue;25542555if(refs_read_ref_full(iter->ref_store,2556 diter->relative_path,0,2557 iter->oid.hash, &flags)) {2558error("bad ref for%s", diter->path.buf);2559continue;2560}25612562 iter->base.refname = diter->relative_path;2563 iter->base.oid = &iter->oid;2564 iter->base.flags = flags;2565return ITER_OK;2566}25672568 iter->dir_iterator = NULL;2569if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2570 ok = ITER_ERROR;2571return ok;2572}25732574static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2575struct object_id *peeled)2576{2577die("BUG: ref_iterator_peel() called for reflog_iterator");2578}25792580static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2581{2582struct files_reflog_iterator *iter =2583(struct files_reflog_iterator *)ref_iterator;2584int ok = ITER_DONE;25852586if(iter->dir_iterator)2587 ok =dir_iterator_abort(iter->dir_iterator);25882589base_ref_iterator_free(ref_iterator);2590return ok;2591}25922593static struct ref_iterator_vtable files_reflog_iterator_vtable = {2594 files_reflog_iterator_advance,2595 files_reflog_iterator_peel,2596 files_reflog_iterator_abort2597};25982599static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2600{2601struct files_ref_store *refs =2602files_downcast(ref_store, REF_STORE_READ,2603"reflog_iterator_begin");2604struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2605struct ref_iterator *ref_iterator = &iter->base;2606struct strbuf sb = STRBUF_INIT;26072608base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2609files_reflog_path(refs, &sb, NULL);2610 iter->dir_iterator =dir_iterator_begin(sb.buf);2611 iter->ref_store = ref_store;2612strbuf_release(&sb);2613return ref_iterator;2614}26152616static intref_update_reject_duplicates(struct string_list *refnames,2617struct strbuf *err)2618{2619int i, n = refnames->nr;26202621assert(err);26222623for(i =1; i < n; i++)2624if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2625strbuf_addf(err,2626"multiple updates for ref '%s' not allowed.",2627 refnames->items[i].string);2628return1;2629}2630return0;2631}26322633/*2634 * If update is a direct update of head_ref (the reference pointed to2635 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2636 */2637static intsplit_head_update(struct ref_update *update,2638struct ref_transaction *transaction,2639const char*head_ref,2640struct string_list *affected_refnames,2641struct strbuf *err)2642{2643struct string_list_item *item;2644struct ref_update *new_update;26452646if((update->flags & REF_LOG_ONLY) ||2647(update->flags & REF_ISPRUNING) ||2648(update->flags & REF_UPDATE_VIA_HEAD))2649return0;26502651if(strcmp(update->refname, head_ref))2652return0;26532654/*2655 * First make sure that HEAD is not already in the2656 * transaction. This insertion is O(N) in the transaction2657 * size, but it happens at most once per transaction.2658 */2659 item =string_list_insert(affected_refnames,"HEAD");2660if(item->util) {2661/* An entry already existed */2662strbuf_addf(err,2663"multiple updates for 'HEAD' (including one "2664"via its referent '%s') are not allowed",2665 update->refname);2666return TRANSACTION_NAME_CONFLICT;2667}26682669 new_update =ref_transaction_add_update(2670 transaction,"HEAD",2671 update->flags | REF_LOG_ONLY | REF_NODEREF,2672 update->new_sha1, update->old_sha1,2673 update->msg);26742675 item->util = new_update;26762677return0;2678}26792680/*2681 * update is for a symref that points at referent and doesn't have2682 * REF_NODEREF set. Split it into two updates:2683 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2684 * - A new, separate update for the referent reference2685 * Note that the new update will itself be subject to splitting when2686 * the iteration gets to it.2687 */2688static intsplit_symref_update(struct files_ref_store *refs,2689struct ref_update *update,2690const char*referent,2691struct ref_transaction *transaction,2692struct string_list *affected_refnames,2693struct strbuf *err)2694{2695struct string_list_item *item;2696struct ref_update *new_update;2697unsigned int new_flags;26982699/*2700 * First make sure that referent is not already in the2701 * transaction. This insertion is O(N) in the transaction2702 * size, but it happens at most once per symref in a2703 * transaction.2704 */2705 item =string_list_insert(affected_refnames, referent);2706if(item->util) {2707/* An entry already existed */2708strbuf_addf(err,2709"multiple updates for '%s' (including one "2710"via symref '%s') are not allowed",2711 referent, update->refname);2712return TRANSACTION_NAME_CONFLICT;2713}27142715 new_flags = update->flags;2716if(!strcmp(update->refname,"HEAD")) {2717/*2718 * Record that the new update came via HEAD, so that2719 * when we process it, split_head_update() doesn't try2720 * to add another reflog update for HEAD. Note that2721 * this bit will be propagated if the new_update2722 * itself needs to be split.2723 */2724 new_flags |= REF_UPDATE_VIA_HEAD;2725}27262727 new_update =ref_transaction_add_update(2728 transaction, referent, new_flags,2729 update->new_sha1, update->old_sha1,2730 update->msg);27312732 new_update->parent_update = update;27332734/*2735 * Change the symbolic ref update to log only. Also, it2736 * doesn't need to check its old SHA-1 value, as that will be2737 * done when new_update is processed.2738 */2739 update->flags |= REF_LOG_ONLY | REF_NODEREF;2740 update->flags &= ~REF_HAVE_OLD;27412742 item->util = new_update;27432744return0;2745}27462747/*2748 * Return the refname under which update was originally requested.2749 */2750static const char*original_update_refname(struct ref_update *update)2751{2752while(update->parent_update)2753 update = update->parent_update;27542755return update->refname;2756}27572758/*2759 * Check whether the REF_HAVE_OLD and old_oid values stored in update2760 * are consistent with oid, which is the reference's current value. If2761 * everything is OK, return 0; otherwise, write an error message to2762 * err and return -1.2763 */2764static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2765struct strbuf *err)2766{2767if(!(update->flags & REF_HAVE_OLD) ||2768!hashcmp(oid->hash, update->old_sha1))2769return0;27702771if(is_null_sha1(update->old_sha1))2772strbuf_addf(err,"cannot lock ref '%s': "2773"reference already exists",2774original_update_refname(update));2775else if(is_null_oid(oid))2776strbuf_addf(err,"cannot lock ref '%s': "2777"reference is missing but expected%s",2778original_update_refname(update),2779sha1_to_hex(update->old_sha1));2780else2781strbuf_addf(err,"cannot lock ref '%s': "2782"is at%sbut expected%s",2783original_update_refname(update),2784oid_to_hex(oid),2785sha1_to_hex(update->old_sha1));27862787return-1;2788}27892790/*2791 * Prepare for carrying out update:2792 * - Lock the reference referred to by update.2793 * - Read the reference under lock.2794 * - Check that its old SHA-1 value (if specified) is correct, and in2795 * any case record it in update->lock->old_oid for later use when2796 * writing the reflog.2797 * - If it is a symref update without REF_NODEREF, split it up into a2798 * REF_LOG_ONLY update of the symref and add a separate update for2799 * the referent to transaction.2800 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2801 * update of HEAD.2802 */2803static intlock_ref_for_update(struct files_ref_store *refs,2804struct ref_update *update,2805struct ref_transaction *transaction,2806const char*head_ref,2807struct string_list *affected_refnames,2808struct strbuf *err)2809{2810struct strbuf referent = STRBUF_INIT;2811int mustexist = (update->flags & REF_HAVE_OLD) &&2812!is_null_sha1(update->old_sha1);2813int ret;2814struct ref_lock *lock;28152816files_assert_main_repository(refs,"lock_ref_for_update");28172818if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))2819 update->flags |= REF_DELETING;28202821if(head_ref) {2822 ret =split_head_update(update, transaction, head_ref,2823 affected_refnames, err);2824if(ret)2825return ret;2826}28272828 ret =lock_raw_ref(refs, update->refname, mustexist,2829 affected_refnames, NULL,2830&lock, &referent,2831&update->type, err);2832if(ret) {2833char*reason;28342835 reason =strbuf_detach(err, NULL);2836strbuf_addf(err,"cannot lock ref '%s':%s",2837original_update_refname(update), reason);2838free(reason);2839return ret;2840}28412842 update->backend_data = lock;28432844if(update->type & REF_ISSYMREF) {2845if(update->flags & REF_NODEREF) {2846/*2847 * We won't be reading the referent as part of2848 * the transaction, so we have to read it here2849 * to record and possibly check old_sha1:2850 */2851if(refs_read_ref_full(&refs->base,2852 referent.buf,0,2853 lock->old_oid.hash, NULL)) {2854if(update->flags & REF_HAVE_OLD) {2855strbuf_addf(err,"cannot lock ref '%s': "2856"error reading reference",2857original_update_refname(update));2858return-1;2859}2860}else if(check_old_oid(update, &lock->old_oid, err)) {2861return TRANSACTION_GENERIC_ERROR;2862}2863}else{2864/*2865 * Create a new update for the reference this2866 * symref is pointing at. Also, we will record2867 * and verify old_sha1 for this update as part2868 * of processing the split-off update, so we2869 * don't have to do it here.2870 */2871 ret =split_symref_update(refs, update,2872 referent.buf, transaction,2873 affected_refnames, err);2874if(ret)2875return ret;2876}2877}else{2878struct ref_update *parent_update;28792880if(check_old_oid(update, &lock->old_oid, err))2881return TRANSACTION_GENERIC_ERROR;28822883/*2884 * If this update is happening indirectly because of a2885 * symref update, record the old SHA-1 in the parent2886 * update:2887 */2888for(parent_update = update->parent_update;2889 parent_update;2890 parent_update = parent_update->parent_update) {2891struct ref_lock *parent_lock = parent_update->backend_data;2892oidcpy(&parent_lock->old_oid, &lock->old_oid);2893}2894}28952896if((update->flags & REF_HAVE_NEW) &&2897!(update->flags & REF_DELETING) &&2898!(update->flags & REF_LOG_ONLY)) {2899if(!(update->type & REF_ISSYMREF) &&2900!hashcmp(lock->old_oid.hash, update->new_sha1)) {2901/*2902 * The reference already has the desired2903 * value, so we don't need to write it.2904 */2905}else if(write_ref_to_lockfile(lock, update->new_sha1,2906 err)) {2907char*write_err =strbuf_detach(err, NULL);29082909/*2910 * The lock was freed upon failure of2911 * write_ref_to_lockfile():2912 */2913 update->backend_data = NULL;2914strbuf_addf(err,2915"cannot update ref '%s':%s",2916 update->refname, write_err);2917free(write_err);2918return TRANSACTION_GENERIC_ERROR;2919}else{2920 update->flags |= REF_NEEDS_COMMIT;2921}2922}2923if(!(update->flags & REF_NEEDS_COMMIT)) {2924/*2925 * We didn't call write_ref_to_lockfile(), so2926 * the lockfile is still open. Close it to2927 * free up the file descriptor:2928 */2929if(close_ref(lock)) {2930strbuf_addf(err,"couldn't close '%s.lock'",2931 update->refname);2932return TRANSACTION_GENERIC_ERROR;2933}2934}2935return0;2936}29372938static intfiles_transaction_commit(struct ref_store *ref_store,2939struct ref_transaction *transaction,2940struct strbuf *err)2941{2942struct files_ref_store *refs =2943files_downcast(ref_store, REF_STORE_WRITE,2944"ref_transaction_commit");2945int ret =0, i;2946struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2947struct string_list_item *ref_to_delete;2948struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2949char*head_ref = NULL;2950int head_type;2951struct object_id head_oid;2952struct strbuf sb = STRBUF_INIT;29532954assert(err);29552956if(transaction->state != REF_TRANSACTION_OPEN)2957die("BUG: commit called for transaction that is not open");29582959if(!transaction->nr) {2960 transaction->state = REF_TRANSACTION_CLOSED;2961return0;2962}29632964/*2965 * Fail if a refname appears more than once in the2966 * transaction. (If we end up splitting up any updates using2967 * split_symref_update() or split_head_update(), those2968 * functions will check that the new updates don't have the2969 * same refname as any existing ones.)2970 */2971for(i =0; i < transaction->nr; i++) {2972struct ref_update *update = transaction->updates[i];2973struct string_list_item *item =2974string_list_append(&affected_refnames, update->refname);29752976/*2977 * We store a pointer to update in item->util, but at2978 * the moment we never use the value of this field2979 * except to check whether it is non-NULL.2980 */2981 item->util = update;2982}2983string_list_sort(&affected_refnames);2984if(ref_update_reject_duplicates(&affected_refnames, err)) {2985 ret = TRANSACTION_GENERIC_ERROR;2986goto cleanup;2987}29882989/*2990 * Special hack: If a branch is updated directly and HEAD2991 * points to it (may happen on the remote side of a push2992 * for example) then logically the HEAD reflog should be2993 * updated too.2994 *2995 * A generic solution would require reverse symref lookups,2996 * but finding all symrefs pointing to a given branch would be2997 * rather costly for this rare event (the direct update of a2998 * branch) to be worth it. So let's cheat and check with HEAD2999 * only, which should cover 99% of all usage scenarios (even3000 * 100% of the default ones).3001 *3002 * So if HEAD is a symbolic reference, then record the name of3003 * the reference that it points to. If we see an update of3004 * head_ref within the transaction, then split_head_update()3005 * arranges for the reflog of HEAD to be updated, too.3006 */3007 head_ref =refs_resolve_refdup(ref_store,"HEAD",3008 RESOLVE_REF_NO_RECURSE,3009 head_oid.hash, &head_type);30103011if(head_ref && !(head_type & REF_ISSYMREF)) {3012free(head_ref);3013 head_ref = NULL;3014}30153016/*3017 * Acquire all locks, verify old values if provided, check3018 * that new values are valid, and write new values to the3019 * lockfiles, ready to be activated. Only keep one lockfile3020 * open at a time to avoid running out of file descriptors.3021 */3022for(i =0; i < transaction->nr; i++) {3023struct ref_update *update = transaction->updates[i];30243025 ret =lock_ref_for_update(refs, update, transaction,3026 head_ref, &affected_refnames, err);3027if(ret)3028goto cleanup;3029}30303031/* Perform updates first so live commits remain referenced */3032for(i =0; i < transaction->nr; i++) {3033struct ref_update *update = transaction->updates[i];3034struct ref_lock *lock = update->backend_data;30353036if(update->flags & REF_NEEDS_COMMIT ||3037 update->flags & REF_LOG_ONLY) {3038if(files_log_ref_write(refs,3039 lock->ref_name,3040 lock->old_oid.hash,3041 update->new_sha1,3042 update->msg, update->flags,3043 err)) {3044char*old_msg =strbuf_detach(err, NULL);30453046strbuf_addf(err,"cannot update the ref '%s':%s",3047 lock->ref_name, old_msg);3048free(old_msg);3049unlock_ref(lock);3050 update->backend_data = NULL;3051 ret = TRANSACTION_GENERIC_ERROR;3052goto cleanup;3053}3054}3055if(update->flags & REF_NEEDS_COMMIT) {3056clear_loose_ref_cache(refs);3057if(commit_ref(lock)) {3058strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3059unlock_ref(lock);3060 update->backend_data = NULL;3061 ret = TRANSACTION_GENERIC_ERROR;3062goto cleanup;3063}3064}3065}3066/* Perform deletes now that updates are safely completed */3067for(i =0; i < transaction->nr; i++) {3068struct ref_update *update = transaction->updates[i];3069struct ref_lock *lock = update->backend_data;30703071if(update->flags & REF_DELETING &&3072!(update->flags & REF_LOG_ONLY)) {3073if(!(update->type & REF_ISPACKED) ||3074 update->type & REF_ISSYMREF) {3075/* It is a loose reference. */3076strbuf_reset(&sb);3077files_ref_path(refs, &sb, lock->ref_name);3078if(unlink_or_msg(sb.buf, err)) {3079 ret = TRANSACTION_GENERIC_ERROR;3080goto cleanup;3081}3082 update->flags |= REF_DELETED_LOOSE;3083}30843085if(!(update->flags & REF_ISPRUNING))3086string_list_append(&refs_to_delete,3087 lock->ref_name);3088}3089}30903091if(repack_without_refs(refs, &refs_to_delete, err)) {3092 ret = TRANSACTION_GENERIC_ERROR;3093goto cleanup;3094}30953096/* Delete the reflogs of any references that were deleted: */3097for_each_string_list_item(ref_to_delete, &refs_to_delete) {3098strbuf_reset(&sb);3099files_reflog_path(refs, &sb, ref_to_delete->string);3100if(!unlink_or_warn(sb.buf))3101try_remove_empty_parents(refs, ref_to_delete->string,3102 REMOVE_EMPTY_PARENTS_REFLOG);3103}31043105clear_loose_ref_cache(refs);31063107cleanup:3108strbuf_release(&sb);3109 transaction->state = REF_TRANSACTION_CLOSED;31103111for(i =0; i < transaction->nr; i++) {3112struct ref_update *update = transaction->updates[i];3113struct ref_lock *lock = update->backend_data;31143115if(lock)3116unlock_ref(lock);31173118if(update->flags & REF_DELETED_LOOSE) {3119/*3120 * The loose reference was deleted. Delete any3121 * empty parent directories. (Note that this3122 * can only work because we have already3123 * removed the lockfile.)3124 */3125try_remove_empty_parents(refs, update->refname,3126 REMOVE_EMPTY_PARENTS_REF);3127}3128}31293130string_list_clear(&refs_to_delete,0);3131free(head_ref);3132string_list_clear(&affected_refnames,0);31333134return ret;3135}31363137static intref_present(const char*refname,3138const struct object_id *oid,int flags,void*cb_data)3139{3140struct string_list *affected_refnames = cb_data;31413142returnstring_list_has_string(affected_refnames, refname);3143}31443145static intfiles_initial_transaction_commit(struct ref_store *ref_store,3146struct ref_transaction *transaction,3147struct strbuf *err)3148{3149struct files_ref_store *refs =3150files_downcast(ref_store, REF_STORE_WRITE,3151"initial_ref_transaction_commit");3152int ret =0, i;3153struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31543155assert(err);31563157if(transaction->state != REF_TRANSACTION_OPEN)3158die("BUG: commit called for transaction that is not open");31593160/* Fail if a refname appears more than once in the transaction: */3161for(i =0; i < transaction->nr; i++)3162string_list_append(&affected_refnames,3163 transaction->updates[i]->refname);3164string_list_sort(&affected_refnames);3165if(ref_update_reject_duplicates(&affected_refnames, err)) {3166 ret = TRANSACTION_GENERIC_ERROR;3167goto cleanup;3168}31693170/*3171 * It's really undefined to call this function in an active3172 * repository or when there are existing references: we are3173 * only locking and changing packed-refs, so (1) any3174 * simultaneous processes might try to change a reference at3175 * the same time we do, and (2) any existing loose versions of3176 * the references that we are setting would have precedence3177 * over our values. But some remote helpers create the remote3178 * "HEAD" and "master" branches before calling this function,3179 * so here we really only check that none of the references3180 * that we are creating already exists.3181 */3182if(refs_for_each_rawref(&refs->base, ref_present,3183&affected_refnames))3184die("BUG: initial ref transaction called with existing refs");31853186for(i =0; i < transaction->nr; i++) {3187struct ref_update *update = transaction->updates[i];31883189if((update->flags & REF_HAVE_OLD) &&3190!is_null_sha1(update->old_sha1))3191die("BUG: initial ref transaction with old_sha1 set");3192if(refs_verify_refname_available(&refs->base, update->refname,3193&affected_refnames, NULL,3194 err)) {3195 ret = TRANSACTION_NAME_CONFLICT;3196goto cleanup;3197}3198}31993200if(lock_packed_refs(refs,0)) {3201strbuf_addf(err,"unable to lock packed-refs file:%s",3202strerror(errno));3203 ret = TRANSACTION_GENERIC_ERROR;3204goto cleanup;3205}32063207for(i =0; i < transaction->nr; i++) {3208struct ref_update *update = transaction->updates[i];32093210if((update->flags & REF_HAVE_NEW) &&3211!is_null_sha1(update->new_sha1))3212add_packed_ref(refs, update->refname, update->new_sha1);3213}32143215if(commit_packed_refs(refs)) {3216strbuf_addf(err,"unable to commit packed-refs file:%s",3217strerror(errno));3218 ret = TRANSACTION_GENERIC_ERROR;3219goto cleanup;3220}32213222cleanup:3223 transaction->state = REF_TRANSACTION_CLOSED;3224string_list_clear(&affected_refnames,0);3225return ret;3226}32273228struct expire_reflog_cb {3229unsigned int flags;3230 reflog_expiry_should_prune_fn *should_prune_fn;3231void*policy_cb;3232FILE*newlog;3233struct object_id last_kept_oid;3234};32353236static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3237const char*email,unsigned long timestamp,int tz,3238const char*message,void*cb_data)3239{3240struct expire_reflog_cb *cb = cb_data;3241struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32423243if(cb->flags & EXPIRE_REFLOGS_REWRITE)3244 ooid = &cb->last_kept_oid;32453246if((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,3247 message, policy_cb)) {3248if(!cb->newlog)3249printf("would prune%s", message);3250else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3251printf("prune%s", message);3252}else{3253if(cb->newlog) {3254fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3255oid_to_hex(ooid),oid_to_hex(noid),3256 email, timestamp, tz, message);3257oidcpy(&cb->last_kept_oid, noid);3258}3259if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3260printf("keep%s", message);3261}3262return0;3263}32643265static intfiles_reflog_expire(struct ref_store *ref_store,3266const char*refname,const unsigned char*sha1,3267unsigned int flags,3268 reflog_expiry_prepare_fn prepare_fn,3269 reflog_expiry_should_prune_fn should_prune_fn,3270 reflog_expiry_cleanup_fn cleanup_fn,3271void*policy_cb_data)3272{3273struct files_ref_store *refs =3274files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3275static struct lock_file reflog_lock;3276struct expire_reflog_cb cb;3277struct ref_lock *lock;3278struct strbuf log_file_sb = STRBUF_INIT;3279char*log_file;3280int status =0;3281int type;3282struct strbuf err = STRBUF_INIT;32833284memset(&cb,0,sizeof(cb));3285 cb.flags = flags;3286 cb.policy_cb = policy_cb_data;3287 cb.should_prune_fn = should_prune_fn;32883289/*3290 * The reflog file is locked by holding the lock on the3291 * reference itself, plus we might need to update the3292 * reference if --updateref was specified:3293 */3294 lock =lock_ref_sha1_basic(refs, refname, sha1,3295 NULL, NULL, REF_NODEREF,3296&type, &err);3297if(!lock) {3298error("cannot lock ref '%s':%s", refname, err.buf);3299strbuf_release(&err);3300return-1;3301}3302if(!refs_reflog_exists(ref_store, refname)) {3303unlock_ref(lock);3304return0;3305}33063307files_reflog_path(refs, &log_file_sb, refname);3308 log_file =strbuf_detach(&log_file_sb, NULL);3309if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3310/*3311 * Even though holding $GIT_DIR/logs/$reflog.lock has3312 * no locking implications, we use the lock_file3313 * machinery here anyway because it does a lot of the3314 * work we need, including cleaning up if the program3315 * exits unexpectedly.3316 */3317if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3318struct strbuf err = STRBUF_INIT;3319unable_to_lock_message(log_file, errno, &err);3320error("%s", err.buf);3321strbuf_release(&err);3322goto failure;3323}3324 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3325if(!cb.newlog) {3326error("cannot fdopen%s(%s)",3327get_lock_file_path(&reflog_lock),strerror(errno));3328goto failure;3329}3330}33313332(*prepare_fn)(refname, sha1, cb.policy_cb);3333refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3334(*cleanup_fn)(cb.policy_cb);33353336if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3337/*3338 * It doesn't make sense to adjust a reference pointed3339 * to by a symbolic ref based on expiring entries in3340 * the symbolic reference's reflog. Nor can we update3341 * a reference if there are no remaining reflog3342 * entries.3343 */3344int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3345!(type & REF_ISSYMREF) &&3346!is_null_oid(&cb.last_kept_oid);33473348if(close_lock_file(&reflog_lock)) {3349 status |=error("couldn't write%s:%s", log_file,3350strerror(errno));3351}else if(update &&3352(write_in_full(get_lock_file_fd(lock->lk),3353oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3354write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3355close_ref(lock) <0)) {3356 status |=error("couldn't write%s",3357get_lock_file_path(lock->lk));3358rollback_lock_file(&reflog_lock);3359}else if(commit_lock_file(&reflog_lock)) {3360 status |=error("unable to write reflog '%s' (%s)",3361 log_file,strerror(errno));3362}else if(update &&commit_ref(lock)) {3363 status |=error("couldn't set%s", lock->ref_name);3364}3365}3366free(log_file);3367unlock_ref(lock);3368return status;33693370 failure:3371rollback_lock_file(&reflog_lock);3372free(log_file);3373unlock_ref(lock);3374return-1;3375}33763377static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3378{3379struct files_ref_store *refs =3380files_downcast(ref_store, REF_STORE_WRITE,"init_db");3381struct strbuf sb = STRBUF_INIT;33823383/*3384 * Create .git/refs/{heads,tags}3385 */3386files_ref_path(refs, &sb,"refs/heads");3387safe_create_dir(sb.buf,1);33883389strbuf_reset(&sb);3390files_ref_path(refs, &sb,"refs/tags");3391safe_create_dir(sb.buf,1);33923393strbuf_release(&sb);3394return0;3395}33963397struct ref_storage_be refs_be_files = {3398 NULL,3399"files",3400 files_ref_store_create,3401 files_init_db,3402 files_transaction_commit,3403 files_initial_transaction_commit,34043405 files_pack_refs,3406 files_peel_ref,3407 files_create_symref,3408 files_delete_refs,3409 files_rename_ref,34103411 files_ref_iterator_begin,3412 files_read_raw_ref,34133414 files_reflog_iterator_begin,3415 files_for_each_reflog_ent,3416 files_for_each_reflog_ent_reverse,3417 files_reflog_exists,3418 files_create_reflog,3419 files_delete_reflog,3420 files_reflog_expire3421};