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_entry *root; 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_entry *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_entry(packed_refs->root); 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_entry(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->root =create_dir_entry(refs,"",0,0); 390 f =fopen(packed_refs_file,"r"); 391if(f) { 392stat_validity_update(&refs->packed->validity,fileno(f)); 393read_packed_refs(f,get_ref_dir(refs->packed->root)); 394fclose(f); 395} 396} 397return refs->packed; 398} 399 400static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 401{ 402returnget_ref_dir(packed_ref_cache->root); 403} 404 405static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 406{ 407returnget_packed_ref_dir(get_packed_ref_cache(refs)); 408} 409 410/* 411 * Add a reference to the in-memory packed reference cache. This may 412 * only be called while the packed-refs file is locked (see 413 * lock_packed_refs()). To actually write the packed-refs file, call 414 * commit_packed_refs(). 415 */ 416static voidadd_packed_ref(struct files_ref_store *refs, 417const char*refname,const unsigned char*sha1) 418{ 419struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 420 421if(!packed_ref_cache->lock) 422die("internal error: packed refs not locked"); 423add_ref_entry(get_packed_ref_dir(packed_ref_cache), 424create_ref_entry(refname, sha1, REF_ISPACKED,1)); 425} 426 427/* 428 * Read the loose references from the namespace dirname into dir 429 * (without recursing). dirname must end with '/'. dir must be the 430 * directory entry corresponding to dirname. 431 */ 432voidread_loose_refs(const char*dirname,struct ref_dir *dir) 433{ 434struct files_ref_store *refs = dir->ref_store; 435DIR*d; 436struct dirent *de; 437int dirnamelen =strlen(dirname); 438struct strbuf refname; 439struct strbuf path = STRBUF_INIT; 440size_t path_baselen; 441 442files_ref_path(refs, &path, dirname); 443 path_baselen = path.len; 444 445 d =opendir(path.buf); 446if(!d) { 447strbuf_release(&path); 448return; 449} 450 451strbuf_init(&refname, dirnamelen +257); 452strbuf_add(&refname, dirname, dirnamelen); 453 454while((de =readdir(d)) != NULL) { 455unsigned char sha1[20]; 456struct stat st; 457int flag; 458 459if(de->d_name[0] =='.') 460continue; 461if(ends_with(de->d_name,".lock")) 462continue; 463strbuf_addstr(&refname, de->d_name); 464strbuf_addstr(&path, de->d_name); 465if(stat(path.buf, &st) <0) { 466;/* silently ignore */ 467}else if(S_ISDIR(st.st_mode)) { 468strbuf_addch(&refname,'/'); 469add_entry_to_dir(dir, 470create_dir_entry(refs, refname.buf, 471 refname.len,1)); 472}else{ 473if(!refs_resolve_ref_unsafe(&refs->base, 474 refname.buf, 475 RESOLVE_REF_READING, 476 sha1, &flag)) { 477hashclr(sha1); 478 flag |= REF_ISBROKEN; 479}else if(is_null_sha1(sha1)) { 480/* 481 * It is so astronomically unlikely 482 * that NULL_SHA1 is the SHA-1 of an 483 * actual object that we consider its 484 * appearance in a loose reference 485 * file to be repo corruption 486 * (probably due to a software bug). 487 */ 488 flag |= REF_ISBROKEN; 489} 490 491if(check_refname_format(refname.buf, 492 REFNAME_ALLOW_ONELEVEL)) { 493if(!refname_is_safe(refname.buf)) 494die("loose refname is dangerous:%s", refname.buf); 495hashclr(sha1); 496 flag |= REF_BAD_NAME | REF_ISBROKEN; 497} 498add_entry_to_dir(dir, 499create_ref_entry(refname.buf, sha1, flag,0)); 500} 501strbuf_setlen(&refname, dirnamelen); 502strbuf_setlen(&path, path_baselen); 503} 504strbuf_release(&refname); 505strbuf_release(&path); 506closedir(d); 507} 508 509static struct ref_dir *get_loose_refs(struct files_ref_store *refs) 510{ 511if(!refs->loose) { 512/* 513 * Mark the top-level directory complete because we 514 * are about to read the only subdirectory that can 515 * hold references: 516 */ 517 refs->loose =create_dir_entry(refs,"",0,0); 518/* 519 * Create an incomplete entry for "refs/": 520 */ 521add_entry_to_dir(get_ref_dir(refs->loose), 522create_dir_entry(refs,"refs/",5,1)); 523} 524returnget_ref_dir(refs->loose); 525} 526 527/* 528 * Return the ref_entry for the given refname from the packed 529 * references. If it does not exist, return NULL. 530 */ 531static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 532const char*refname) 533{ 534returnfind_ref_entry(get_packed_refs(refs), refname); 535} 536 537/* 538 * A loose ref file doesn't exist; check for a packed ref. 539 */ 540static intresolve_packed_ref(struct files_ref_store *refs, 541const char*refname, 542unsigned char*sha1,unsigned int*flags) 543{ 544struct ref_entry *entry; 545 546/* 547 * The loose reference file does not exist; check for a packed 548 * reference. 549 */ 550 entry =get_packed_ref(refs, refname); 551if(entry) { 552hashcpy(sha1, entry->u.value.oid.hash); 553*flags |= REF_ISPACKED; 554return0; 555} 556/* refname is not a packed reference. */ 557return-1; 558} 559 560static intfiles_read_raw_ref(struct ref_store *ref_store, 561const char*refname,unsigned char*sha1, 562struct strbuf *referent,unsigned int*type) 563{ 564struct files_ref_store *refs = 565files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 566struct strbuf sb_contents = STRBUF_INIT; 567struct strbuf sb_path = STRBUF_INIT; 568const char*path; 569const char*buf; 570struct stat st; 571int fd; 572int ret = -1; 573int save_errno; 574int remaining_retries =3; 575 576*type =0; 577strbuf_reset(&sb_path); 578 579files_ref_path(refs, &sb_path, refname); 580 581 path = sb_path.buf; 582 583stat_ref: 584/* 585 * We might have to loop back here to avoid a race 586 * condition: first we lstat() the file, then we try 587 * to read it as a link or as a file. But if somebody 588 * changes the type of the file (file <-> directory 589 * <-> symlink) between the lstat() and reading, then 590 * we don't want to report that as an error but rather 591 * try again starting with the lstat(). 592 * 593 * We'll keep a count of the retries, though, just to avoid 594 * any confusing situation sending us into an infinite loop. 595 */ 596 597if(remaining_retries-- <=0) 598goto out; 599 600if(lstat(path, &st) <0) { 601if(errno != ENOENT) 602goto out; 603if(resolve_packed_ref(refs, refname, sha1, type)) { 604 errno = ENOENT; 605goto out; 606} 607 ret =0; 608goto out; 609} 610 611/* Follow "normalized" - ie "refs/.." symlinks by hand */ 612if(S_ISLNK(st.st_mode)) { 613strbuf_reset(&sb_contents); 614if(strbuf_readlink(&sb_contents, path,0) <0) { 615if(errno == ENOENT || errno == EINVAL) 616/* inconsistent with lstat; retry */ 617goto stat_ref; 618else 619goto out; 620} 621if(starts_with(sb_contents.buf,"refs/") && 622!check_refname_format(sb_contents.buf,0)) { 623strbuf_swap(&sb_contents, referent); 624*type |= REF_ISSYMREF; 625 ret =0; 626goto out; 627} 628/* 629 * It doesn't look like a refname; fall through to just 630 * treating it like a non-symlink, and reading whatever it 631 * points to. 632 */ 633} 634 635/* Is it a directory? */ 636if(S_ISDIR(st.st_mode)) { 637/* 638 * Even though there is a directory where the loose 639 * ref is supposed to be, there could still be a 640 * packed ref: 641 */ 642if(resolve_packed_ref(refs, refname, sha1, type)) { 643 errno = EISDIR; 644goto out; 645} 646 ret =0; 647goto out; 648} 649 650/* 651 * Anything else, just open it and try to use it as 652 * a ref 653 */ 654 fd =open(path, O_RDONLY); 655if(fd <0) { 656if(errno == ENOENT && !S_ISLNK(st.st_mode)) 657/* inconsistent with lstat; retry */ 658goto stat_ref; 659else 660goto out; 661} 662strbuf_reset(&sb_contents); 663if(strbuf_read(&sb_contents, fd,256) <0) { 664int save_errno = errno; 665close(fd); 666 errno = save_errno; 667goto out; 668} 669close(fd); 670strbuf_rtrim(&sb_contents); 671 buf = sb_contents.buf; 672if(starts_with(buf,"ref:")) { 673 buf +=4; 674while(isspace(*buf)) 675 buf++; 676 677strbuf_reset(referent); 678strbuf_addstr(referent, buf); 679*type |= REF_ISSYMREF; 680 ret =0; 681goto out; 682} 683 684/* 685 * Please note that FETCH_HEAD has additional 686 * data after the sha. 687 */ 688if(get_sha1_hex(buf, sha1) || 689(buf[40] !='\0'&& !isspace(buf[40]))) { 690*type |= REF_ISBROKEN; 691 errno = EINVAL; 692goto out; 693} 694 695 ret =0; 696 697out: 698 save_errno = errno; 699strbuf_release(&sb_path); 700strbuf_release(&sb_contents); 701 errno = save_errno; 702return ret; 703} 704 705static voidunlock_ref(struct ref_lock *lock) 706{ 707/* Do not free lock->lk -- atexit() still looks at them */ 708if(lock->lk) 709rollback_lock_file(lock->lk); 710free(lock->ref_name); 711free(lock); 712} 713 714/* 715 * Lock refname, without following symrefs, and set *lock_p to point 716 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 717 * and type similarly to read_raw_ref(). 718 * 719 * The caller must verify that refname is a "safe" reference name (in 720 * the sense of refname_is_safe()) before calling this function. 721 * 722 * If the reference doesn't already exist, verify that refname doesn't 723 * have a D/F conflict with any existing references. extras and skip 724 * are passed to refs_verify_refname_available() for this check. 725 * 726 * If mustexist is not set and the reference is not found or is 727 * broken, lock the reference anyway but clear sha1. 728 * 729 * Return 0 on success. On failure, write an error message to err and 730 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 731 * 732 * Implementation note: This function is basically 733 * 734 * lock reference 735 * read_raw_ref() 736 * 737 * but it includes a lot more code to 738 * - Deal with possible races with other processes 739 * - Avoid calling refs_verify_refname_available() when it can be 740 * avoided, namely if we were successfully able to read the ref 741 * - Generate informative error messages in the case of failure 742 */ 743static intlock_raw_ref(struct files_ref_store *refs, 744const char*refname,int mustexist, 745const struct string_list *extras, 746const struct string_list *skip, 747struct ref_lock **lock_p, 748struct strbuf *referent, 749unsigned int*type, 750struct strbuf *err) 751{ 752struct ref_lock *lock; 753struct strbuf ref_file = STRBUF_INIT; 754int attempts_remaining =3; 755int ret = TRANSACTION_GENERIC_ERROR; 756 757assert(err); 758files_assert_main_repository(refs,"lock_raw_ref"); 759 760*type =0; 761 762/* First lock the file so it can't change out from under us. */ 763 764*lock_p = lock =xcalloc(1,sizeof(*lock)); 765 766 lock->ref_name =xstrdup(refname); 767files_ref_path(refs, &ref_file, refname); 768 769retry: 770switch(safe_create_leading_directories(ref_file.buf)) { 771case SCLD_OK: 772break;/* success */ 773case SCLD_EXISTS: 774/* 775 * Suppose refname is "refs/foo/bar". We just failed 776 * to create the containing directory, "refs/foo", 777 * because there was a non-directory in the way. This 778 * indicates a D/F conflict, probably because of 779 * another reference such as "refs/foo". There is no 780 * reason to expect this error to be transitory. 781 */ 782if(refs_verify_refname_available(&refs->base, refname, 783 extras, skip, err)) { 784if(mustexist) { 785/* 786 * To the user the relevant error is 787 * that the "mustexist" reference is 788 * missing: 789 */ 790strbuf_reset(err); 791strbuf_addf(err,"unable to resolve reference '%s'", 792 refname); 793}else{ 794/* 795 * The error message set by 796 * refs_verify_refname_available() is 797 * OK. 798 */ 799 ret = TRANSACTION_NAME_CONFLICT; 800} 801}else{ 802/* 803 * The file that is in the way isn't a loose 804 * reference. Report it as a low-level 805 * failure. 806 */ 807strbuf_addf(err,"unable to create lock file%s.lock; " 808"non-directory in the way", 809 ref_file.buf); 810} 811goto error_return; 812case SCLD_VANISHED: 813/* Maybe another process was tidying up. Try again. */ 814if(--attempts_remaining >0) 815goto retry; 816/* fall through */ 817default: 818strbuf_addf(err,"unable to create directory for%s", 819 ref_file.buf); 820goto error_return; 821} 822 823if(!lock->lk) 824 lock->lk =xcalloc(1,sizeof(struct lock_file)); 825 826if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 827if(errno == ENOENT && --attempts_remaining >0) { 828/* 829 * Maybe somebody just deleted one of the 830 * directories leading to ref_file. Try 831 * again: 832 */ 833goto retry; 834}else{ 835unable_to_lock_message(ref_file.buf, errno, err); 836goto error_return; 837} 838} 839 840/* 841 * Now we hold the lock and can read the reference without 842 * fear that its value will change. 843 */ 844 845if(files_read_raw_ref(&refs->base, refname, 846 lock->old_oid.hash, referent, type)) { 847if(errno == ENOENT) { 848if(mustexist) { 849/* Garden variety missing reference. */ 850strbuf_addf(err,"unable to resolve reference '%s'", 851 refname); 852goto error_return; 853}else{ 854/* 855 * Reference is missing, but that's OK. We 856 * know that there is not a conflict with 857 * another loose reference because 858 * (supposing that we are trying to lock 859 * reference "refs/foo/bar"): 860 * 861 * - We were successfully able to create 862 * the lockfile refs/foo/bar.lock, so we 863 * know there cannot be a loose reference 864 * named "refs/foo". 865 * 866 * - We got ENOENT and not EISDIR, so we 867 * know that there cannot be a loose 868 * reference named "refs/foo/bar/baz". 869 */ 870} 871}else if(errno == EISDIR) { 872/* 873 * There is a directory in the way. It might have 874 * contained references that have been deleted. If 875 * we don't require that the reference already 876 * exists, try to remove the directory so that it 877 * doesn't cause trouble when we want to rename the 878 * lockfile into place later. 879 */ 880if(mustexist) { 881/* Garden variety missing reference. */ 882strbuf_addf(err,"unable to resolve reference '%s'", 883 refname); 884goto error_return; 885}else if(remove_dir_recursively(&ref_file, 886 REMOVE_DIR_EMPTY_ONLY)) { 887if(refs_verify_refname_available( 888&refs->base, refname, 889 extras, skip, err)) { 890/* 891 * The error message set by 892 * verify_refname_available() is OK. 893 */ 894 ret = TRANSACTION_NAME_CONFLICT; 895goto error_return; 896}else{ 897/* 898 * We can't delete the directory, 899 * but we also don't know of any 900 * references that it should 901 * contain. 902 */ 903strbuf_addf(err,"there is a non-empty directory '%s' " 904"blocking reference '%s'", 905 ref_file.buf, refname); 906goto error_return; 907} 908} 909}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 910strbuf_addf(err,"unable to resolve reference '%s': " 911"reference broken", refname); 912goto error_return; 913}else{ 914strbuf_addf(err,"unable to resolve reference '%s':%s", 915 refname,strerror(errno)); 916goto error_return; 917} 918 919/* 920 * If the ref did not exist and we are creating it, 921 * make sure there is no existing ref that conflicts 922 * with refname: 923 */ 924if(refs_verify_refname_available( 925&refs->base, refname, 926 extras, skip, err)) 927goto error_return; 928} 929 930 ret =0; 931goto out; 932 933error_return: 934unlock_ref(lock); 935*lock_p = NULL; 936 937out: 938strbuf_release(&ref_file); 939return ret; 940} 941 942static intfiles_peel_ref(struct ref_store *ref_store, 943const char*refname,unsigned char*sha1) 944{ 945struct files_ref_store *refs = 946files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 947"peel_ref"); 948int flag; 949unsigned char base[20]; 950 951if(current_ref_iter && current_ref_iter->refname == refname) { 952struct object_id peeled; 953 954if(ref_iterator_peel(current_ref_iter, &peeled)) 955return-1; 956hashcpy(sha1, peeled.hash); 957return0; 958} 959 960if(refs_read_ref_full(ref_store, refname, 961 RESOLVE_REF_READING, base, &flag)) 962return-1; 963 964/* 965 * If the reference is packed, read its ref_entry from the 966 * cache in the hope that we already know its peeled value. 967 * We only try this optimization on packed references because 968 * (a) forcing the filling of the loose reference cache could 969 * be expensive and (b) loose references anyway usually do not 970 * have REF_KNOWS_PEELED. 971 */ 972if(flag & REF_ISPACKED) { 973struct ref_entry *r =get_packed_ref(refs, refname); 974if(r) { 975if(peel_entry(r,0)) 976return-1; 977hashcpy(sha1, r->u.value.peeled.hash); 978return0; 979} 980} 981 982returnpeel_object(base, sha1); 983} 984 985struct files_ref_iterator { 986struct ref_iterator base; 987 988struct packed_ref_cache *packed_ref_cache; 989struct ref_iterator *iter0; 990unsigned int flags; 991}; 992 993static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 994{ 995struct files_ref_iterator *iter = 996(struct files_ref_iterator *)ref_iterator; 997int ok; 998 999while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1000if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1001ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1002continue;10031004if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1005!ref_resolves_to_object(iter->iter0->refname,1006 iter->iter0->oid,1007 iter->iter0->flags))1008continue;10091010 iter->base.refname = iter->iter0->refname;1011 iter->base.oid = iter->iter0->oid;1012 iter->base.flags = iter->iter0->flags;1013return ITER_OK;1014}10151016 iter->iter0 = NULL;1017if(ref_iterator_abort(ref_iterator) != ITER_DONE)1018 ok = ITER_ERROR;10191020return ok;1021}10221023static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1024struct object_id *peeled)1025{1026struct files_ref_iterator *iter =1027(struct files_ref_iterator *)ref_iterator;10281029returnref_iterator_peel(iter->iter0, peeled);1030}10311032static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1033{1034struct files_ref_iterator *iter =1035(struct files_ref_iterator *)ref_iterator;1036int ok = ITER_DONE;10371038if(iter->iter0)1039 ok =ref_iterator_abort(iter->iter0);10401041release_packed_ref_cache(iter->packed_ref_cache);1042base_ref_iterator_free(ref_iterator);1043return ok;1044}10451046static struct ref_iterator_vtable files_ref_iterator_vtable = {1047 files_ref_iterator_advance,1048 files_ref_iterator_peel,1049 files_ref_iterator_abort1050};10511052static struct ref_iterator *files_ref_iterator_begin(1053struct ref_store *ref_store,1054const char*prefix,unsigned int flags)1055{1056struct files_ref_store *refs;1057struct ref_dir *loose_dir, *packed_dir;1058struct ref_iterator *loose_iter, *packed_iter;1059struct files_ref_iterator *iter;1060struct ref_iterator *ref_iterator;10611062if(ref_paranoia <0)1063 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1064if(ref_paranoia)1065 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10661067 refs =files_downcast(ref_store,1068 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1069"ref_iterator_begin");10701071 iter =xcalloc(1,sizeof(*iter));1072 ref_iterator = &iter->base;1073base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10741075/*1076 * We must make sure that all loose refs are read before1077 * accessing the packed-refs file; this avoids a race1078 * condition if loose refs are migrated to the packed-refs1079 * file by a simultaneous process, but our in-memory view is1080 * from before the migration. We ensure this as follows:1081 * First, we call prime_ref_dir(), which pre-reads the loose1082 * references for the subtree into the cache. (If they've1083 * already been read, that's OK; we only need to guarantee1084 * that they're read before the packed refs, not *how much*1085 * before.) After that, we call get_packed_ref_cache(), which1086 * internally checks whether the packed-ref cache is up to1087 * date with what is on disk, and re-reads it if not.1088 */10891090 loose_dir =get_loose_refs(refs);10911092if(prefix && *prefix)1093 loose_dir =find_containing_dir(loose_dir, prefix,0);10941095if(loose_dir) {1096prime_ref_dir(loose_dir);1097 loose_iter =cache_ref_iterator_begin(loose_dir);1098}else{1099/* There's nothing to iterate over. */1100 loose_iter =empty_ref_iterator_begin();1101}11021103 iter->packed_ref_cache =get_packed_ref_cache(refs);1104acquire_packed_ref_cache(iter->packed_ref_cache);1105 packed_dir =get_packed_ref_dir(iter->packed_ref_cache);11061107if(prefix && *prefix)1108 packed_dir =find_containing_dir(packed_dir, prefix,0);11091110if(packed_dir) {1111 packed_iter =cache_ref_iterator_begin(packed_dir);1112}else{1113/* There's nothing to iterate over. */1114 packed_iter =empty_ref_iterator_begin();1115}11161117 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1118 iter->flags = flags;11191120return ref_iterator;1121}11221123/*1124 * Verify that the reference locked by lock has the value old_sha1.1125 * Fail if the reference doesn't exist and mustexist is set. Return 01126 * on success. On error, write an error message to err, set errno, and1127 * return a negative value.1128 */1129static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1130const unsigned char*old_sha1,int mustexist,1131struct strbuf *err)1132{1133assert(err);11341135if(refs_read_ref_full(ref_store, lock->ref_name,1136 mustexist ? RESOLVE_REF_READING :0,1137 lock->old_oid.hash, NULL)) {1138if(old_sha1) {1139int save_errno = errno;1140strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1141 errno = save_errno;1142return-1;1143}else{1144oidclr(&lock->old_oid);1145return0;1146}1147}1148if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1149strbuf_addf(err,"ref '%s' is at%sbut expected%s",1150 lock->ref_name,1151oid_to_hex(&lock->old_oid),1152sha1_to_hex(old_sha1));1153 errno = EBUSY;1154return-1;1155}1156return0;1157}11581159static intremove_empty_directories(struct strbuf *path)1160{1161/*1162 * we want to create a file but there is a directory there;1163 * if that is an empty directory (or a directory that contains1164 * only empty directories), remove them.1165 */1166returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1167}11681169static intcreate_reflock(const char*path,void*cb)1170{1171struct lock_file *lk = cb;11721173returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1174}11751176/*1177 * Locks a ref returning the lock on success and NULL on failure.1178 * On failure errno is set to something meaningful.1179 */1180static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1181const char*refname,1182const unsigned char*old_sha1,1183const struct string_list *extras,1184const struct string_list *skip,1185unsigned int flags,int*type,1186struct strbuf *err)1187{1188struct strbuf ref_file = STRBUF_INIT;1189struct ref_lock *lock;1190int last_errno =0;1191int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1192int resolve_flags = RESOLVE_REF_NO_RECURSE;1193int resolved;11941195files_assert_main_repository(refs,"lock_ref_sha1_basic");1196assert(err);11971198 lock =xcalloc(1,sizeof(struct ref_lock));11991200if(mustexist)1201 resolve_flags |= RESOLVE_REF_READING;1202if(flags & REF_DELETING)1203 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12041205files_ref_path(refs, &ref_file, refname);1206 resolved = !!refs_resolve_ref_unsafe(&refs->base,1207 refname, resolve_flags,1208 lock->old_oid.hash, type);1209if(!resolved && errno == EISDIR) {1210/*1211 * we are trying to lock foo but we used to1212 * have foo/bar which now does not exist;1213 * it is normal for the empty directory 'foo'1214 * to remain.1215 */1216if(remove_empty_directories(&ref_file)) {1217 last_errno = errno;1218if(!refs_verify_refname_available(1219&refs->base,1220 refname, extras, skip, err))1221strbuf_addf(err,"there are still refs under '%s'",1222 refname);1223goto error_return;1224}1225 resolved = !!refs_resolve_ref_unsafe(&refs->base,1226 refname, resolve_flags,1227 lock->old_oid.hash, type);1228}1229if(!resolved) {1230 last_errno = errno;1231if(last_errno != ENOTDIR ||1232!refs_verify_refname_available(&refs->base, refname,1233 extras, skip, err))1234strbuf_addf(err,"unable to resolve reference '%s':%s",1235 refname,strerror(last_errno));12361237goto error_return;1238}12391240/*1241 * If the ref did not exist and we are creating it, make sure1242 * there is no existing packed ref whose name begins with our1243 * refname, nor a packed ref whose name is a proper prefix of1244 * our refname.1245 */1246if(is_null_oid(&lock->old_oid) &&1247refs_verify_refname_available(&refs->base, refname,1248 extras, skip, err)) {1249 last_errno = ENOTDIR;1250goto error_return;1251}12521253 lock->lk =xcalloc(1,sizeof(struct lock_file));12541255 lock->ref_name =xstrdup(refname);12561257if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1258 last_errno = errno;1259unable_to_lock_message(ref_file.buf, errno, err);1260goto error_return;1261}12621263if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1264 last_errno = errno;1265goto error_return;1266}1267goto out;12681269 error_return:1270unlock_ref(lock);1271 lock = NULL;12721273 out:1274strbuf_release(&ref_file);1275 errno = last_errno;1276return lock;1277}12781279/*1280 * Write an entry to the packed-refs file for the specified refname.1281 * If peeled is non-NULL, write it as the entry's peeled value.1282 */1283static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1284unsigned char*peeled)1285{1286fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1287if(peeled)1288fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1289}12901291/*1292 * An each_ref_entry_fn that writes the entry to a packed-refs file.1293 */1294static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1295{1296enum peel_status peel_status =peel_entry(entry,0);12971298if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1299error("internal error:%sis not a valid packed reference!",1300 entry->name);1301write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1302 peel_status == PEEL_PEELED ?1303 entry->u.value.peeled.hash : NULL);1304return0;1305}13061307/*1308 * Lock the packed-refs file for writing. Flags is passed to1309 * hold_lock_file_for_update(). Return 0 on success. On errors, set1310 * errno appropriately and return a nonzero value.1311 */1312static intlock_packed_refs(struct files_ref_store *refs,int flags)1313{1314static int timeout_configured =0;1315static int timeout_value =1000;1316struct packed_ref_cache *packed_ref_cache;13171318files_assert_main_repository(refs,"lock_packed_refs");13191320if(!timeout_configured) {1321git_config_get_int("core.packedrefstimeout", &timeout_value);1322 timeout_configured =1;1323}13241325if(hold_lock_file_for_update_timeout(1326&packlock,files_packed_refs_path(refs),1327 flags, timeout_value) <0)1328return-1;1329/*1330 * Get the current packed-refs while holding the lock. If the1331 * packed-refs file has been modified since we last read it,1332 * this will automatically invalidate the cache and re-read1333 * the packed-refs file.1334 */1335 packed_ref_cache =get_packed_ref_cache(refs);1336 packed_ref_cache->lock = &packlock;1337/* Increment the reference count to prevent it from being freed: */1338acquire_packed_ref_cache(packed_ref_cache);1339return0;1340}13411342/*1343 * Write the current version of the packed refs cache from memory to1344 * disk. The packed-refs file must already be locked for writing (see1345 * lock_packed_refs()). Return zero on success. On errors, set errno1346 * and return a nonzero value1347 */1348static intcommit_packed_refs(struct files_ref_store *refs)1349{1350struct packed_ref_cache *packed_ref_cache =1351get_packed_ref_cache(refs);1352int error =0;1353int save_errno =0;1354FILE*out;13551356files_assert_main_repository(refs,"commit_packed_refs");13571358if(!packed_ref_cache->lock)1359die("internal error: packed-refs not locked");13601361 out =fdopen_lock_file(packed_ref_cache->lock,"w");1362if(!out)1363die_errno("unable to fdopen packed-refs descriptor");13641365fprintf_or_die(out,"%s", PACKED_REFS_HEADER);1366do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),13670, write_packed_entry_fn, out);13681369if(commit_lock_file(packed_ref_cache->lock)) {1370 save_errno = errno;1371 error = -1;1372}1373 packed_ref_cache->lock = NULL;1374release_packed_ref_cache(packed_ref_cache);1375 errno = save_errno;1376return error;1377}13781379/*1380 * Rollback the lockfile for the packed-refs file, and discard the1381 * in-memory packed reference cache. (The packed-refs file will be1382 * read anew if it is needed again after this function is called.)1383 */1384static voidrollback_packed_refs(struct files_ref_store *refs)1385{1386struct packed_ref_cache *packed_ref_cache =1387get_packed_ref_cache(refs);13881389files_assert_main_repository(refs,"rollback_packed_refs");13901391if(!packed_ref_cache->lock)1392die("internal error: packed-refs not locked");1393rollback_lock_file(packed_ref_cache->lock);1394 packed_ref_cache->lock = NULL;1395release_packed_ref_cache(packed_ref_cache);1396clear_packed_ref_cache(refs);1397}13981399struct ref_to_prune {1400struct ref_to_prune *next;1401unsigned char sha1[20];1402char name[FLEX_ARRAY];1403};14041405struct pack_refs_cb_data {1406unsigned int flags;1407struct ref_dir *packed_refs;1408struct ref_to_prune *ref_to_prune;1409};14101411/*1412 * An each_ref_entry_fn that is run over loose references only. If1413 * the loose reference can be packed, add an entry in the packed ref1414 * cache. If the reference should be pruned, also add it to1415 * ref_to_prune in the pack_refs_cb_data.1416 */1417static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)1418{1419struct pack_refs_cb_data *cb = cb_data;1420enum peel_status peel_status;1421struct ref_entry *packed_entry;1422int is_tag_ref =starts_with(entry->name,"refs/tags/");14231424/* Do not pack per-worktree refs: */1425if(ref_type(entry->name) != REF_TYPE_NORMAL)1426return0;14271428/* ALWAYS pack tags */1429if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)1430return0;14311432/* Do not pack symbolic or broken refs: */1433if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))1434return0;14351436/* Add a packed ref cache entry equivalent to the loose entry. */1437 peel_status =peel_entry(entry,1);1438if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1439die("internal error peeling reference%s(%s)",1440 entry->name,oid_to_hex(&entry->u.value.oid));1441 packed_entry =find_ref_entry(cb->packed_refs, entry->name);1442if(packed_entry) {1443/* Overwrite existing packed entry with info from loose entry */1444 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;1445oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);1446}else{1447 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,1448 REF_ISPACKED | REF_KNOWS_PEELED,0);1449add_ref_entry(cb->packed_refs, packed_entry);1450}1451oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);14521453/* Schedule the loose reference for pruning if requested. */1454if((cb->flags & PACK_REFS_PRUNE)) {1455struct ref_to_prune *n;1456FLEX_ALLOC_STR(n, name, entry->name);1457hashcpy(n->sha1, entry->u.value.oid.hash);1458 n->next = cb->ref_to_prune;1459 cb->ref_to_prune = n;1460}1461return0;1462}14631464enum{1465 REMOVE_EMPTY_PARENTS_REF =0x01,1466 REMOVE_EMPTY_PARENTS_REFLOG =0x021467};14681469/*1470 * Remove empty parent directories associated with the specified1471 * reference and/or its reflog, but spare [logs/]refs/ and immediate1472 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1473 * REMOVE_EMPTY_PARENTS_REFLOG.1474 */1475static voidtry_remove_empty_parents(struct files_ref_store *refs,1476const char*refname,1477unsigned int flags)1478{1479struct strbuf buf = STRBUF_INIT;1480struct strbuf sb = STRBUF_INIT;1481char*p, *q;1482int i;14831484strbuf_addstr(&buf, refname);1485 p = buf.buf;1486for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1487while(*p && *p !='/')1488 p++;1489/* tolerate duplicate slashes; see check_refname_format() */1490while(*p =='/')1491 p++;1492}1493 q = buf.buf + buf.len;1494while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1495while(q > p && *q !='/')1496 q--;1497while(q > p && *(q-1) =='/')1498 q--;1499if(q == p)1500break;1501strbuf_setlen(&buf, q - buf.buf);15021503strbuf_reset(&sb);1504files_ref_path(refs, &sb, buf.buf);1505if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1506 flags &= ~REMOVE_EMPTY_PARENTS_REF;15071508strbuf_reset(&sb);1509files_reflog_path(refs, &sb, buf.buf);1510if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1511 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1512}1513strbuf_release(&buf);1514strbuf_release(&sb);1515}15161517/* make sure nobody touched the ref, and unlink */1518static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1519{1520struct ref_transaction *transaction;1521struct strbuf err = STRBUF_INIT;15221523if(check_refname_format(r->name,0))1524return;15251526 transaction =ref_store_transaction_begin(&refs->base, &err);1527if(!transaction ||1528ref_transaction_delete(transaction, r->name, r->sha1,1529 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1530ref_transaction_commit(transaction, &err)) {1531ref_transaction_free(transaction);1532error("%s", err.buf);1533strbuf_release(&err);1534return;1535}1536ref_transaction_free(transaction);1537strbuf_release(&err);1538}15391540static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1541{1542while(r) {1543prune_ref(refs, r);1544 r = r->next;1545}1546}15471548static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1549{1550struct files_ref_store *refs =1551files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1552"pack_refs");1553struct pack_refs_cb_data cbdata;15541555memset(&cbdata,0,sizeof(cbdata));1556 cbdata.flags = flags;15571558lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1559 cbdata.packed_refs =get_packed_refs(refs);15601561do_for_each_entry_in_dir(get_loose_refs(refs),0,1562 pack_if_possible_fn, &cbdata);15631564if(commit_packed_refs(refs))1565die_errno("unable to overwrite old ref-pack file");15661567prune_refs(refs, cbdata.ref_to_prune);1568return0;1569}15701571/*1572 * Rewrite the packed-refs file, omitting any refs listed in1573 * 'refnames'. On error, leave packed-refs unchanged, write an error1574 * message to 'err', and return a nonzero value.1575 *1576 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1577 */1578static intrepack_without_refs(struct files_ref_store *refs,1579struct string_list *refnames,struct strbuf *err)1580{1581struct ref_dir *packed;1582struct string_list_item *refname;1583int ret, needs_repacking =0, removed =0;15841585files_assert_main_repository(refs,"repack_without_refs");1586assert(err);15871588/* Look for a packed ref */1589for_each_string_list_item(refname, refnames) {1590if(get_packed_ref(refs, refname->string)) {1591 needs_repacking =1;1592break;1593}1594}15951596/* Avoid locking if we have nothing to do */1597if(!needs_repacking)1598return0;/* no refname exists in packed refs */15991600if(lock_packed_refs(refs,0)) {1601unable_to_lock_message(files_packed_refs_path(refs), errno, err);1602return-1;1603}1604 packed =get_packed_refs(refs);16051606/* Remove refnames from the cache */1607for_each_string_list_item(refname, refnames)1608if(remove_entry_from_dir(packed, refname->string) != -1)1609 removed =1;1610if(!removed) {1611/*1612 * All packed entries disappeared while we were1613 * acquiring the lock.1614 */1615rollback_packed_refs(refs);1616return0;1617}16181619/* Write what remains */1620 ret =commit_packed_refs(refs);1621if(ret)1622strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1623strerror(errno));1624return ret;1625}16261627static intfiles_delete_refs(struct ref_store *ref_store,1628struct string_list *refnames,unsigned int flags)1629{1630struct files_ref_store *refs =1631files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1632struct strbuf err = STRBUF_INIT;1633int i, result =0;16341635if(!refnames->nr)1636return0;16371638 result =repack_without_refs(refs, refnames, &err);1639if(result) {1640/*1641 * If we failed to rewrite the packed-refs file, then1642 * it is unsafe to try to remove loose refs, because1643 * doing so might expose an obsolete packed value for1644 * a reference that might even point at an object that1645 * has been garbage collected.1646 */1647if(refnames->nr ==1)1648error(_("could not delete reference%s:%s"),1649 refnames->items[0].string, err.buf);1650else1651error(_("could not delete references:%s"), err.buf);16521653goto out;1654}16551656for(i =0; i < refnames->nr; i++) {1657const char*refname = refnames->items[i].string;16581659if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))1660 result |=error(_("could not remove reference%s"), refname);1661}16621663out:1664strbuf_release(&err);1665return result;1666}16671668/*1669 * People using contrib's git-new-workdir have .git/logs/refs ->1670 * /some/other/path/.git/logs/refs, and that may live on another device.1671 *1672 * IOW, to avoid cross device rename errors, the temporary renamed log must1673 * live into logs/refs.1674 */1675#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16761677struct rename_cb {1678const char*tmp_renamed_log;1679int true_errno;1680};16811682static intrename_tmp_log_callback(const char*path,void*cb_data)1683{1684struct rename_cb *cb = cb_data;16851686if(rename(cb->tmp_renamed_log, path)) {1687/*1688 * rename(a, b) when b is an existing directory ought1689 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1690 * Sheesh. Record the true errno for error reporting,1691 * but report EISDIR to raceproof_create_file() so1692 * that it knows to retry.1693 */1694 cb->true_errno = errno;1695if(errno == ENOTDIR)1696 errno = EISDIR;1697return-1;1698}else{1699return0;1700}1701}17021703static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1704{1705struct strbuf path = STRBUF_INIT;1706struct strbuf tmp = STRBUF_INIT;1707struct rename_cb cb;1708int ret;17091710files_reflog_path(refs, &path, newrefname);1711files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1712 cb.tmp_renamed_log = tmp.buf;1713 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1714if(ret) {1715if(errno == EISDIR)1716error("directory not empty:%s", path.buf);1717else1718error("unable to move logfile%sto%s:%s",1719 tmp.buf, path.buf,1720strerror(cb.true_errno));1721}17221723strbuf_release(&path);1724strbuf_release(&tmp);1725return ret;1726}17271728static intwrite_ref_to_lockfile(struct ref_lock *lock,1729const unsigned char*sha1,struct strbuf *err);1730static intcommit_ref_update(struct files_ref_store *refs,1731struct ref_lock *lock,1732const unsigned char*sha1,const char*logmsg,1733struct strbuf *err);17341735static intfiles_rename_ref(struct ref_store *ref_store,1736const char*oldrefname,const char*newrefname,1737const char*logmsg)1738{1739struct files_ref_store *refs =1740files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1741unsigned char sha1[20], orig_sha1[20];1742int flag =0, logmoved =0;1743struct ref_lock *lock;1744struct stat loginfo;1745struct strbuf sb_oldref = STRBUF_INIT;1746struct strbuf sb_newref = STRBUF_INIT;1747struct strbuf tmp_renamed_log = STRBUF_INIT;1748int log, ret;1749struct strbuf err = STRBUF_INIT;17501751files_reflog_path(refs, &sb_oldref, oldrefname);1752files_reflog_path(refs, &sb_newref, newrefname);1753files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17541755 log = !lstat(sb_oldref.buf, &loginfo);1756if(log &&S_ISLNK(loginfo.st_mode)) {1757 ret =error("reflog for%sis a symlink", oldrefname);1758goto out;1759}17601761if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1762 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1763 orig_sha1, &flag)) {1764 ret =error("refname%snot found", oldrefname);1765goto out;1766}17671768if(flag & REF_ISSYMREF) {1769 ret =error("refname%sis a symbolic ref, renaming it is not supported",1770 oldrefname);1771goto out;1772}1773if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1774 ret =1;1775goto out;1776}17771778if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1779 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1780 oldrefname,strerror(errno));1781goto out;1782}17831784if(refs_delete_ref(&refs->base, logmsg, oldrefname,1785 orig_sha1, REF_NODEREF)) {1786error("unable to delete old%s", oldrefname);1787goto rollback;1788}17891790/*1791 * Since we are doing a shallow lookup, sha1 is not the1792 * correct value to pass to delete_ref as old_sha1. But that1793 * doesn't matter, because an old_sha1 check wouldn't add to1794 * the safety anyway; we want to delete the reference whatever1795 * its current value.1796 */1797if(!refs_read_ref_full(&refs->base, newrefname,1798 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1799 sha1, NULL) &&1800refs_delete_ref(&refs->base, NULL, newrefname,1801 NULL, REF_NODEREF)) {1802if(errno == EISDIR) {1803struct strbuf path = STRBUF_INIT;1804int result;18051806files_ref_path(refs, &path, newrefname);1807 result =remove_empty_directories(&path);1808strbuf_release(&path);18091810if(result) {1811error("Directory not empty:%s", newrefname);1812goto rollback;1813}1814}else{1815error("unable to delete existing%s", newrefname);1816goto rollback;1817}1818}18191820if(log &&rename_tmp_log(refs, newrefname))1821goto rollback;18221823 logmoved = log;18241825 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1826 REF_NODEREF, NULL, &err);1827if(!lock) {1828error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1829strbuf_release(&err);1830goto rollback;1831}1832hashcpy(lock->old_oid.hash, orig_sha1);18331834if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1835commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {1836error("unable to write current sha1 into%s:%s", newrefname, err.buf);1837strbuf_release(&err);1838goto rollback;1839}18401841 ret =0;1842goto out;18431844 rollback:1845 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1846 REF_NODEREF, NULL, &err);1847if(!lock) {1848error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1849strbuf_release(&err);1850goto rollbacklog;1851}18521853 flag = log_all_ref_updates;1854 log_all_ref_updates = LOG_REFS_NONE;1855if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1856commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {1857error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1858strbuf_release(&err);1859}1860 log_all_ref_updates = flag;18611862 rollbacklog:1863if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1864error("unable to restore logfile%sfrom%s:%s",1865 oldrefname, newrefname,strerror(errno));1866if(!logmoved && log &&1867rename(tmp_renamed_log.buf, sb_oldref.buf))1868error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1869 oldrefname,strerror(errno));1870 ret =1;1871 out:1872strbuf_release(&sb_newref);1873strbuf_release(&sb_oldref);1874strbuf_release(&tmp_renamed_log);18751876return ret;1877}18781879static intclose_ref(struct ref_lock *lock)1880{1881if(close_lock_file(lock->lk))1882return-1;1883return0;1884}18851886static intcommit_ref(struct ref_lock *lock)1887{1888char*path =get_locked_file_path(lock->lk);1889struct stat st;18901891if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1892/*1893 * There is a directory at the path we want to rename1894 * the lockfile to. Hopefully it is empty; try to1895 * delete it.1896 */1897size_t len =strlen(path);1898struct strbuf sb_path = STRBUF_INIT;18991900strbuf_attach(&sb_path, path, len, len);19011902/*1903 * If this fails, commit_lock_file() will also fail1904 * and will report the problem.1905 */1906remove_empty_directories(&sb_path);1907strbuf_release(&sb_path);1908}else{1909free(path);1910}19111912if(commit_lock_file(lock->lk))1913return-1;1914return0;1915}19161917static intopen_or_create_logfile(const char*path,void*cb)1918{1919int*fd = cb;19201921*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1922return(*fd <0) ? -1:0;1923}19241925/*1926 * Create a reflog for a ref. If force_create = 0, only create the1927 * reflog for certain refs (those for which should_autocreate_reflog1928 * returns non-zero). Otherwise, create it regardless of the reference1929 * name. If the logfile already existed or was created, return 0 and1930 * set *logfd to the file descriptor opened for appending to the file.1931 * If no logfile exists and we decided not to create one, return 0 and1932 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1933 * return -1.1934 */1935static intlog_ref_setup(struct files_ref_store *refs,1936const char*refname,int force_create,1937int*logfd,struct strbuf *err)1938{1939struct strbuf logfile_sb = STRBUF_INIT;1940char*logfile;19411942files_reflog_path(refs, &logfile_sb, refname);1943 logfile =strbuf_detach(&logfile_sb, NULL);19441945if(force_create ||should_autocreate_reflog(refname)) {1946if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1947if(errno == ENOENT)1948strbuf_addf(err,"unable to create directory for '%s': "1949"%s", logfile,strerror(errno));1950else if(errno == EISDIR)1951strbuf_addf(err,"there are still logs under '%s'",1952 logfile);1953else1954strbuf_addf(err,"unable to append to '%s':%s",1955 logfile,strerror(errno));19561957goto error;1958}1959}else{1960*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1961if(*logfd <0) {1962if(errno == ENOENT || errno == EISDIR) {1963/*1964 * The logfile doesn't already exist,1965 * but that is not an error; it only1966 * means that we won't write log1967 * entries to it.1968 */1969;1970}else{1971strbuf_addf(err,"unable to append to '%s':%s",1972 logfile,strerror(errno));1973goto error;1974}1975}1976}19771978if(*logfd >=0)1979adjust_shared_perm(logfile);19801981free(logfile);1982return0;19831984error:1985free(logfile);1986return-1;1987}19881989static intfiles_create_reflog(struct ref_store *ref_store,1990const char*refname,int force_create,1991struct strbuf *err)1992{1993struct files_ref_store *refs =1994files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1995int fd;19961997if(log_ref_setup(refs, refname, force_create, &fd, err))1998return-1;19992000if(fd >=0)2001close(fd);20022003return0;2004}20052006static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2007const unsigned char*new_sha1,2008const char*committer,const char*msg)2009{2010int msglen, written;2011unsigned maxlen, len;2012char*logrec;20132014 msglen = msg ?strlen(msg) :0;2015 maxlen =strlen(committer) + msglen +100;2016 logrec =xmalloc(maxlen);2017 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2018sha1_to_hex(old_sha1),2019sha1_to_hex(new_sha1),2020 committer);2021if(msglen)2022 len +=copy_reflog_msg(logrec + len -1, msg) -1;20232024 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2025free(logrec);2026if(written != len)2027return-1;20282029return0;2030}20312032static intfiles_log_ref_write(struct files_ref_store *refs,2033const char*refname,const unsigned char*old_sha1,2034const unsigned char*new_sha1,const char*msg,2035int flags,struct strbuf *err)2036{2037int logfd, result;20382039if(log_all_ref_updates == LOG_REFS_UNSET)2040 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20412042 result =log_ref_setup(refs, refname,2043 flags & REF_FORCE_CREATE_REFLOG,2044&logfd, err);20452046if(result)2047return result;20482049if(logfd <0)2050return0;2051 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2052git_committer_info(0), msg);2053if(result) {2054struct strbuf sb = STRBUF_INIT;2055int save_errno = errno;20562057files_reflog_path(refs, &sb, refname);2058strbuf_addf(err,"unable to append to '%s':%s",2059 sb.buf,strerror(save_errno));2060strbuf_release(&sb);2061close(logfd);2062return-1;2063}2064if(close(logfd)) {2065struct strbuf sb = STRBUF_INIT;2066int save_errno = errno;20672068files_reflog_path(refs, &sb, refname);2069strbuf_addf(err,"unable to append to '%s':%s",2070 sb.buf,strerror(save_errno));2071strbuf_release(&sb);2072return-1;2073}2074return0;2075}20762077/*2078 * Write sha1 into the open lockfile, then close the lockfile. On2079 * errors, rollback the lockfile, fill in *err and2080 * return -1.2081 */2082static intwrite_ref_to_lockfile(struct ref_lock *lock,2083const unsigned char*sha1,struct strbuf *err)2084{2085static char term ='\n';2086struct object *o;2087int fd;20882089 o =parse_object(sha1);2090if(!o) {2091strbuf_addf(err,2092"trying to write ref '%s' with nonexistent object%s",2093 lock->ref_name,sha1_to_hex(sha1));2094unlock_ref(lock);2095return-1;2096}2097if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2098strbuf_addf(err,2099"trying to write non-commit object%sto branch '%s'",2100sha1_to_hex(sha1), lock->ref_name);2101unlock_ref(lock);2102return-1;2103}2104 fd =get_lock_file_fd(lock->lk);2105if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2106write_in_full(fd, &term,1) !=1||2107close_ref(lock) <0) {2108strbuf_addf(err,2109"couldn't write '%s'",get_lock_file_path(lock->lk));2110unlock_ref(lock);2111return-1;2112}2113return0;2114}21152116/*2117 * Commit a change to a loose reference that has already been written2118 * to the loose reference lockfile. Also update the reflogs if2119 * necessary, using the specified lockmsg (which can be NULL).2120 */2121static intcommit_ref_update(struct files_ref_store *refs,2122struct ref_lock *lock,2123const unsigned char*sha1,const char*logmsg,2124struct strbuf *err)2125{2126files_assert_main_repository(refs,"commit_ref_update");21272128clear_loose_ref_cache(refs);2129if(files_log_ref_write(refs, lock->ref_name,2130 lock->old_oid.hash, sha1,2131 logmsg,0, err)) {2132char*old_msg =strbuf_detach(err, NULL);2133strbuf_addf(err,"cannot update the ref '%s':%s",2134 lock->ref_name, old_msg);2135free(old_msg);2136unlock_ref(lock);2137return-1;2138}21392140if(strcmp(lock->ref_name,"HEAD") !=0) {2141/*2142 * Special hack: If a branch is updated directly and HEAD2143 * points to it (may happen on the remote side of a push2144 * for example) then logically the HEAD reflog should be2145 * updated too.2146 * A generic solution implies reverse symref information,2147 * but finding all symrefs pointing to the given branch2148 * would be rather costly for this rare event (the direct2149 * update of a branch) to be worth it. So let's cheat and2150 * check with HEAD only which should cover 99% of all usage2151 * scenarios (even 100% of the default ones).2152 */2153unsigned char head_sha1[20];2154int head_flag;2155const char*head_ref;21562157 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2158 RESOLVE_REF_READING,2159 head_sha1, &head_flag);2160if(head_ref && (head_flag & REF_ISSYMREF) &&2161!strcmp(head_ref, lock->ref_name)) {2162struct strbuf log_err = STRBUF_INIT;2163if(files_log_ref_write(refs,"HEAD",2164 lock->old_oid.hash, sha1,2165 logmsg,0, &log_err)) {2166error("%s", log_err.buf);2167strbuf_release(&log_err);2168}2169}2170}21712172if(commit_ref(lock)) {2173strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2174unlock_ref(lock);2175return-1;2176}21772178unlock_ref(lock);2179return0;2180}21812182static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2183{2184int ret = -1;2185#ifndef NO_SYMLINK_HEAD2186char*ref_path =get_locked_file_path(lock->lk);2187unlink(ref_path);2188 ret =symlink(target, ref_path);2189free(ref_path);21902191if(ret)2192fprintf(stderr,"no symlink - falling back to symbolic ref\n");2193#endif2194return ret;2195}21962197static voidupdate_symref_reflog(struct files_ref_store *refs,2198struct ref_lock *lock,const char*refname,2199const char*target,const char*logmsg)2200{2201struct strbuf err = STRBUF_INIT;2202unsigned char new_sha1[20];2203if(logmsg &&2204!refs_read_ref_full(&refs->base, target,2205 RESOLVE_REF_READING, new_sha1, NULL) &&2206files_log_ref_write(refs, refname, lock->old_oid.hash,2207 new_sha1, logmsg,0, &err)) {2208error("%s", err.buf);2209strbuf_release(&err);2210}2211}22122213static intcreate_symref_locked(struct files_ref_store *refs,2214struct ref_lock *lock,const char*refname,2215const char*target,const char*logmsg)2216{2217if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2218update_symref_reflog(refs, lock, refname, target, logmsg);2219return0;2220}22212222if(!fdopen_lock_file(lock->lk,"w"))2223returnerror("unable to fdopen%s:%s",2224 lock->lk->tempfile.filename.buf,strerror(errno));22252226update_symref_reflog(refs, lock, refname, target, logmsg);22272228/* no error check; commit_ref will check ferror */2229fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2230if(commit_ref(lock) <0)2231returnerror("unable to write symref for%s:%s", refname,2232strerror(errno));2233return0;2234}22352236static intfiles_create_symref(struct ref_store *ref_store,2237const char*refname,const char*target,2238const char*logmsg)2239{2240struct files_ref_store *refs =2241files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2242struct strbuf err = STRBUF_INIT;2243struct ref_lock *lock;2244int ret;22452246 lock =lock_ref_sha1_basic(refs, refname, NULL,2247 NULL, NULL, REF_NODEREF, NULL,2248&err);2249if(!lock) {2250error("%s", err.buf);2251strbuf_release(&err);2252return-1;2253}22542255 ret =create_symref_locked(refs, lock, refname, target, logmsg);2256unlock_ref(lock);2257return ret;2258}22592260intset_worktree_head_symref(const char*gitdir,const char*target,const char*logmsg)2261{2262/*2263 * FIXME: this obviously will not work well for future refs2264 * backends. This function needs to die.2265 */2266struct files_ref_store *refs =2267files_downcast(get_main_ref_store(),2268 REF_STORE_WRITE,2269"set_head_symref");22702271static struct lock_file head_lock;2272struct ref_lock *lock;2273struct strbuf head_path = STRBUF_INIT;2274const char*head_rel;2275int ret;22762277strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2278if(hold_lock_file_for_update(&head_lock, head_path.buf,2279 LOCK_NO_DEREF) <0) {2280struct strbuf err = STRBUF_INIT;2281unable_to_lock_message(head_path.buf, errno, &err);2282error("%s", err.buf);2283strbuf_release(&err);2284strbuf_release(&head_path);2285return-1;2286}22872288/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2289 linked trees */2290 head_rel =remove_leading_path(head_path.buf,2291absolute_path(get_git_common_dir()));2292/* to make use of create_symref_locked(), initialize ref_lock */2293 lock =xcalloc(1,sizeof(struct ref_lock));2294 lock->lk = &head_lock;2295 lock->ref_name =xstrdup(head_rel);22962297 ret =create_symref_locked(refs, lock, head_rel, target, logmsg);22982299unlock_ref(lock);/* will free lock */2300strbuf_release(&head_path);2301return ret;2302}23032304static intfiles_reflog_exists(struct ref_store *ref_store,2305const char*refname)2306{2307struct files_ref_store *refs =2308files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2309struct strbuf sb = STRBUF_INIT;2310struct stat st;2311int ret;23122313files_reflog_path(refs, &sb, refname);2314 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2315strbuf_release(&sb);2316return ret;2317}23182319static intfiles_delete_reflog(struct ref_store *ref_store,2320const char*refname)2321{2322struct files_ref_store *refs =2323files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2324struct strbuf sb = STRBUF_INIT;2325int ret;23262327files_reflog_path(refs, &sb, refname);2328 ret =remove_path(sb.buf);2329strbuf_release(&sb);2330return ret;2331}23322333static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2334{2335struct object_id ooid, noid;2336char*email_end, *message;2337unsigned long timestamp;2338int tz;2339const char*p = sb->buf;23402341/* old SP new SP name <email> SP time TAB msg LF */2342if(!sb->len || sb->buf[sb->len -1] !='\n'||2343parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2344parse_oid_hex(p, &noid, &p) || *p++ !=' '||2345!(email_end =strchr(p,'>')) ||2346 email_end[1] !=' '||2347!(timestamp =strtoul(email_end +2, &message,10)) ||2348!message || message[0] !=' '||2349(message[1] !='+'&& message[1] !='-') ||2350!isdigit(message[2]) || !isdigit(message[3]) ||2351!isdigit(message[4]) || !isdigit(message[5]))2352return0;/* corrupt? */2353 email_end[1] ='\0';2354 tz =strtol(message +1, NULL,10);2355if(message[6] !='\t')2356 message +=6;2357else2358 message +=7;2359returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2360}23612362static char*find_beginning_of_line(char*bob,char*scan)2363{2364while(bob < scan && *(--scan) !='\n')2365;/* keep scanning backwards */2366/*2367 * Return either beginning of the buffer, or LF at the end of2368 * the previous line.2369 */2370return scan;2371}23722373static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2374const char*refname,2375 each_reflog_ent_fn fn,2376void*cb_data)2377{2378struct files_ref_store *refs =2379files_downcast(ref_store, REF_STORE_READ,2380"for_each_reflog_ent_reverse");2381struct strbuf sb = STRBUF_INIT;2382FILE*logfp;2383long pos;2384int ret =0, at_tail =1;23852386files_reflog_path(refs, &sb, refname);2387 logfp =fopen(sb.buf,"r");2388strbuf_release(&sb);2389if(!logfp)2390return-1;23912392/* Jump to the end */2393if(fseek(logfp,0, SEEK_END) <0)2394returnerror("cannot seek back reflog for%s:%s",2395 refname,strerror(errno));2396 pos =ftell(logfp);2397while(!ret &&0< pos) {2398int cnt;2399size_t nread;2400char buf[BUFSIZ];2401char*endp, *scanp;24022403/* Fill next block from the end */2404 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2405if(fseek(logfp, pos - cnt, SEEK_SET))2406returnerror("cannot seek back reflog for%s:%s",2407 refname,strerror(errno));2408 nread =fread(buf, cnt,1, logfp);2409if(nread !=1)2410returnerror("cannot read%dbytes from reflog for%s:%s",2411 cnt, refname,strerror(errno));2412 pos -= cnt;24132414 scanp = endp = buf + cnt;2415if(at_tail && scanp[-1] =='\n')2416/* Looking at the final LF at the end of the file */2417 scanp--;2418 at_tail =0;24192420while(buf < scanp) {2421/*2422 * terminating LF of the previous line, or the beginning2423 * of the buffer.2424 */2425char*bp;24262427 bp =find_beginning_of_line(buf, scanp);24282429if(*bp =='\n') {2430/*2431 * The newline is the end of the previous line,2432 * so we know we have complete line starting2433 * at (bp + 1). Prefix it onto any prior data2434 * we collected for the line and process it.2435 */2436strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2437 scanp = bp;2438 endp = bp +1;2439 ret =show_one_reflog_ent(&sb, fn, cb_data);2440strbuf_reset(&sb);2441if(ret)2442break;2443}else if(!pos) {2444/*2445 * We are at the start of the buffer, and the2446 * start of the file; there is no previous2447 * line, and we have everything for this one.2448 * Process it, and we can end the loop.2449 */2450strbuf_splice(&sb,0,0, buf, endp - buf);2451 ret =show_one_reflog_ent(&sb, fn, cb_data);2452strbuf_reset(&sb);2453break;2454}24552456if(bp == buf) {2457/*2458 * We are at the start of the buffer, and there2459 * is more file to read backwards. Which means2460 * we are in the middle of a line. Note that we2461 * may get here even if *bp was a newline; that2462 * just means we are at the exact end of the2463 * previous line, rather than some spot in the2464 * middle.2465 *2466 * Save away what we have to be combined with2467 * the data from the next read.2468 */2469strbuf_splice(&sb,0,0, buf, endp - buf);2470break;2471}2472}24732474}2475if(!ret && sb.len)2476die("BUG: reverse reflog parser had leftover data");24772478fclose(logfp);2479strbuf_release(&sb);2480return ret;2481}24822483static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2484const char*refname,2485 each_reflog_ent_fn fn,void*cb_data)2486{2487struct files_ref_store *refs =2488files_downcast(ref_store, REF_STORE_READ,2489"for_each_reflog_ent");2490FILE*logfp;2491struct strbuf sb = STRBUF_INIT;2492int ret =0;24932494files_reflog_path(refs, &sb, refname);2495 logfp =fopen(sb.buf,"r");2496strbuf_release(&sb);2497if(!logfp)2498return-1;24992500while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2501 ret =show_one_reflog_ent(&sb, fn, cb_data);2502fclose(logfp);2503strbuf_release(&sb);2504return ret;2505}25062507struct files_reflog_iterator {2508struct ref_iterator base;25092510struct ref_store *ref_store;2511struct dir_iterator *dir_iterator;2512struct object_id oid;2513};25142515static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2516{2517struct files_reflog_iterator *iter =2518(struct files_reflog_iterator *)ref_iterator;2519struct dir_iterator *diter = iter->dir_iterator;2520int ok;25212522while((ok =dir_iterator_advance(diter)) == ITER_OK) {2523int flags;25242525if(!S_ISREG(diter->st.st_mode))2526continue;2527if(diter->basename[0] =='.')2528continue;2529if(ends_with(diter->basename,".lock"))2530continue;25312532if(refs_read_ref_full(iter->ref_store,2533 diter->relative_path,0,2534 iter->oid.hash, &flags)) {2535error("bad ref for%s", diter->path.buf);2536continue;2537}25382539 iter->base.refname = diter->relative_path;2540 iter->base.oid = &iter->oid;2541 iter->base.flags = flags;2542return ITER_OK;2543}25442545 iter->dir_iterator = NULL;2546if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2547 ok = ITER_ERROR;2548return ok;2549}25502551static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2552struct object_id *peeled)2553{2554die("BUG: ref_iterator_peel() called for reflog_iterator");2555}25562557static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2558{2559struct files_reflog_iterator *iter =2560(struct files_reflog_iterator *)ref_iterator;2561int ok = ITER_DONE;25622563if(iter->dir_iterator)2564 ok =dir_iterator_abort(iter->dir_iterator);25652566base_ref_iterator_free(ref_iterator);2567return ok;2568}25692570static struct ref_iterator_vtable files_reflog_iterator_vtable = {2571 files_reflog_iterator_advance,2572 files_reflog_iterator_peel,2573 files_reflog_iterator_abort2574};25752576static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2577{2578struct files_ref_store *refs =2579files_downcast(ref_store, REF_STORE_READ,2580"reflog_iterator_begin");2581struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2582struct ref_iterator *ref_iterator = &iter->base;2583struct strbuf sb = STRBUF_INIT;25842585base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2586files_reflog_path(refs, &sb, NULL);2587 iter->dir_iterator =dir_iterator_begin(sb.buf);2588 iter->ref_store = ref_store;2589strbuf_release(&sb);2590return ref_iterator;2591}25922593static intref_update_reject_duplicates(struct string_list *refnames,2594struct strbuf *err)2595{2596int i, n = refnames->nr;25972598assert(err);25992600for(i =1; i < n; i++)2601if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2602strbuf_addf(err,2603"multiple updates for ref '%s' not allowed.",2604 refnames->items[i].string);2605return1;2606}2607return0;2608}26092610/*2611 * If update is a direct update of head_ref (the reference pointed to2612 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2613 */2614static intsplit_head_update(struct ref_update *update,2615struct ref_transaction *transaction,2616const char*head_ref,2617struct string_list *affected_refnames,2618struct strbuf *err)2619{2620struct string_list_item *item;2621struct ref_update *new_update;26222623if((update->flags & REF_LOG_ONLY) ||2624(update->flags & REF_ISPRUNING) ||2625(update->flags & REF_UPDATE_VIA_HEAD))2626return0;26272628if(strcmp(update->refname, head_ref))2629return0;26302631/*2632 * First make sure that HEAD is not already in the2633 * transaction. This insertion is O(N) in the transaction2634 * size, but it happens at most once per transaction.2635 */2636 item =string_list_insert(affected_refnames,"HEAD");2637if(item->util) {2638/* An entry already existed */2639strbuf_addf(err,2640"multiple updates for 'HEAD' (including one "2641"via its referent '%s') are not allowed",2642 update->refname);2643return TRANSACTION_NAME_CONFLICT;2644}26452646 new_update =ref_transaction_add_update(2647 transaction,"HEAD",2648 update->flags | REF_LOG_ONLY | REF_NODEREF,2649 update->new_sha1, update->old_sha1,2650 update->msg);26512652 item->util = new_update;26532654return0;2655}26562657/*2658 * update is for a symref that points at referent and doesn't have2659 * REF_NODEREF set. Split it into two updates:2660 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2661 * - A new, separate update for the referent reference2662 * Note that the new update will itself be subject to splitting when2663 * the iteration gets to it.2664 */2665static intsplit_symref_update(struct files_ref_store *refs,2666struct ref_update *update,2667const char*referent,2668struct ref_transaction *transaction,2669struct string_list *affected_refnames,2670struct strbuf *err)2671{2672struct string_list_item *item;2673struct ref_update *new_update;2674unsigned int new_flags;26752676/*2677 * First make sure that referent is not already in the2678 * transaction. This insertion is O(N) in the transaction2679 * size, but it happens at most once per symref in a2680 * transaction.2681 */2682 item =string_list_insert(affected_refnames, referent);2683if(item->util) {2684/* An entry already existed */2685strbuf_addf(err,2686"multiple updates for '%s' (including one "2687"via symref '%s') are not allowed",2688 referent, update->refname);2689return TRANSACTION_NAME_CONFLICT;2690}26912692 new_flags = update->flags;2693if(!strcmp(update->refname,"HEAD")) {2694/*2695 * Record that the new update came via HEAD, so that2696 * when we process it, split_head_update() doesn't try2697 * to add another reflog update for HEAD. Note that2698 * this bit will be propagated if the new_update2699 * itself needs to be split.2700 */2701 new_flags |= REF_UPDATE_VIA_HEAD;2702}27032704 new_update =ref_transaction_add_update(2705 transaction, referent, new_flags,2706 update->new_sha1, update->old_sha1,2707 update->msg);27082709 new_update->parent_update = update;27102711/*2712 * Change the symbolic ref update to log only. Also, it2713 * doesn't need to check its old SHA-1 value, as that will be2714 * done when new_update is processed.2715 */2716 update->flags |= REF_LOG_ONLY | REF_NODEREF;2717 update->flags &= ~REF_HAVE_OLD;27182719 item->util = new_update;27202721return0;2722}27232724/*2725 * Return the refname under which update was originally requested.2726 */2727static const char*original_update_refname(struct ref_update *update)2728{2729while(update->parent_update)2730 update = update->parent_update;27312732return update->refname;2733}27342735/*2736 * Check whether the REF_HAVE_OLD and old_oid values stored in update2737 * are consistent with oid, which is the reference's current value. If2738 * everything is OK, return 0; otherwise, write an error message to2739 * err and return -1.2740 */2741static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2742struct strbuf *err)2743{2744if(!(update->flags & REF_HAVE_OLD) ||2745!hashcmp(oid->hash, update->old_sha1))2746return0;27472748if(is_null_sha1(update->old_sha1))2749strbuf_addf(err,"cannot lock ref '%s': "2750"reference already exists",2751original_update_refname(update));2752else if(is_null_oid(oid))2753strbuf_addf(err,"cannot lock ref '%s': "2754"reference is missing but expected%s",2755original_update_refname(update),2756sha1_to_hex(update->old_sha1));2757else2758strbuf_addf(err,"cannot lock ref '%s': "2759"is at%sbut expected%s",2760original_update_refname(update),2761oid_to_hex(oid),2762sha1_to_hex(update->old_sha1));27632764return-1;2765}27662767/*2768 * Prepare for carrying out update:2769 * - Lock the reference referred to by update.2770 * - Read the reference under lock.2771 * - Check that its old SHA-1 value (if specified) is correct, and in2772 * any case record it in update->lock->old_oid for later use when2773 * writing the reflog.2774 * - If it is a symref update without REF_NODEREF, split it up into a2775 * REF_LOG_ONLY update of the symref and add a separate update for2776 * the referent to transaction.2777 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2778 * update of HEAD.2779 */2780static intlock_ref_for_update(struct files_ref_store *refs,2781struct ref_update *update,2782struct ref_transaction *transaction,2783const char*head_ref,2784struct string_list *affected_refnames,2785struct strbuf *err)2786{2787struct strbuf referent = STRBUF_INIT;2788int mustexist = (update->flags & REF_HAVE_OLD) &&2789!is_null_sha1(update->old_sha1);2790int ret;2791struct ref_lock *lock;27922793files_assert_main_repository(refs,"lock_ref_for_update");27942795if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))2796 update->flags |= REF_DELETING;27972798if(head_ref) {2799 ret =split_head_update(update, transaction, head_ref,2800 affected_refnames, err);2801if(ret)2802return ret;2803}28042805 ret =lock_raw_ref(refs, update->refname, mustexist,2806 affected_refnames, NULL,2807&lock, &referent,2808&update->type, err);2809if(ret) {2810char*reason;28112812 reason =strbuf_detach(err, NULL);2813strbuf_addf(err,"cannot lock ref '%s':%s",2814original_update_refname(update), reason);2815free(reason);2816return ret;2817}28182819 update->backend_data = lock;28202821if(update->type & REF_ISSYMREF) {2822if(update->flags & REF_NODEREF) {2823/*2824 * We won't be reading the referent as part of2825 * the transaction, so we have to read it here2826 * to record and possibly check old_sha1:2827 */2828if(refs_read_ref_full(&refs->base,2829 referent.buf,0,2830 lock->old_oid.hash, NULL)) {2831if(update->flags & REF_HAVE_OLD) {2832strbuf_addf(err,"cannot lock ref '%s': "2833"error reading reference",2834original_update_refname(update));2835return-1;2836}2837}else if(check_old_oid(update, &lock->old_oid, err)) {2838return TRANSACTION_GENERIC_ERROR;2839}2840}else{2841/*2842 * Create a new update for the reference this2843 * symref is pointing at. Also, we will record2844 * and verify old_sha1 for this update as part2845 * of processing the split-off update, so we2846 * don't have to do it here.2847 */2848 ret =split_symref_update(refs, update,2849 referent.buf, transaction,2850 affected_refnames, err);2851if(ret)2852return ret;2853}2854}else{2855struct ref_update *parent_update;28562857if(check_old_oid(update, &lock->old_oid, err))2858return TRANSACTION_GENERIC_ERROR;28592860/*2861 * If this update is happening indirectly because of a2862 * symref update, record the old SHA-1 in the parent2863 * update:2864 */2865for(parent_update = update->parent_update;2866 parent_update;2867 parent_update = parent_update->parent_update) {2868struct ref_lock *parent_lock = parent_update->backend_data;2869oidcpy(&parent_lock->old_oid, &lock->old_oid);2870}2871}28722873if((update->flags & REF_HAVE_NEW) &&2874!(update->flags & REF_DELETING) &&2875!(update->flags & REF_LOG_ONLY)) {2876if(!(update->type & REF_ISSYMREF) &&2877!hashcmp(lock->old_oid.hash, update->new_sha1)) {2878/*2879 * The reference already has the desired2880 * value, so we don't need to write it.2881 */2882}else if(write_ref_to_lockfile(lock, update->new_sha1,2883 err)) {2884char*write_err =strbuf_detach(err, NULL);28852886/*2887 * The lock was freed upon failure of2888 * write_ref_to_lockfile():2889 */2890 update->backend_data = NULL;2891strbuf_addf(err,2892"cannot update ref '%s':%s",2893 update->refname, write_err);2894free(write_err);2895return TRANSACTION_GENERIC_ERROR;2896}else{2897 update->flags |= REF_NEEDS_COMMIT;2898}2899}2900if(!(update->flags & REF_NEEDS_COMMIT)) {2901/*2902 * We didn't call write_ref_to_lockfile(), so2903 * the lockfile is still open. Close it to2904 * free up the file descriptor:2905 */2906if(close_ref(lock)) {2907strbuf_addf(err,"couldn't close '%s.lock'",2908 update->refname);2909return TRANSACTION_GENERIC_ERROR;2910}2911}2912return0;2913}29142915static intfiles_transaction_commit(struct ref_store *ref_store,2916struct ref_transaction *transaction,2917struct strbuf *err)2918{2919struct files_ref_store *refs =2920files_downcast(ref_store, REF_STORE_WRITE,2921"ref_transaction_commit");2922int ret =0, i;2923struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2924struct string_list_item *ref_to_delete;2925struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2926char*head_ref = NULL;2927int head_type;2928struct object_id head_oid;2929struct strbuf sb = STRBUF_INIT;29302931assert(err);29322933if(transaction->state != REF_TRANSACTION_OPEN)2934die("BUG: commit called for transaction that is not open");29352936if(!transaction->nr) {2937 transaction->state = REF_TRANSACTION_CLOSED;2938return0;2939}29402941/*2942 * Fail if a refname appears more than once in the2943 * transaction. (If we end up splitting up any updates using2944 * split_symref_update() or split_head_update(), those2945 * functions will check that the new updates don't have the2946 * same refname as any existing ones.)2947 */2948for(i =0; i < transaction->nr; i++) {2949struct ref_update *update = transaction->updates[i];2950struct string_list_item *item =2951string_list_append(&affected_refnames, update->refname);29522953/*2954 * We store a pointer to update in item->util, but at2955 * the moment we never use the value of this field2956 * except to check whether it is non-NULL.2957 */2958 item->util = update;2959}2960string_list_sort(&affected_refnames);2961if(ref_update_reject_duplicates(&affected_refnames, err)) {2962 ret = TRANSACTION_GENERIC_ERROR;2963goto cleanup;2964}29652966/*2967 * Special hack: If a branch is updated directly and HEAD2968 * points to it (may happen on the remote side of a push2969 * for example) then logically the HEAD reflog should be2970 * updated too.2971 *2972 * A generic solution would require reverse symref lookups,2973 * but finding all symrefs pointing to a given branch would be2974 * rather costly for this rare event (the direct update of a2975 * branch) to be worth it. So let's cheat and check with HEAD2976 * only, which should cover 99% of all usage scenarios (even2977 * 100% of the default ones).2978 *2979 * So if HEAD is a symbolic reference, then record the name of2980 * the reference that it points to. If we see an update of2981 * head_ref within the transaction, then split_head_update()2982 * arranges for the reflog of HEAD to be updated, too.2983 */2984 head_ref =refs_resolve_refdup(ref_store,"HEAD",2985 RESOLVE_REF_NO_RECURSE,2986 head_oid.hash, &head_type);29872988if(head_ref && !(head_type & REF_ISSYMREF)) {2989free(head_ref);2990 head_ref = NULL;2991}29922993/*2994 * Acquire all locks, verify old values if provided, check2995 * that new values are valid, and write new values to the2996 * lockfiles, ready to be activated. Only keep one lockfile2997 * open at a time to avoid running out of file descriptors.2998 */2999for(i =0; i < transaction->nr; i++) {3000struct ref_update *update = transaction->updates[i];30013002 ret =lock_ref_for_update(refs, update, transaction,3003 head_ref, &affected_refnames, err);3004if(ret)3005goto cleanup;3006}30073008/* Perform updates first so live commits remain referenced */3009for(i =0; i < transaction->nr; i++) {3010struct ref_update *update = transaction->updates[i];3011struct ref_lock *lock = update->backend_data;30123013if(update->flags & REF_NEEDS_COMMIT ||3014 update->flags & REF_LOG_ONLY) {3015if(files_log_ref_write(refs,3016 lock->ref_name,3017 lock->old_oid.hash,3018 update->new_sha1,3019 update->msg, update->flags,3020 err)) {3021char*old_msg =strbuf_detach(err, NULL);30223023strbuf_addf(err,"cannot update the ref '%s':%s",3024 lock->ref_name, old_msg);3025free(old_msg);3026unlock_ref(lock);3027 update->backend_data = NULL;3028 ret = TRANSACTION_GENERIC_ERROR;3029goto cleanup;3030}3031}3032if(update->flags & REF_NEEDS_COMMIT) {3033clear_loose_ref_cache(refs);3034if(commit_ref(lock)) {3035strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3036unlock_ref(lock);3037 update->backend_data = NULL;3038 ret = TRANSACTION_GENERIC_ERROR;3039goto cleanup;3040}3041}3042}3043/* Perform deletes now that updates are safely completed */3044for(i =0; i < transaction->nr; i++) {3045struct ref_update *update = transaction->updates[i];3046struct ref_lock *lock = update->backend_data;30473048if(update->flags & REF_DELETING &&3049!(update->flags & REF_LOG_ONLY)) {3050if(!(update->type & REF_ISPACKED) ||3051 update->type & REF_ISSYMREF) {3052/* It is a loose reference. */3053strbuf_reset(&sb);3054files_ref_path(refs, &sb, lock->ref_name);3055if(unlink_or_msg(sb.buf, err)) {3056 ret = TRANSACTION_GENERIC_ERROR;3057goto cleanup;3058}3059 update->flags |= REF_DELETED_LOOSE;3060}30613062if(!(update->flags & REF_ISPRUNING))3063string_list_append(&refs_to_delete,3064 lock->ref_name);3065}3066}30673068if(repack_without_refs(refs, &refs_to_delete, err)) {3069 ret = TRANSACTION_GENERIC_ERROR;3070goto cleanup;3071}30723073/* Delete the reflogs of any references that were deleted: */3074for_each_string_list_item(ref_to_delete, &refs_to_delete) {3075strbuf_reset(&sb);3076files_reflog_path(refs, &sb, ref_to_delete->string);3077if(!unlink_or_warn(sb.buf))3078try_remove_empty_parents(refs, ref_to_delete->string,3079 REMOVE_EMPTY_PARENTS_REFLOG);3080}30813082clear_loose_ref_cache(refs);30833084cleanup:3085strbuf_release(&sb);3086 transaction->state = REF_TRANSACTION_CLOSED;30873088for(i =0; i < transaction->nr; i++) {3089struct ref_update *update = transaction->updates[i];3090struct ref_lock *lock = update->backend_data;30913092if(lock)3093unlock_ref(lock);30943095if(update->flags & REF_DELETED_LOOSE) {3096/*3097 * The loose reference was deleted. Delete any3098 * empty parent directories. (Note that this3099 * can only work because we have already3100 * removed the lockfile.)3101 */3102try_remove_empty_parents(refs, update->refname,3103 REMOVE_EMPTY_PARENTS_REF);3104}3105}31063107string_list_clear(&refs_to_delete,0);3108free(head_ref);3109string_list_clear(&affected_refnames,0);31103111return ret;3112}31133114static intref_present(const char*refname,3115const struct object_id *oid,int flags,void*cb_data)3116{3117struct string_list *affected_refnames = cb_data;31183119returnstring_list_has_string(affected_refnames, refname);3120}31213122static intfiles_initial_transaction_commit(struct ref_store *ref_store,3123struct ref_transaction *transaction,3124struct strbuf *err)3125{3126struct files_ref_store *refs =3127files_downcast(ref_store, REF_STORE_WRITE,3128"initial_ref_transaction_commit");3129int ret =0, i;3130struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31313132assert(err);31333134if(transaction->state != REF_TRANSACTION_OPEN)3135die("BUG: commit called for transaction that is not open");31363137/* Fail if a refname appears more than once in the transaction: */3138for(i =0; i < transaction->nr; i++)3139string_list_append(&affected_refnames,3140 transaction->updates[i]->refname);3141string_list_sort(&affected_refnames);3142if(ref_update_reject_duplicates(&affected_refnames, err)) {3143 ret = TRANSACTION_GENERIC_ERROR;3144goto cleanup;3145}31463147/*3148 * It's really undefined to call this function in an active3149 * repository or when there are existing references: we are3150 * only locking and changing packed-refs, so (1) any3151 * simultaneous processes might try to change a reference at3152 * the same time we do, and (2) any existing loose versions of3153 * the references that we are setting would have precedence3154 * over our values. But some remote helpers create the remote3155 * "HEAD" and "master" branches before calling this function,3156 * so here we really only check that none of the references3157 * that we are creating already exists.3158 */3159if(refs_for_each_rawref(&refs->base, ref_present,3160&affected_refnames))3161die("BUG: initial ref transaction called with existing refs");31623163for(i =0; i < transaction->nr; i++) {3164struct ref_update *update = transaction->updates[i];31653166if((update->flags & REF_HAVE_OLD) &&3167!is_null_sha1(update->old_sha1))3168die("BUG: initial ref transaction with old_sha1 set");3169if(refs_verify_refname_available(&refs->base, update->refname,3170&affected_refnames, NULL,3171 err)) {3172 ret = TRANSACTION_NAME_CONFLICT;3173goto cleanup;3174}3175}31763177if(lock_packed_refs(refs,0)) {3178strbuf_addf(err,"unable to lock packed-refs file:%s",3179strerror(errno));3180 ret = TRANSACTION_GENERIC_ERROR;3181goto cleanup;3182}31833184for(i =0; i < transaction->nr; i++) {3185struct ref_update *update = transaction->updates[i];31863187if((update->flags & REF_HAVE_NEW) &&3188!is_null_sha1(update->new_sha1))3189add_packed_ref(refs, update->refname, update->new_sha1);3190}31913192if(commit_packed_refs(refs)) {3193strbuf_addf(err,"unable to commit packed-refs file:%s",3194strerror(errno));3195 ret = TRANSACTION_GENERIC_ERROR;3196goto cleanup;3197}31983199cleanup:3200 transaction->state = REF_TRANSACTION_CLOSED;3201string_list_clear(&affected_refnames,0);3202return ret;3203}32043205struct expire_reflog_cb {3206unsigned int flags;3207 reflog_expiry_should_prune_fn *should_prune_fn;3208void*policy_cb;3209FILE*newlog;3210struct object_id last_kept_oid;3211};32123213static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3214const char*email,unsigned long timestamp,int tz,3215const char*message,void*cb_data)3216{3217struct expire_reflog_cb *cb = cb_data;3218struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32193220if(cb->flags & EXPIRE_REFLOGS_REWRITE)3221 ooid = &cb->last_kept_oid;32223223if((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,3224 message, policy_cb)) {3225if(!cb->newlog)3226printf("would prune%s", message);3227else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3228printf("prune%s", message);3229}else{3230if(cb->newlog) {3231fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3232oid_to_hex(ooid),oid_to_hex(noid),3233 email, timestamp, tz, message);3234oidcpy(&cb->last_kept_oid, noid);3235}3236if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3237printf("keep%s", message);3238}3239return0;3240}32413242static intfiles_reflog_expire(struct ref_store *ref_store,3243const char*refname,const unsigned char*sha1,3244unsigned int flags,3245 reflog_expiry_prepare_fn prepare_fn,3246 reflog_expiry_should_prune_fn should_prune_fn,3247 reflog_expiry_cleanup_fn cleanup_fn,3248void*policy_cb_data)3249{3250struct files_ref_store *refs =3251files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3252static struct lock_file reflog_lock;3253struct expire_reflog_cb cb;3254struct ref_lock *lock;3255struct strbuf log_file_sb = STRBUF_INIT;3256char*log_file;3257int status =0;3258int type;3259struct strbuf err = STRBUF_INIT;32603261memset(&cb,0,sizeof(cb));3262 cb.flags = flags;3263 cb.policy_cb = policy_cb_data;3264 cb.should_prune_fn = should_prune_fn;32653266/*3267 * The reflog file is locked by holding the lock on the3268 * reference itself, plus we might need to update the3269 * reference if --updateref was specified:3270 */3271 lock =lock_ref_sha1_basic(refs, refname, sha1,3272 NULL, NULL, REF_NODEREF,3273&type, &err);3274if(!lock) {3275error("cannot lock ref '%s':%s", refname, err.buf);3276strbuf_release(&err);3277return-1;3278}3279if(!refs_reflog_exists(ref_store, refname)) {3280unlock_ref(lock);3281return0;3282}32833284files_reflog_path(refs, &log_file_sb, refname);3285 log_file =strbuf_detach(&log_file_sb, NULL);3286if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3287/*3288 * Even though holding $GIT_DIR/logs/$reflog.lock has3289 * no locking implications, we use the lock_file3290 * machinery here anyway because it does a lot of the3291 * work we need, including cleaning up if the program3292 * exits unexpectedly.3293 */3294if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3295struct strbuf err = STRBUF_INIT;3296unable_to_lock_message(log_file, errno, &err);3297error("%s", err.buf);3298strbuf_release(&err);3299goto failure;3300}3301 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3302if(!cb.newlog) {3303error("cannot fdopen%s(%s)",3304get_lock_file_path(&reflog_lock),strerror(errno));3305goto failure;3306}3307}33083309(*prepare_fn)(refname, sha1, cb.policy_cb);3310refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3311(*cleanup_fn)(cb.policy_cb);33123313if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3314/*3315 * It doesn't make sense to adjust a reference pointed3316 * to by a symbolic ref based on expiring entries in3317 * the symbolic reference's reflog. Nor can we update3318 * a reference if there are no remaining reflog3319 * entries.3320 */3321int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3322!(type & REF_ISSYMREF) &&3323!is_null_oid(&cb.last_kept_oid);33243325if(close_lock_file(&reflog_lock)) {3326 status |=error("couldn't write%s:%s", log_file,3327strerror(errno));3328}else if(update &&3329(write_in_full(get_lock_file_fd(lock->lk),3330oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3331write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3332close_ref(lock) <0)) {3333 status |=error("couldn't write%s",3334get_lock_file_path(lock->lk));3335rollback_lock_file(&reflog_lock);3336}else if(commit_lock_file(&reflog_lock)) {3337 status |=error("unable to write reflog '%s' (%s)",3338 log_file,strerror(errno));3339}else if(update &&commit_ref(lock)) {3340 status |=error("couldn't set%s", lock->ref_name);3341}3342}3343free(log_file);3344unlock_ref(lock);3345return status;33463347 failure:3348rollback_lock_file(&reflog_lock);3349free(log_file);3350unlock_ref(lock);3351return-1;3352}33533354static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3355{3356struct files_ref_store *refs =3357files_downcast(ref_store, REF_STORE_WRITE,"init_db");3358struct strbuf sb = STRBUF_INIT;33593360/*3361 * Create .git/refs/{heads,tags}3362 */3363files_ref_path(refs, &sb,"refs/heads");3364safe_create_dir(sb.buf,1);33653366strbuf_reset(&sb);3367files_ref_path(refs, &sb,"refs/tags");3368safe_create_dir(sb.buf,1);33693370strbuf_release(&sb);3371return0;3372}33733374struct ref_storage_be refs_be_files = {3375 NULL,3376"files",3377 files_ref_store_create,3378 files_init_db,3379 files_transaction_commit,3380 files_initial_transaction_commit,33813382 files_pack_refs,3383 files_peel_ref,3384 files_create_symref,3385 files_delete_refs,3386 files_rename_ref,33873388 files_ref_iterator_begin,3389 files_read_raw_ref,33903391 files_reflog_iterator_begin,3392 files_for_each_reflog_ent,3393 files_for_each_reflog_ent_reverse,3394 files_reflog_exists,3395 files_create_reflog,3396 files_delete_reflog,3397 files_reflog_expire3398};