1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* 47 * Iff the packed-refs file associated with this instance is 48 * currently locked for writing, this points at the associated 49 * lock (which is owned by somebody else). The referrer count 50 * is also incremented when the file is locked and decremented 51 * when it is unlocked. 52 */ 53struct lock_file *lock; 54 55/* The metadata from when this packed-refs cache was read */ 56struct stat_validity validity; 57}; 58 59/* 60 * Future: need to be in "struct repository" 61 * when doing a full libification. 62 */ 63struct files_ref_store { 64struct ref_store base; 65unsigned int store_flags; 66 67char*gitdir; 68char*gitcommondir; 69char*packed_refs_path; 70 71struct ref_cache *loose; 72struct packed_ref_cache *packed; 73}; 74 75/* Lock used for the main packed-refs file: */ 76static struct lock_file packlock; 77 78/* 79 * Increment the reference count of *packed_refs. 80 */ 81static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 82{ 83 packed_refs->referrers++; 84} 85 86/* 87 * Decrease the reference count of *packed_refs. If it goes to zero, 88 * free *packed_refs and return true; otherwise return false. 89 */ 90static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 91{ 92if(!--packed_refs->referrers) { 93free_ref_cache(packed_refs->cache); 94stat_validity_clear(&packed_refs->validity); 95free(packed_refs); 96return1; 97}else{ 98return0; 99} 100} 101 102static voidclear_packed_ref_cache(struct files_ref_store *refs) 103{ 104if(refs->packed) { 105struct packed_ref_cache *packed_refs = refs->packed; 106 107if(packed_refs->lock) 108die("internal error: packed-ref cache cleared while locked"); 109 refs->packed = NULL; 110release_packed_ref_cache(packed_refs); 111} 112} 113 114static voidclear_loose_ref_cache(struct files_ref_store *refs) 115{ 116if(refs->loose) { 117free_ref_cache(refs->loose); 118 refs->loose = NULL; 119} 120} 121 122/* 123 * Create a new submodule ref cache and add it to the internal 124 * set of caches. 125 */ 126static struct ref_store *files_ref_store_create(const char*gitdir, 127unsigned int flags) 128{ 129struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 130struct ref_store *ref_store = (struct ref_store *)refs; 131struct strbuf sb = STRBUF_INIT; 132 133base_ref_store_init(ref_store, &refs_be_files); 134 refs->store_flags = flags; 135 136 refs->gitdir =xstrdup(gitdir); 137get_common_dir_noenv(&sb, gitdir); 138 refs->gitcommondir =strbuf_detach(&sb, NULL); 139strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 140 refs->packed_refs_path =strbuf_detach(&sb, NULL); 141 142return ref_store; 143} 144 145/* 146 * Die if refs is not the main ref store. caller is used in any 147 * necessary error messages. 148 */ 149static voidfiles_assert_main_repository(struct files_ref_store *refs, 150const char*caller) 151{ 152if(refs->store_flags & REF_STORE_MAIN) 153return; 154 155die("BUG: operation%sonly allowed for main ref store", caller); 156} 157 158/* 159 * Downcast ref_store to files_ref_store. Die if ref_store is not a 160 * files_ref_store. required_flags is compared with ref_store's 161 * store_flags to ensure the ref_store has all required capabilities. 162 * "caller" is used in any necessary error messages. 163 */ 164static struct files_ref_store *files_downcast(struct ref_store *ref_store, 165unsigned int required_flags, 166const char*caller) 167{ 168struct files_ref_store *refs; 169 170if(ref_store->be != &refs_be_files) 171die("BUG: ref_store is type\"%s\"not\"files\"in%s", 172 ref_store->be->name, caller); 173 174 refs = (struct files_ref_store *)ref_store; 175 176if((refs->store_flags & required_flags) != required_flags) 177die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 178 caller, required_flags, refs->store_flags); 179 180return refs; 181} 182 183/* The length of a peeled reference line in packed-refs, including EOL: */ 184#define PEELED_LINE_LENGTH 42 185 186/* 187 * The packed-refs header line that we write out. Perhaps other 188 * traits will be added later. The trailing space is required. 189 */ 190static const char PACKED_REFS_HEADER[] = 191"# pack-refs with: peeled fully-peeled\n"; 192 193/* 194 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 195 * Return a pointer to the refname within the line (null-terminated), 196 * or NULL if there was a problem. 197 */ 198static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 199{ 200const char*ref; 201 202/* 203 * 42: the answer to everything. 204 * 205 * In this case, it happens to be the answer to 206 * 40 (length of sha1 hex representation) 207 * +1 (space in between hex and name) 208 * +1 (newline at the end of the line) 209 */ 210if(line->len <=42) 211return NULL; 212 213if(get_sha1_hex(line->buf, sha1) <0) 214return NULL; 215if(!isspace(line->buf[40])) 216return NULL; 217 218 ref = line->buf +41; 219if(isspace(*ref)) 220return NULL; 221 222if(line->buf[line->len -1] !='\n') 223return NULL; 224 line->buf[--line->len] =0; 225 226return ref; 227} 228 229/* 230 * Read f, which is a packed-refs file, into dir. 231 * 232 * A comment line of the form "# pack-refs with: " may contain zero or 233 * more traits. We interpret the traits as follows: 234 * 235 * No traits: 236 * 237 * Probably no references are peeled. But if the file contains a 238 * peeled value for a reference, we will use it. 239 * 240 * peeled: 241 * 242 * References under "refs/tags/", if they *can* be peeled, *are* 243 * peeled in this file. References outside of "refs/tags/" are 244 * probably not peeled even if they could have been, but if we find 245 * a peeled value for such a reference we will use it. 246 * 247 * fully-peeled: 248 * 249 * All references in the file that can be peeled are peeled. 250 * Inversely (and this is more important), any references in the 251 * file for which no peeled value is recorded is not peelable. This 252 * trait should typically be written alongside "peeled" for 253 * compatibility with older clients, but we do not require it 254 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 255 */ 256static voidread_packed_refs(FILE*f,struct ref_dir *dir) 257{ 258struct ref_entry *last = NULL; 259struct strbuf line = STRBUF_INIT; 260enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 261 262while(strbuf_getwholeline(&line, f,'\n') != EOF) { 263unsigned char sha1[20]; 264const char*refname; 265const char*traits; 266 267if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 268if(strstr(traits," fully-peeled ")) 269 peeled = PEELED_FULLY; 270else if(strstr(traits," peeled ")) 271 peeled = PEELED_TAGS; 272/* perhaps other traits later as well */ 273continue; 274} 275 276 refname =parse_ref_line(&line, sha1); 277if(refname) { 278int flag = REF_ISPACKED; 279 280if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 281if(!refname_is_safe(refname)) 282die("packed refname is dangerous:%s", refname); 283hashclr(sha1); 284 flag |= REF_BAD_NAME | REF_ISBROKEN; 285} 286 last =create_ref_entry(refname, sha1, flag,0); 287if(peeled == PEELED_FULLY || 288(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 289 last->flag |= REF_KNOWS_PEELED; 290add_ref_entry(dir, last); 291continue; 292} 293if(last && 294 line.buf[0] =='^'&& 295 line.len == PEELED_LINE_LENGTH && 296 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 297!get_sha1_hex(line.buf +1, sha1)) { 298hashcpy(last->u.value.peeled.hash, sha1); 299/* 300 * Regardless of what the file header said, 301 * we definitely know the value of *this* 302 * reference: 303 */ 304 last->flag |= REF_KNOWS_PEELED; 305} 306} 307 308strbuf_release(&line); 309} 310 311static const char*files_packed_refs_path(struct files_ref_store *refs) 312{ 313return refs->packed_refs_path; 314} 315 316static voidfiles_reflog_path(struct files_ref_store *refs, 317struct strbuf *sb, 318const char*refname) 319{ 320if(!refname) { 321/* 322 * FIXME: of course this is wrong in multi worktree 323 * setting. To be fixed real soon. 324 */ 325strbuf_addf(sb,"%s/logs", refs->gitcommondir); 326return; 327} 328 329switch(ref_type(refname)) { 330case REF_TYPE_PER_WORKTREE: 331case REF_TYPE_PSEUDOREF: 332strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 333break; 334case REF_TYPE_NORMAL: 335strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 336break; 337default: 338die("BUG: unknown ref type%dof ref%s", 339ref_type(refname), refname); 340} 341} 342 343static voidfiles_ref_path(struct files_ref_store *refs, 344struct strbuf *sb, 345const char*refname) 346{ 347switch(ref_type(refname)) { 348case REF_TYPE_PER_WORKTREE: 349case REF_TYPE_PSEUDOREF: 350strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 351break; 352case REF_TYPE_NORMAL: 353strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 354break; 355default: 356die("BUG: unknown ref type%dof ref%s", 357ref_type(refname), refname); 358} 359} 360 361/* 362 * Get the packed_ref_cache for the specified files_ref_store, 363 * creating it if necessary. 364 */ 365static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 366{ 367const char*packed_refs_file =files_packed_refs_path(refs); 368 369if(refs->packed && 370!stat_validity_check(&refs->packed->validity, packed_refs_file)) 371clear_packed_ref_cache(refs); 372 373if(!refs->packed) { 374FILE*f; 375 376 refs->packed =xcalloc(1,sizeof(*refs->packed)); 377acquire_packed_ref_cache(refs->packed); 378 refs->packed->cache =create_ref_cache(&refs->base, NULL); 379 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 380 f =fopen(packed_refs_file,"r"); 381if(f) { 382stat_validity_update(&refs->packed->validity,fileno(f)); 383read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 384fclose(f); 385} 386} 387return refs->packed; 388} 389 390static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 391{ 392returnget_ref_dir(packed_ref_cache->cache->root); 393} 394 395static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 396{ 397returnget_packed_ref_dir(get_packed_ref_cache(refs)); 398} 399 400/* 401 * Add a reference to the in-memory packed reference cache. This may 402 * only be called while the packed-refs file is locked (see 403 * lock_packed_refs()). To actually write the packed-refs file, call 404 * commit_packed_refs(). 405 */ 406static voidadd_packed_ref(struct files_ref_store *refs, 407const char*refname,const unsigned char*sha1) 408{ 409struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 410 411if(!packed_ref_cache->lock) 412die("internal error: packed refs not locked"); 413add_ref_entry(get_packed_ref_dir(packed_ref_cache), 414create_ref_entry(refname, sha1, REF_ISPACKED,1)); 415} 416 417/* 418 * Read the loose references from the namespace dirname into dir 419 * (without recursing). dirname must end with '/'. dir must be the 420 * directory entry corresponding to dirname. 421 */ 422static voidloose_fill_ref_dir(struct ref_store *ref_store, 423struct ref_dir *dir,const char*dirname) 424{ 425struct files_ref_store *refs = 426files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 427DIR*d; 428struct dirent *de; 429int dirnamelen =strlen(dirname); 430struct strbuf refname; 431struct strbuf path = STRBUF_INIT; 432size_t path_baselen; 433 434files_ref_path(refs, &path, dirname); 435 path_baselen = path.len; 436 437 d =opendir(path.buf); 438if(!d) { 439strbuf_release(&path); 440return; 441} 442 443strbuf_init(&refname, dirnamelen +257); 444strbuf_add(&refname, dirname, dirnamelen); 445 446while((de =readdir(d)) != NULL) { 447unsigned char sha1[20]; 448struct stat st; 449int flag; 450 451if(de->d_name[0] =='.') 452continue; 453if(ends_with(de->d_name,".lock")) 454continue; 455strbuf_addstr(&refname, de->d_name); 456strbuf_addstr(&path, de->d_name); 457if(stat(path.buf, &st) <0) { 458;/* silently ignore */ 459}else if(S_ISDIR(st.st_mode)) { 460strbuf_addch(&refname,'/'); 461add_entry_to_dir(dir, 462create_dir_entry(dir->cache, refname.buf, 463 refname.len,1)); 464}else{ 465if(!refs_resolve_ref_unsafe(&refs->base, 466 refname.buf, 467 RESOLVE_REF_READING, 468 sha1, &flag)) { 469hashclr(sha1); 470 flag |= REF_ISBROKEN; 471}else if(is_null_sha1(sha1)) { 472/* 473 * It is so astronomically unlikely 474 * that NULL_SHA1 is the SHA-1 of an 475 * actual object that we consider its 476 * appearance in a loose reference 477 * file to be repo corruption 478 * (probably due to a software bug). 479 */ 480 flag |= REF_ISBROKEN; 481} 482 483if(check_refname_format(refname.buf, 484 REFNAME_ALLOW_ONELEVEL)) { 485if(!refname_is_safe(refname.buf)) 486die("loose refname is dangerous:%s", refname.buf); 487hashclr(sha1); 488 flag |= REF_BAD_NAME | REF_ISBROKEN; 489} 490add_entry_to_dir(dir, 491create_ref_entry(refname.buf, sha1, flag,0)); 492} 493strbuf_setlen(&refname, dirnamelen); 494strbuf_setlen(&path, path_baselen); 495} 496strbuf_release(&refname); 497strbuf_release(&path); 498closedir(d); 499 500/* 501 * Manually add refs/bisect, which, being per-worktree, might 502 * not appear in the directory listing for refs/ in the main 503 * repo. 504 */ 505if(!strcmp(dirname,"refs/")) { 506int pos =search_ref_dir(dir,"refs/bisect/",12); 507 508if(pos <0) { 509struct ref_entry *child_entry =create_dir_entry( 510 dir->cache,"refs/bisect/",12,1); 511add_entry_to_dir(dir, child_entry); 512} 513} 514} 515 516static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 517{ 518if(!refs->loose) { 519/* 520 * Mark the top-level directory complete because we 521 * are about to read the only subdirectory that can 522 * hold references: 523 */ 524 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 525 526/* We're going to fill the top level ourselves: */ 527 refs->loose->root->flag &= ~REF_INCOMPLETE; 528 529/* 530 * Add an incomplete entry for "refs/" (to be filled 531 * lazily): 532 */ 533add_entry_to_dir(get_ref_dir(refs->loose->root), 534create_dir_entry(refs->loose,"refs/",5,1)); 535} 536return refs->loose; 537} 538 539/* 540 * Return the ref_entry for the given refname from the packed 541 * references. If it does not exist, return NULL. 542 */ 543static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 544const char*refname) 545{ 546returnfind_ref_entry(get_packed_refs(refs), refname); 547} 548 549/* 550 * A loose ref file doesn't exist; check for a packed ref. 551 */ 552static intresolve_packed_ref(struct files_ref_store *refs, 553const char*refname, 554unsigned char*sha1,unsigned int*flags) 555{ 556struct ref_entry *entry; 557 558/* 559 * The loose reference file does not exist; check for a packed 560 * reference. 561 */ 562 entry =get_packed_ref(refs, refname); 563if(entry) { 564hashcpy(sha1, entry->u.value.oid.hash); 565*flags |= REF_ISPACKED; 566return0; 567} 568/* refname is not a packed reference. */ 569return-1; 570} 571 572static intfiles_read_raw_ref(struct ref_store *ref_store, 573const char*refname,unsigned char*sha1, 574struct strbuf *referent,unsigned int*type) 575{ 576struct files_ref_store *refs = 577files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 578struct strbuf sb_contents = STRBUF_INIT; 579struct strbuf sb_path = STRBUF_INIT; 580const char*path; 581const char*buf; 582struct stat st; 583int fd; 584int ret = -1; 585int save_errno; 586int remaining_retries =3; 587 588*type =0; 589strbuf_reset(&sb_path); 590 591files_ref_path(refs, &sb_path, refname); 592 593 path = sb_path.buf; 594 595stat_ref: 596/* 597 * We might have to loop back here to avoid a race 598 * condition: first we lstat() the file, then we try 599 * to read it as a link or as a file. But if somebody 600 * changes the type of the file (file <-> directory 601 * <-> symlink) between the lstat() and reading, then 602 * we don't want to report that as an error but rather 603 * try again starting with the lstat(). 604 * 605 * We'll keep a count of the retries, though, just to avoid 606 * any confusing situation sending us into an infinite loop. 607 */ 608 609if(remaining_retries-- <=0) 610goto out; 611 612if(lstat(path, &st) <0) { 613if(errno != ENOENT) 614goto out; 615if(resolve_packed_ref(refs, refname, sha1, type)) { 616 errno = ENOENT; 617goto out; 618} 619 ret =0; 620goto out; 621} 622 623/* Follow "normalized" - ie "refs/.." symlinks by hand */ 624if(S_ISLNK(st.st_mode)) { 625strbuf_reset(&sb_contents); 626if(strbuf_readlink(&sb_contents, path,0) <0) { 627if(errno == ENOENT || errno == EINVAL) 628/* inconsistent with lstat; retry */ 629goto stat_ref; 630else 631goto out; 632} 633if(starts_with(sb_contents.buf,"refs/") && 634!check_refname_format(sb_contents.buf,0)) { 635strbuf_swap(&sb_contents, referent); 636*type |= REF_ISSYMREF; 637 ret =0; 638goto out; 639} 640/* 641 * It doesn't look like a refname; fall through to just 642 * treating it like a non-symlink, and reading whatever it 643 * points to. 644 */ 645} 646 647/* Is it a directory? */ 648if(S_ISDIR(st.st_mode)) { 649/* 650 * Even though there is a directory where the loose 651 * ref is supposed to be, there could still be a 652 * packed ref: 653 */ 654if(resolve_packed_ref(refs, refname, sha1, type)) { 655 errno = EISDIR; 656goto out; 657} 658 ret =0; 659goto out; 660} 661 662/* 663 * Anything else, just open it and try to use it as 664 * a ref 665 */ 666 fd =open(path, O_RDONLY); 667if(fd <0) { 668if(errno == ENOENT && !S_ISLNK(st.st_mode)) 669/* inconsistent with lstat; retry */ 670goto stat_ref; 671else 672goto out; 673} 674strbuf_reset(&sb_contents); 675if(strbuf_read(&sb_contents, fd,256) <0) { 676int save_errno = errno; 677close(fd); 678 errno = save_errno; 679goto out; 680} 681close(fd); 682strbuf_rtrim(&sb_contents); 683 buf = sb_contents.buf; 684if(starts_with(buf,"ref:")) { 685 buf +=4; 686while(isspace(*buf)) 687 buf++; 688 689strbuf_reset(referent); 690strbuf_addstr(referent, buf); 691*type |= REF_ISSYMREF; 692 ret =0; 693goto out; 694} 695 696/* 697 * Please note that FETCH_HEAD has additional 698 * data after the sha. 699 */ 700if(get_sha1_hex(buf, sha1) || 701(buf[40] !='\0'&& !isspace(buf[40]))) { 702*type |= REF_ISBROKEN; 703 errno = EINVAL; 704goto out; 705} 706 707 ret =0; 708 709out: 710 save_errno = errno; 711strbuf_release(&sb_path); 712strbuf_release(&sb_contents); 713 errno = save_errno; 714return ret; 715} 716 717static voidunlock_ref(struct ref_lock *lock) 718{ 719/* Do not free lock->lk -- atexit() still looks at them */ 720if(lock->lk) 721rollback_lock_file(lock->lk); 722free(lock->ref_name); 723free(lock); 724} 725 726/* 727 * Lock refname, without following symrefs, and set *lock_p to point 728 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 729 * and type similarly to read_raw_ref(). 730 * 731 * The caller must verify that refname is a "safe" reference name (in 732 * the sense of refname_is_safe()) before calling this function. 733 * 734 * If the reference doesn't already exist, verify that refname doesn't 735 * have a D/F conflict with any existing references. extras and skip 736 * are passed to refs_verify_refname_available() for this check. 737 * 738 * If mustexist is not set and the reference is not found or is 739 * broken, lock the reference anyway but clear sha1. 740 * 741 * Return 0 on success. On failure, write an error message to err and 742 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 743 * 744 * Implementation note: This function is basically 745 * 746 * lock reference 747 * read_raw_ref() 748 * 749 * but it includes a lot more code to 750 * - Deal with possible races with other processes 751 * - Avoid calling refs_verify_refname_available() when it can be 752 * avoided, namely if we were successfully able to read the ref 753 * - Generate informative error messages in the case of failure 754 */ 755static intlock_raw_ref(struct files_ref_store *refs, 756const char*refname,int mustexist, 757const struct string_list *extras, 758const struct string_list *skip, 759struct ref_lock **lock_p, 760struct strbuf *referent, 761unsigned int*type, 762struct strbuf *err) 763{ 764struct ref_lock *lock; 765struct strbuf ref_file = STRBUF_INIT; 766int attempts_remaining =3; 767int ret = TRANSACTION_GENERIC_ERROR; 768 769assert(err); 770files_assert_main_repository(refs,"lock_raw_ref"); 771 772*type =0; 773 774/* First lock the file so it can't change out from under us. */ 775 776*lock_p = lock =xcalloc(1,sizeof(*lock)); 777 778 lock->ref_name =xstrdup(refname); 779files_ref_path(refs, &ref_file, refname); 780 781retry: 782switch(safe_create_leading_directories(ref_file.buf)) { 783case SCLD_OK: 784break;/* success */ 785case SCLD_EXISTS: 786/* 787 * Suppose refname is "refs/foo/bar". We just failed 788 * to create the containing directory, "refs/foo", 789 * because there was a non-directory in the way. This 790 * indicates a D/F conflict, probably because of 791 * another reference such as "refs/foo". There is no 792 * reason to expect this error to be transitory. 793 */ 794if(refs_verify_refname_available(&refs->base, refname, 795 extras, skip, err)) { 796if(mustexist) { 797/* 798 * To the user the relevant error is 799 * that the "mustexist" reference is 800 * missing: 801 */ 802strbuf_reset(err); 803strbuf_addf(err,"unable to resolve reference '%s'", 804 refname); 805}else{ 806/* 807 * The error message set by 808 * refs_verify_refname_available() is 809 * OK. 810 */ 811 ret = TRANSACTION_NAME_CONFLICT; 812} 813}else{ 814/* 815 * The file that is in the way isn't a loose 816 * reference. Report it as a low-level 817 * failure. 818 */ 819strbuf_addf(err,"unable to create lock file%s.lock; " 820"non-directory in the way", 821 ref_file.buf); 822} 823goto error_return; 824case SCLD_VANISHED: 825/* Maybe another process was tidying up. Try again. */ 826if(--attempts_remaining >0) 827goto retry; 828/* fall through */ 829default: 830strbuf_addf(err,"unable to create directory for%s", 831 ref_file.buf); 832goto error_return; 833} 834 835if(!lock->lk) 836 lock->lk =xcalloc(1,sizeof(struct lock_file)); 837 838if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 839if(errno == ENOENT && --attempts_remaining >0) { 840/* 841 * Maybe somebody just deleted one of the 842 * directories leading to ref_file. Try 843 * again: 844 */ 845goto retry; 846}else{ 847unable_to_lock_message(ref_file.buf, errno, err); 848goto error_return; 849} 850} 851 852/* 853 * Now we hold the lock and can read the reference without 854 * fear that its value will change. 855 */ 856 857if(files_read_raw_ref(&refs->base, refname, 858 lock->old_oid.hash, referent, type)) { 859if(errno == ENOENT) { 860if(mustexist) { 861/* Garden variety missing reference. */ 862strbuf_addf(err,"unable to resolve reference '%s'", 863 refname); 864goto error_return; 865}else{ 866/* 867 * Reference is missing, but that's OK. We 868 * know that there is not a conflict with 869 * another loose reference because 870 * (supposing that we are trying to lock 871 * reference "refs/foo/bar"): 872 * 873 * - We were successfully able to create 874 * the lockfile refs/foo/bar.lock, so we 875 * know there cannot be a loose reference 876 * named "refs/foo". 877 * 878 * - We got ENOENT and not EISDIR, so we 879 * know that there cannot be a loose 880 * reference named "refs/foo/bar/baz". 881 */ 882} 883}else if(errno == EISDIR) { 884/* 885 * There is a directory in the way. It might have 886 * contained references that have been deleted. If 887 * we don't require that the reference already 888 * exists, try to remove the directory so that it 889 * doesn't cause trouble when we want to rename the 890 * lockfile into place later. 891 */ 892if(mustexist) { 893/* Garden variety missing reference. */ 894strbuf_addf(err,"unable to resolve reference '%s'", 895 refname); 896goto error_return; 897}else if(remove_dir_recursively(&ref_file, 898 REMOVE_DIR_EMPTY_ONLY)) { 899if(refs_verify_refname_available( 900&refs->base, refname, 901 extras, skip, err)) { 902/* 903 * The error message set by 904 * verify_refname_available() is OK. 905 */ 906 ret = TRANSACTION_NAME_CONFLICT; 907goto error_return; 908}else{ 909/* 910 * We can't delete the directory, 911 * but we also don't know of any 912 * references that it should 913 * contain. 914 */ 915strbuf_addf(err,"there is a non-empty directory '%s' " 916"blocking reference '%s'", 917 ref_file.buf, refname); 918goto error_return; 919} 920} 921}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 922strbuf_addf(err,"unable to resolve reference '%s': " 923"reference broken", refname); 924goto error_return; 925}else{ 926strbuf_addf(err,"unable to resolve reference '%s':%s", 927 refname,strerror(errno)); 928goto error_return; 929} 930 931/* 932 * If the ref did not exist and we are creating it, 933 * make sure there is no existing ref that conflicts 934 * with refname: 935 */ 936if(refs_verify_refname_available( 937&refs->base, refname, 938 extras, skip, err)) 939goto error_return; 940} 941 942 ret =0; 943goto out; 944 945error_return: 946unlock_ref(lock); 947*lock_p = NULL; 948 949out: 950strbuf_release(&ref_file); 951return ret; 952} 953 954static intfiles_peel_ref(struct ref_store *ref_store, 955const char*refname,unsigned char*sha1) 956{ 957struct files_ref_store *refs = 958files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 959"peel_ref"); 960int flag; 961unsigned char base[20]; 962 963if(current_ref_iter && current_ref_iter->refname == refname) { 964struct object_id peeled; 965 966if(ref_iterator_peel(current_ref_iter, &peeled)) 967return-1; 968hashcpy(sha1, peeled.hash); 969return0; 970} 971 972if(refs_read_ref_full(ref_store, refname, 973 RESOLVE_REF_READING, base, &flag)) 974return-1; 975 976/* 977 * If the reference is packed, read its ref_entry from the 978 * cache in the hope that we already know its peeled value. 979 * We only try this optimization on packed references because 980 * (a) forcing the filling of the loose reference cache could 981 * be expensive and (b) loose references anyway usually do not 982 * have REF_KNOWS_PEELED. 983 */ 984if(flag & REF_ISPACKED) { 985struct ref_entry *r =get_packed_ref(refs, refname); 986if(r) { 987if(peel_entry(r,0)) 988return-1; 989hashcpy(sha1, r->u.value.peeled.hash); 990return0; 991} 992} 993 994returnpeel_object(base, sha1); 995} 996 997struct files_ref_iterator { 998struct ref_iterator base; 9991000struct packed_ref_cache *packed_ref_cache;1001struct ref_iterator *iter0;1002unsigned int flags;1003};10041005static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1006{1007struct files_ref_iterator *iter =1008(struct files_ref_iterator *)ref_iterator;1009int ok;10101011while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1012if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1013ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1014continue;10151016if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1017!ref_resolves_to_object(iter->iter0->refname,1018 iter->iter0->oid,1019 iter->iter0->flags))1020continue;10211022 iter->base.refname = iter->iter0->refname;1023 iter->base.oid = iter->iter0->oid;1024 iter->base.flags = iter->iter0->flags;1025return ITER_OK;1026}10271028 iter->iter0 = NULL;1029if(ref_iterator_abort(ref_iterator) != ITER_DONE)1030 ok = ITER_ERROR;10311032return ok;1033}10341035static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1036struct object_id *peeled)1037{1038struct files_ref_iterator *iter =1039(struct files_ref_iterator *)ref_iterator;10401041returnref_iterator_peel(iter->iter0, peeled);1042}10431044static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1045{1046struct files_ref_iterator *iter =1047(struct files_ref_iterator *)ref_iterator;1048int ok = ITER_DONE;10491050if(iter->iter0)1051 ok =ref_iterator_abort(iter->iter0);10521053release_packed_ref_cache(iter->packed_ref_cache);1054base_ref_iterator_free(ref_iterator);1055return ok;1056}10571058static struct ref_iterator_vtable files_ref_iterator_vtable = {1059 files_ref_iterator_advance,1060 files_ref_iterator_peel,1061 files_ref_iterator_abort1062};10631064static struct ref_iterator *files_ref_iterator_begin(1065struct ref_store *ref_store,1066const char*prefix,unsigned int flags)1067{1068struct files_ref_store *refs;1069struct ref_iterator *loose_iter, *packed_iter;1070struct files_ref_iterator *iter;1071struct ref_iterator *ref_iterator;10721073if(ref_paranoia <0)1074 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1075if(ref_paranoia)1076 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10771078 refs =files_downcast(ref_store,1079 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1080"ref_iterator_begin");10811082 iter =xcalloc(1,sizeof(*iter));1083 ref_iterator = &iter->base;1084base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10851086/*1087 * We must make sure that all loose refs are read before1088 * accessing the packed-refs file; this avoids a race1089 * condition if loose refs are migrated to the packed-refs1090 * file by a simultaneous process, but our in-memory view is1091 * from before the migration. We ensure this as follows:1092 * First, we call start the loose refs iteration with its1093 * `prime_ref` argument set to true. This causes the loose1094 * references in the subtree to be pre-read into the cache.1095 * (If they've already been read, that's OK; we only need to1096 * guarantee that they're read before the packed refs, not1097 * *how much* before.) After that, we call1098 * get_packed_ref_cache(), which internally checks whether the1099 * packed-ref cache is up to date with what is on disk, and1100 * re-reads it if not.1101 */11021103 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1104 prefix,1);11051106 iter->packed_ref_cache =get_packed_ref_cache(refs);1107acquire_packed_ref_cache(iter->packed_ref_cache);1108 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1109 prefix,0);11101111 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1112 iter->flags = flags;11131114return ref_iterator;1115}11161117/*1118 * Verify that the reference locked by lock has the value old_sha1.1119 * Fail if the reference doesn't exist and mustexist is set. Return 01120 * on success. On error, write an error message to err, set errno, and1121 * return a negative value.1122 */1123static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1124const unsigned char*old_sha1,int mustexist,1125struct strbuf *err)1126{1127assert(err);11281129if(refs_read_ref_full(ref_store, lock->ref_name,1130 mustexist ? RESOLVE_REF_READING :0,1131 lock->old_oid.hash, NULL)) {1132if(old_sha1) {1133int save_errno = errno;1134strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1135 errno = save_errno;1136return-1;1137}else{1138oidclr(&lock->old_oid);1139return0;1140}1141}1142if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1143strbuf_addf(err,"ref '%s' is at%sbut expected%s",1144 lock->ref_name,1145oid_to_hex(&lock->old_oid),1146sha1_to_hex(old_sha1));1147 errno = EBUSY;1148return-1;1149}1150return0;1151}11521153static intremove_empty_directories(struct strbuf *path)1154{1155/*1156 * we want to create a file but there is a directory there;1157 * if that is an empty directory (or a directory that contains1158 * only empty directories), remove them.1159 */1160returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1161}11621163static intcreate_reflock(const char*path,void*cb)1164{1165struct lock_file *lk = cb;11661167returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1168}11691170/*1171 * Locks a ref returning the lock on success and NULL on failure.1172 * On failure errno is set to something meaningful.1173 */1174static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1175const char*refname,1176const unsigned char*old_sha1,1177const struct string_list *extras,1178const struct string_list *skip,1179unsigned int flags,int*type,1180struct strbuf *err)1181{1182struct strbuf ref_file = STRBUF_INIT;1183struct ref_lock *lock;1184int last_errno =0;1185int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1186int resolve_flags = RESOLVE_REF_NO_RECURSE;1187int resolved;11881189files_assert_main_repository(refs,"lock_ref_sha1_basic");1190assert(err);11911192 lock =xcalloc(1,sizeof(struct ref_lock));11931194if(mustexist)1195 resolve_flags |= RESOLVE_REF_READING;1196if(flags & REF_DELETING)1197 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11981199files_ref_path(refs, &ref_file, refname);1200 resolved = !!refs_resolve_ref_unsafe(&refs->base,1201 refname, resolve_flags,1202 lock->old_oid.hash, type);1203if(!resolved && errno == EISDIR) {1204/*1205 * we are trying to lock foo but we used to1206 * have foo/bar which now does not exist;1207 * it is normal for the empty directory 'foo'1208 * to remain.1209 */1210if(remove_empty_directories(&ref_file)) {1211 last_errno = errno;1212if(!refs_verify_refname_available(1213&refs->base,1214 refname, extras, skip, err))1215strbuf_addf(err,"there are still refs under '%s'",1216 refname);1217goto error_return;1218}1219 resolved = !!refs_resolve_ref_unsafe(&refs->base,1220 refname, resolve_flags,1221 lock->old_oid.hash, type);1222}1223if(!resolved) {1224 last_errno = errno;1225if(last_errno != ENOTDIR ||1226!refs_verify_refname_available(&refs->base, refname,1227 extras, skip, err))1228strbuf_addf(err,"unable to resolve reference '%s':%s",1229 refname,strerror(last_errno));12301231goto error_return;1232}12331234/*1235 * If the ref did not exist and we are creating it, make sure1236 * there is no existing packed ref whose name begins with our1237 * refname, nor a packed ref whose name is a proper prefix of1238 * our refname.1239 */1240if(is_null_oid(&lock->old_oid) &&1241refs_verify_refname_available(&refs->base, refname,1242 extras, skip, err)) {1243 last_errno = ENOTDIR;1244goto error_return;1245}12461247 lock->lk =xcalloc(1,sizeof(struct lock_file));12481249 lock->ref_name =xstrdup(refname);12501251if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1252 last_errno = errno;1253unable_to_lock_message(ref_file.buf, errno, err);1254goto error_return;1255}12561257if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1258 last_errno = errno;1259goto error_return;1260}1261goto out;12621263 error_return:1264unlock_ref(lock);1265 lock = NULL;12661267 out:1268strbuf_release(&ref_file);1269 errno = last_errno;1270return lock;1271}12721273/*1274 * Write an entry to the packed-refs file for the specified refname.1275 * If peeled is non-NULL, write it as the entry's peeled value.1276 */1277static voidwrite_packed_entry(FILE*fh,const char*refname,1278const unsigned char*sha1,1279const unsigned char*peeled)1280{1281fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1282if(peeled)1283fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1284}12851286/*1287 * Lock the packed-refs file for writing. Flags is passed to1288 * hold_lock_file_for_update(). Return 0 on success. On errors, set1289 * errno appropriately and return a nonzero value.1290 */1291static intlock_packed_refs(struct files_ref_store *refs,int flags)1292{1293static int timeout_configured =0;1294static int timeout_value =1000;1295struct packed_ref_cache *packed_ref_cache;12961297files_assert_main_repository(refs,"lock_packed_refs");12981299if(!timeout_configured) {1300git_config_get_int("core.packedrefstimeout", &timeout_value);1301 timeout_configured =1;1302}13031304if(hold_lock_file_for_update_timeout(1305&packlock,files_packed_refs_path(refs),1306 flags, timeout_value) <0)1307return-1;1308/*1309 * Get the current packed-refs while holding the lock. If the1310 * packed-refs file has been modified since we last read it,1311 * this will automatically invalidate the cache and re-read1312 * the packed-refs file.1313 */1314 packed_ref_cache =get_packed_ref_cache(refs);1315 packed_ref_cache->lock = &packlock;1316/* Increment the reference count to prevent it from being freed: */1317acquire_packed_ref_cache(packed_ref_cache);1318return0;1319}13201321/*1322 * Write the current version of the packed refs cache from memory to1323 * disk. The packed-refs file must already be locked for writing (see1324 * lock_packed_refs()). Return zero on success. On errors, set errno1325 * and return a nonzero value1326 */1327static intcommit_packed_refs(struct files_ref_store *refs)1328{1329struct packed_ref_cache *packed_ref_cache =1330get_packed_ref_cache(refs);1331int ok, error =0;1332int save_errno =0;1333FILE*out;1334struct ref_iterator *iter;13351336files_assert_main_repository(refs,"commit_packed_refs");13371338if(!packed_ref_cache->lock)1339die("internal error: packed-refs not locked");13401341 out =fdopen_lock_file(packed_ref_cache->lock,"w");1342if(!out)1343die_errno("unable to fdopen packed-refs descriptor");13441345fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13461347 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1348while((ok =ref_iterator_advance(iter)) == ITER_OK) {1349struct object_id peeled;1350int peel_error =ref_iterator_peel(iter, &peeled);13511352write_packed_entry(out, iter->refname, iter->oid->hash,1353 peel_error ? NULL : peeled.hash);1354}13551356if(ok != ITER_DONE)1357die("error while iterating over references");13581359if(commit_lock_file(packed_ref_cache->lock)) {1360 save_errno = errno;1361 error = -1;1362}1363 packed_ref_cache->lock = NULL;1364release_packed_ref_cache(packed_ref_cache);1365 errno = save_errno;1366return error;1367}13681369/*1370 * Rollback the lockfile for the packed-refs file, and discard the1371 * in-memory packed reference cache. (The packed-refs file will be1372 * read anew if it is needed again after this function is called.)1373 */1374static voidrollback_packed_refs(struct files_ref_store *refs)1375{1376struct packed_ref_cache *packed_ref_cache =1377get_packed_ref_cache(refs);13781379files_assert_main_repository(refs,"rollback_packed_refs");13801381if(!packed_ref_cache->lock)1382die("internal error: packed-refs not locked");1383rollback_lock_file(packed_ref_cache->lock);1384 packed_ref_cache->lock = NULL;1385release_packed_ref_cache(packed_ref_cache);1386clear_packed_ref_cache(refs);1387}13881389struct ref_to_prune {1390struct ref_to_prune *next;1391unsigned char sha1[20];1392char name[FLEX_ARRAY];1393};13941395enum{1396 REMOVE_EMPTY_PARENTS_REF =0x01,1397 REMOVE_EMPTY_PARENTS_REFLOG =0x021398};13991400/*1401 * Remove empty parent directories associated with the specified1402 * reference and/or its reflog, but spare [logs/]refs/ and immediate1403 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1404 * REMOVE_EMPTY_PARENTS_REFLOG.1405 */1406static voidtry_remove_empty_parents(struct files_ref_store *refs,1407const char*refname,1408unsigned int flags)1409{1410struct strbuf buf = STRBUF_INIT;1411struct strbuf sb = STRBUF_INIT;1412char*p, *q;1413int i;14141415strbuf_addstr(&buf, refname);1416 p = buf.buf;1417for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1418while(*p && *p !='/')1419 p++;1420/* tolerate duplicate slashes; see check_refname_format() */1421while(*p =='/')1422 p++;1423}1424 q = buf.buf + buf.len;1425while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1426while(q > p && *q !='/')1427 q--;1428while(q > p && *(q-1) =='/')1429 q--;1430if(q == p)1431break;1432strbuf_setlen(&buf, q - buf.buf);14331434strbuf_reset(&sb);1435files_ref_path(refs, &sb, buf.buf);1436if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1437 flags &= ~REMOVE_EMPTY_PARENTS_REF;14381439strbuf_reset(&sb);1440files_reflog_path(refs, &sb, buf.buf);1441if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1442 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1443}1444strbuf_release(&buf);1445strbuf_release(&sb);1446}14471448/* make sure nobody touched the ref, and unlink */1449static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1450{1451struct ref_transaction *transaction;1452struct strbuf err = STRBUF_INIT;14531454if(check_refname_format(r->name,0))1455return;14561457 transaction =ref_store_transaction_begin(&refs->base, &err);1458if(!transaction ||1459ref_transaction_delete(transaction, r->name, r->sha1,1460 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1461ref_transaction_commit(transaction, &err)) {1462ref_transaction_free(transaction);1463error("%s", err.buf);1464strbuf_release(&err);1465return;1466}1467ref_transaction_free(transaction);1468strbuf_release(&err);1469}14701471static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1472{1473while(r) {1474prune_ref(refs, r);1475 r = r->next;1476}1477}14781479static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1480{1481struct files_ref_store *refs =1482files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1483"pack_refs");1484struct ref_iterator *iter;1485struct ref_dir *packed_refs;1486int ok;1487struct ref_to_prune *refs_to_prune = NULL;14881489lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1490 packed_refs =get_packed_refs(refs);14911492 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1493while((ok =ref_iterator_advance(iter)) == ITER_OK) {1494/*1495 * If the loose reference can be packed, add an entry1496 * in the packed ref cache. If the reference should be1497 * pruned, also add it to refs_to_prune.1498 */1499struct ref_entry *packed_entry;1500int is_tag_ref =starts_with(iter->refname,"refs/tags/");15011502/* Do not pack per-worktree refs: */1503if(ref_type(iter->refname) != REF_TYPE_NORMAL)1504continue;15051506/* ALWAYS pack tags */1507if(!(flags & PACK_REFS_ALL) && !is_tag_ref)1508continue;15091510/* Do not pack symbolic or broken refs: */1511if(iter->flags & REF_ISSYMREF)1512continue;15131514if(!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))1515continue;15161517/*1518 * Create an entry in the packed-refs cache equivalent1519 * to the one from the loose ref cache, except that1520 * we don't copy the peeled status, because we want it1521 * to be re-peeled.1522 */1523 packed_entry =find_ref_entry(packed_refs, iter->refname);1524if(packed_entry) {1525/* Overwrite existing packed entry with info from loose entry */1526 packed_entry->flag = REF_ISPACKED;1527oidcpy(&packed_entry->u.value.oid, iter->oid);1528}else{1529 packed_entry =create_ref_entry(iter->refname, iter->oid->hash,1530 REF_ISPACKED,0);1531add_ref_entry(packed_refs, packed_entry);1532}1533oidclr(&packed_entry->u.value.peeled);15341535/* Schedule the loose reference for pruning if requested. */1536if((flags & PACK_REFS_PRUNE)) {1537struct ref_to_prune *n;1538FLEX_ALLOC_STR(n, name, iter->refname);1539hashcpy(n->sha1, iter->oid->hash);1540 n->next = refs_to_prune;1541 refs_to_prune = n;1542}1543}1544if(ok != ITER_DONE)1545die("error while iterating over references");15461547if(commit_packed_refs(refs))1548die_errno("unable to overwrite old ref-pack file");15491550prune_refs(refs, refs_to_prune);1551return0;1552}15531554/*1555 * Rewrite the packed-refs file, omitting any refs listed in1556 * 'refnames'. On error, leave packed-refs unchanged, write an error1557 * message to 'err', and return a nonzero value.1558 *1559 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1560 */1561static intrepack_without_refs(struct files_ref_store *refs,1562struct string_list *refnames,struct strbuf *err)1563{1564struct ref_dir *packed;1565struct string_list_item *refname;1566int ret, needs_repacking =0, removed =0;15671568files_assert_main_repository(refs,"repack_without_refs");1569assert(err);15701571/* Look for a packed ref */1572for_each_string_list_item(refname, refnames) {1573if(get_packed_ref(refs, refname->string)) {1574 needs_repacking =1;1575break;1576}1577}15781579/* Avoid locking if we have nothing to do */1580if(!needs_repacking)1581return0;/* no refname exists in packed refs */15821583if(lock_packed_refs(refs,0)) {1584unable_to_lock_message(files_packed_refs_path(refs), errno, err);1585return-1;1586}1587 packed =get_packed_refs(refs);15881589/* Remove refnames from the cache */1590for_each_string_list_item(refname, refnames)1591if(remove_entry_from_dir(packed, refname->string) != -1)1592 removed =1;1593if(!removed) {1594/*1595 * All packed entries disappeared while we were1596 * acquiring the lock.1597 */1598rollback_packed_refs(refs);1599return0;1600}16011602/* Write what remains */1603 ret =commit_packed_refs(refs);1604if(ret)1605strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1606strerror(errno));1607return ret;1608}16091610static intfiles_delete_refs(struct ref_store *ref_store,1611struct string_list *refnames,unsigned int flags)1612{1613struct files_ref_store *refs =1614files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1615struct strbuf err = STRBUF_INIT;1616int i, result =0;16171618if(!refnames->nr)1619return0;16201621 result =repack_without_refs(refs, refnames, &err);1622if(result) {1623/*1624 * If we failed to rewrite the packed-refs file, then1625 * it is unsafe to try to remove loose refs, because1626 * doing so might expose an obsolete packed value for1627 * a reference that might even point at an object that1628 * has been garbage collected.1629 */1630if(refnames->nr ==1)1631error(_("could not delete reference%s:%s"),1632 refnames->items[0].string, err.buf);1633else1634error(_("could not delete references:%s"), err.buf);16351636goto out;1637}16381639for(i =0; i < refnames->nr; i++) {1640const char*refname = refnames->items[i].string;16411642if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))1643 result |=error(_("could not remove reference%s"), refname);1644}16451646out:1647strbuf_release(&err);1648return result;1649}16501651/*1652 * People using contrib's git-new-workdir have .git/logs/refs ->1653 * /some/other/path/.git/logs/refs, and that may live on another device.1654 *1655 * IOW, to avoid cross device rename errors, the temporary renamed log must1656 * live into logs/refs.1657 */1658#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16591660struct rename_cb {1661const char*tmp_renamed_log;1662int true_errno;1663};16641665static intrename_tmp_log_callback(const char*path,void*cb_data)1666{1667struct rename_cb *cb = cb_data;16681669if(rename(cb->tmp_renamed_log, path)) {1670/*1671 * rename(a, b) when b is an existing directory ought1672 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1673 * Sheesh. Record the true errno for error reporting,1674 * but report EISDIR to raceproof_create_file() so1675 * that it knows to retry.1676 */1677 cb->true_errno = errno;1678if(errno == ENOTDIR)1679 errno = EISDIR;1680return-1;1681}else{1682return0;1683}1684}16851686static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1687{1688struct strbuf path = STRBUF_INIT;1689struct strbuf tmp = STRBUF_INIT;1690struct rename_cb cb;1691int ret;16921693files_reflog_path(refs, &path, newrefname);1694files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1695 cb.tmp_renamed_log = tmp.buf;1696 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1697if(ret) {1698if(errno == EISDIR)1699error("directory not empty:%s", path.buf);1700else1701error("unable to move logfile%sto%s:%s",1702 tmp.buf, path.buf,1703strerror(cb.true_errno));1704}17051706strbuf_release(&path);1707strbuf_release(&tmp);1708return ret;1709}17101711static intwrite_ref_to_lockfile(struct ref_lock *lock,1712const unsigned char*sha1,struct strbuf *err);1713static intcommit_ref_update(struct files_ref_store *refs,1714struct ref_lock *lock,1715const unsigned char*sha1,const char*logmsg,1716struct strbuf *err);17171718static intfiles_rename_ref(struct ref_store *ref_store,1719const char*oldrefname,const char*newrefname,1720const char*logmsg)1721{1722struct files_ref_store *refs =1723files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1724unsigned char sha1[20], orig_sha1[20];1725int flag =0, logmoved =0;1726struct ref_lock *lock;1727struct stat loginfo;1728struct strbuf sb_oldref = STRBUF_INIT;1729struct strbuf sb_newref = STRBUF_INIT;1730struct strbuf tmp_renamed_log = STRBUF_INIT;1731int log, ret;1732struct strbuf err = STRBUF_INIT;17331734files_reflog_path(refs, &sb_oldref, oldrefname);1735files_reflog_path(refs, &sb_newref, newrefname);1736files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17371738 log = !lstat(sb_oldref.buf, &loginfo);1739if(log &&S_ISLNK(loginfo.st_mode)) {1740 ret =error("reflog for%sis a symlink", oldrefname);1741goto out;1742}17431744if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1745 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1746 orig_sha1, &flag)) {1747 ret =error("refname%snot found", oldrefname);1748goto out;1749}17501751if(flag & REF_ISSYMREF) {1752 ret =error("refname%sis a symbolic ref, renaming it is not supported",1753 oldrefname);1754goto out;1755}1756if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1757 ret =1;1758goto out;1759}17601761if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1762 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1763 oldrefname,strerror(errno));1764goto out;1765}17661767if(refs_delete_ref(&refs->base, logmsg, oldrefname,1768 orig_sha1, REF_NODEREF)) {1769error("unable to delete old%s", oldrefname);1770goto rollback;1771}17721773/*1774 * Since we are doing a shallow lookup, sha1 is not the1775 * correct value to pass to delete_ref as old_sha1. But that1776 * doesn't matter, because an old_sha1 check wouldn't add to1777 * the safety anyway; we want to delete the reference whatever1778 * its current value.1779 */1780if(!refs_read_ref_full(&refs->base, newrefname,1781 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1782 sha1, NULL) &&1783refs_delete_ref(&refs->base, NULL, newrefname,1784 NULL, REF_NODEREF)) {1785if(errno == EISDIR) {1786struct strbuf path = STRBUF_INIT;1787int result;17881789files_ref_path(refs, &path, newrefname);1790 result =remove_empty_directories(&path);1791strbuf_release(&path);17921793if(result) {1794error("Directory not empty:%s", newrefname);1795goto rollback;1796}1797}else{1798error("unable to delete existing%s", newrefname);1799goto rollback;1800}1801}18021803if(log &&rename_tmp_log(refs, newrefname))1804goto rollback;18051806 logmoved = log;18071808 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1809 REF_NODEREF, NULL, &err);1810if(!lock) {1811error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1812strbuf_release(&err);1813goto rollback;1814}1815hashcpy(lock->old_oid.hash, orig_sha1);18161817if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1818commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {1819error("unable to write current sha1 into%s:%s", newrefname, err.buf);1820strbuf_release(&err);1821goto rollback;1822}18231824 ret =0;1825goto out;18261827 rollback:1828 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1829 REF_NODEREF, NULL, &err);1830if(!lock) {1831error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1832strbuf_release(&err);1833goto rollbacklog;1834}18351836 flag = log_all_ref_updates;1837 log_all_ref_updates = LOG_REFS_NONE;1838if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1839commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {1840error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1841strbuf_release(&err);1842}1843 log_all_ref_updates = flag;18441845 rollbacklog:1846if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1847error("unable to restore logfile%sfrom%s:%s",1848 oldrefname, newrefname,strerror(errno));1849if(!logmoved && log &&1850rename(tmp_renamed_log.buf, sb_oldref.buf))1851error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1852 oldrefname,strerror(errno));1853 ret =1;1854 out:1855strbuf_release(&sb_newref);1856strbuf_release(&sb_oldref);1857strbuf_release(&tmp_renamed_log);18581859return ret;1860}18611862static intclose_ref(struct ref_lock *lock)1863{1864if(close_lock_file(lock->lk))1865return-1;1866return0;1867}18681869static intcommit_ref(struct ref_lock *lock)1870{1871char*path =get_locked_file_path(lock->lk);1872struct stat st;18731874if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1875/*1876 * There is a directory at the path we want to rename1877 * the lockfile to. Hopefully it is empty; try to1878 * delete it.1879 */1880size_t len =strlen(path);1881struct strbuf sb_path = STRBUF_INIT;18821883strbuf_attach(&sb_path, path, len, len);18841885/*1886 * If this fails, commit_lock_file() will also fail1887 * and will report the problem.1888 */1889remove_empty_directories(&sb_path);1890strbuf_release(&sb_path);1891}else{1892free(path);1893}18941895if(commit_lock_file(lock->lk))1896return-1;1897return0;1898}18991900static intopen_or_create_logfile(const char*path,void*cb)1901{1902int*fd = cb;19031904*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1905return(*fd <0) ? -1:0;1906}19071908/*1909 * Create a reflog for a ref. If force_create = 0, only create the1910 * reflog for certain refs (those for which should_autocreate_reflog1911 * returns non-zero). Otherwise, create it regardless of the reference1912 * name. If the logfile already existed or was created, return 0 and1913 * set *logfd to the file descriptor opened for appending to the file.1914 * If no logfile exists and we decided not to create one, return 0 and1915 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1916 * return -1.1917 */1918static intlog_ref_setup(struct files_ref_store *refs,1919const char*refname,int force_create,1920int*logfd,struct strbuf *err)1921{1922struct strbuf logfile_sb = STRBUF_INIT;1923char*logfile;19241925files_reflog_path(refs, &logfile_sb, refname);1926 logfile =strbuf_detach(&logfile_sb, NULL);19271928if(force_create ||should_autocreate_reflog(refname)) {1929if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1930if(errno == ENOENT)1931strbuf_addf(err,"unable to create directory for '%s': "1932"%s", logfile,strerror(errno));1933else if(errno == EISDIR)1934strbuf_addf(err,"there are still logs under '%s'",1935 logfile);1936else1937strbuf_addf(err,"unable to append to '%s':%s",1938 logfile,strerror(errno));19391940goto error;1941}1942}else{1943*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1944if(*logfd <0) {1945if(errno == ENOENT || errno == EISDIR) {1946/*1947 * The logfile doesn't already exist,1948 * but that is not an error; it only1949 * means that we won't write log1950 * entries to it.1951 */1952;1953}else{1954strbuf_addf(err,"unable to append to '%s':%s",1955 logfile,strerror(errno));1956goto error;1957}1958}1959}19601961if(*logfd >=0)1962adjust_shared_perm(logfile);19631964free(logfile);1965return0;19661967error:1968free(logfile);1969return-1;1970}19711972static intfiles_create_reflog(struct ref_store *ref_store,1973const char*refname,int force_create,1974struct strbuf *err)1975{1976struct files_ref_store *refs =1977files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1978int fd;19791980if(log_ref_setup(refs, refname, force_create, &fd, err))1981return-1;19821983if(fd >=0)1984close(fd);19851986return0;1987}19881989static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,1990const unsigned char*new_sha1,1991const char*committer,const char*msg)1992{1993int msglen, written;1994unsigned maxlen, len;1995char*logrec;19961997 msglen = msg ?strlen(msg) :0;1998 maxlen =strlen(committer) + msglen +100;1999 logrec =xmalloc(maxlen);2000 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2001sha1_to_hex(old_sha1),2002sha1_to_hex(new_sha1),2003 committer);2004if(msglen)2005 len +=copy_reflog_msg(logrec + len -1, msg) -1;20062007 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2008free(logrec);2009if(written != len)2010return-1;20112012return0;2013}20142015static intfiles_log_ref_write(struct files_ref_store *refs,2016const char*refname,const unsigned char*old_sha1,2017const unsigned char*new_sha1,const char*msg,2018int flags,struct strbuf *err)2019{2020int logfd, result;20212022if(log_all_ref_updates == LOG_REFS_UNSET)2023 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20242025 result =log_ref_setup(refs, refname,2026 flags & REF_FORCE_CREATE_REFLOG,2027&logfd, err);20282029if(result)2030return result;20312032if(logfd <0)2033return0;2034 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2035git_committer_info(0), msg);2036if(result) {2037struct strbuf sb = STRBUF_INIT;2038int save_errno = errno;20392040files_reflog_path(refs, &sb, refname);2041strbuf_addf(err,"unable to append to '%s':%s",2042 sb.buf,strerror(save_errno));2043strbuf_release(&sb);2044close(logfd);2045return-1;2046}2047if(close(logfd)) {2048struct strbuf sb = STRBUF_INIT;2049int save_errno = errno;20502051files_reflog_path(refs, &sb, refname);2052strbuf_addf(err,"unable to append to '%s':%s",2053 sb.buf,strerror(save_errno));2054strbuf_release(&sb);2055return-1;2056}2057return0;2058}20592060/*2061 * Write sha1 into the open lockfile, then close the lockfile. On2062 * errors, rollback the lockfile, fill in *err and2063 * return -1.2064 */2065static intwrite_ref_to_lockfile(struct ref_lock *lock,2066const unsigned char*sha1,struct strbuf *err)2067{2068static char term ='\n';2069struct object *o;2070int fd;20712072 o =parse_object(sha1);2073if(!o) {2074strbuf_addf(err,2075"trying to write ref '%s' with nonexistent object%s",2076 lock->ref_name,sha1_to_hex(sha1));2077unlock_ref(lock);2078return-1;2079}2080if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2081strbuf_addf(err,2082"trying to write non-commit object%sto branch '%s'",2083sha1_to_hex(sha1), lock->ref_name);2084unlock_ref(lock);2085return-1;2086}2087 fd =get_lock_file_fd(lock->lk);2088if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2089write_in_full(fd, &term,1) !=1||2090close_ref(lock) <0) {2091strbuf_addf(err,2092"couldn't write '%s'",get_lock_file_path(lock->lk));2093unlock_ref(lock);2094return-1;2095}2096return0;2097}20982099/*2100 * Commit a change to a loose reference that has already been written2101 * to the loose reference lockfile. Also update the reflogs if2102 * necessary, using the specified lockmsg (which can be NULL).2103 */2104static intcommit_ref_update(struct files_ref_store *refs,2105struct ref_lock *lock,2106const unsigned char*sha1,const char*logmsg,2107struct strbuf *err)2108{2109files_assert_main_repository(refs,"commit_ref_update");21102111clear_loose_ref_cache(refs);2112if(files_log_ref_write(refs, lock->ref_name,2113 lock->old_oid.hash, sha1,2114 logmsg,0, err)) {2115char*old_msg =strbuf_detach(err, NULL);2116strbuf_addf(err,"cannot update the ref '%s':%s",2117 lock->ref_name, old_msg);2118free(old_msg);2119unlock_ref(lock);2120return-1;2121}21222123if(strcmp(lock->ref_name,"HEAD") !=0) {2124/*2125 * Special hack: If a branch is updated directly and HEAD2126 * points to it (may happen on the remote side of a push2127 * for example) then logically the HEAD reflog should be2128 * updated too.2129 * A generic solution implies reverse symref information,2130 * but finding all symrefs pointing to the given branch2131 * would be rather costly for this rare event (the direct2132 * update of a branch) to be worth it. So let's cheat and2133 * check with HEAD only which should cover 99% of all usage2134 * scenarios (even 100% of the default ones).2135 */2136unsigned char head_sha1[20];2137int head_flag;2138const char*head_ref;21392140 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2141 RESOLVE_REF_READING,2142 head_sha1, &head_flag);2143if(head_ref && (head_flag & REF_ISSYMREF) &&2144!strcmp(head_ref, lock->ref_name)) {2145struct strbuf log_err = STRBUF_INIT;2146if(files_log_ref_write(refs,"HEAD",2147 lock->old_oid.hash, sha1,2148 logmsg,0, &log_err)) {2149error("%s", log_err.buf);2150strbuf_release(&log_err);2151}2152}2153}21542155if(commit_ref(lock)) {2156strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2157unlock_ref(lock);2158return-1;2159}21602161unlock_ref(lock);2162return0;2163}21642165static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2166{2167int ret = -1;2168#ifndef NO_SYMLINK_HEAD2169char*ref_path =get_locked_file_path(lock->lk);2170unlink(ref_path);2171 ret =symlink(target, ref_path);2172free(ref_path);21732174if(ret)2175fprintf(stderr,"no symlink - falling back to symbolic ref\n");2176#endif2177return ret;2178}21792180static voidupdate_symref_reflog(struct files_ref_store *refs,2181struct ref_lock *lock,const char*refname,2182const char*target,const char*logmsg)2183{2184struct strbuf err = STRBUF_INIT;2185unsigned char new_sha1[20];2186if(logmsg &&2187!refs_read_ref_full(&refs->base, target,2188 RESOLVE_REF_READING, new_sha1, NULL) &&2189files_log_ref_write(refs, refname, lock->old_oid.hash,2190 new_sha1, logmsg,0, &err)) {2191error("%s", err.buf);2192strbuf_release(&err);2193}2194}21952196static intcreate_symref_locked(struct files_ref_store *refs,2197struct ref_lock *lock,const char*refname,2198const char*target,const char*logmsg)2199{2200if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2201update_symref_reflog(refs, lock, refname, target, logmsg);2202return0;2203}22042205if(!fdopen_lock_file(lock->lk,"w"))2206returnerror("unable to fdopen%s:%s",2207 lock->lk->tempfile.filename.buf,strerror(errno));22082209update_symref_reflog(refs, lock, refname, target, logmsg);22102211/* no error check; commit_ref will check ferror */2212fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2213if(commit_ref(lock) <0)2214returnerror("unable to write symref for%s:%s", refname,2215strerror(errno));2216return0;2217}22182219static intfiles_create_symref(struct ref_store *ref_store,2220const char*refname,const char*target,2221const char*logmsg)2222{2223struct files_ref_store *refs =2224files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2225struct strbuf err = STRBUF_INIT;2226struct ref_lock *lock;2227int ret;22282229 lock =lock_ref_sha1_basic(refs, refname, NULL,2230 NULL, NULL, REF_NODEREF, NULL,2231&err);2232if(!lock) {2233error("%s", err.buf);2234strbuf_release(&err);2235return-1;2236}22372238 ret =create_symref_locked(refs, lock, refname, target, logmsg);2239unlock_ref(lock);2240return ret;2241}22422243intset_worktree_head_symref(const char*gitdir,const char*target,const char*logmsg)2244{2245/*2246 * FIXME: this obviously will not work well for future refs2247 * backends. This function needs to die.2248 */2249struct files_ref_store *refs =2250files_downcast(get_main_ref_store(),2251 REF_STORE_WRITE,2252"set_head_symref");22532254static struct lock_file head_lock;2255struct ref_lock *lock;2256struct strbuf head_path = STRBUF_INIT;2257const char*head_rel;2258int ret;22592260strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2261if(hold_lock_file_for_update(&head_lock, head_path.buf,2262 LOCK_NO_DEREF) <0) {2263struct strbuf err = STRBUF_INIT;2264unable_to_lock_message(head_path.buf, errno, &err);2265error("%s", err.buf);2266strbuf_release(&err);2267strbuf_release(&head_path);2268return-1;2269}22702271/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2272 linked trees */2273 head_rel =remove_leading_path(head_path.buf,2274absolute_path(get_git_common_dir()));2275/* to make use of create_symref_locked(), initialize ref_lock */2276 lock =xcalloc(1,sizeof(struct ref_lock));2277 lock->lk = &head_lock;2278 lock->ref_name =xstrdup(head_rel);22792280 ret =create_symref_locked(refs, lock, head_rel, target, logmsg);22812282unlock_ref(lock);/* will free lock */2283strbuf_release(&head_path);2284return ret;2285}22862287static intfiles_reflog_exists(struct ref_store *ref_store,2288const char*refname)2289{2290struct files_ref_store *refs =2291files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2292struct strbuf sb = STRBUF_INIT;2293struct stat st;2294int ret;22952296files_reflog_path(refs, &sb, refname);2297 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2298strbuf_release(&sb);2299return ret;2300}23012302static intfiles_delete_reflog(struct ref_store *ref_store,2303const char*refname)2304{2305struct files_ref_store *refs =2306files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2307struct strbuf sb = STRBUF_INIT;2308int ret;23092310files_reflog_path(refs, &sb, refname);2311 ret =remove_path(sb.buf);2312strbuf_release(&sb);2313return ret;2314}23152316static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2317{2318struct object_id ooid, noid;2319char*email_end, *message;2320unsigned long timestamp;2321int tz;2322const char*p = sb->buf;23232324/* old SP new SP name <email> SP time TAB msg LF */2325if(!sb->len || sb->buf[sb->len -1] !='\n'||2326parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2327parse_oid_hex(p, &noid, &p) || *p++ !=' '||2328!(email_end =strchr(p,'>')) ||2329 email_end[1] !=' '||2330!(timestamp =strtoul(email_end +2, &message,10)) ||2331!message || message[0] !=' '||2332(message[1] !='+'&& message[1] !='-') ||2333!isdigit(message[2]) || !isdigit(message[3]) ||2334!isdigit(message[4]) || !isdigit(message[5]))2335return0;/* corrupt? */2336 email_end[1] ='\0';2337 tz =strtol(message +1, NULL,10);2338if(message[6] !='\t')2339 message +=6;2340else2341 message +=7;2342returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2343}23442345static char*find_beginning_of_line(char*bob,char*scan)2346{2347while(bob < scan && *(--scan) !='\n')2348;/* keep scanning backwards */2349/*2350 * Return either beginning of the buffer, or LF at the end of2351 * the previous line.2352 */2353return scan;2354}23552356static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2357const char*refname,2358 each_reflog_ent_fn fn,2359void*cb_data)2360{2361struct files_ref_store *refs =2362files_downcast(ref_store, REF_STORE_READ,2363"for_each_reflog_ent_reverse");2364struct strbuf sb = STRBUF_INIT;2365FILE*logfp;2366long pos;2367int ret =0, at_tail =1;23682369files_reflog_path(refs, &sb, refname);2370 logfp =fopen(sb.buf,"r");2371strbuf_release(&sb);2372if(!logfp)2373return-1;23742375/* Jump to the end */2376if(fseek(logfp,0, SEEK_END) <0)2377 ret =error("cannot seek back reflog for%s:%s",2378 refname,strerror(errno));2379 pos =ftell(logfp);2380while(!ret &&0< pos) {2381int cnt;2382size_t nread;2383char buf[BUFSIZ];2384char*endp, *scanp;23852386/* Fill next block from the end */2387 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2388if(fseek(logfp, pos - cnt, SEEK_SET)) {2389 ret =error("cannot seek back reflog for%s:%s",2390 refname,strerror(errno));2391break;2392}2393 nread =fread(buf, cnt,1, logfp);2394if(nread !=1) {2395 ret =error("cannot read%dbytes from reflog for%s:%s",2396 cnt, refname,strerror(errno));2397break;2398}2399 pos -= cnt;24002401 scanp = endp = buf + cnt;2402if(at_tail && scanp[-1] =='\n')2403/* Looking at the final LF at the end of the file */2404 scanp--;2405 at_tail =0;24062407while(buf < scanp) {2408/*2409 * terminating LF of the previous line, or the beginning2410 * of the buffer.2411 */2412char*bp;24132414 bp =find_beginning_of_line(buf, scanp);24152416if(*bp =='\n') {2417/*2418 * The newline is the end of the previous line,2419 * so we know we have complete line starting2420 * at (bp + 1). Prefix it onto any prior data2421 * we collected for the line and process it.2422 */2423strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2424 scanp = bp;2425 endp = bp +1;2426 ret =show_one_reflog_ent(&sb, fn, cb_data);2427strbuf_reset(&sb);2428if(ret)2429break;2430}else if(!pos) {2431/*2432 * We are at the start of the buffer, and the2433 * start of the file; there is no previous2434 * line, and we have everything for this one.2435 * Process it, and we can end the loop.2436 */2437strbuf_splice(&sb,0,0, buf, endp - buf);2438 ret =show_one_reflog_ent(&sb, fn, cb_data);2439strbuf_reset(&sb);2440break;2441}24422443if(bp == buf) {2444/*2445 * We are at the start of the buffer, and there2446 * is more file to read backwards. Which means2447 * we are in the middle of a line. Note that we2448 * may get here even if *bp was a newline; that2449 * just means we are at the exact end of the2450 * previous line, rather than some spot in the2451 * middle.2452 *2453 * Save away what we have to be combined with2454 * the data from the next read.2455 */2456strbuf_splice(&sb,0,0, buf, endp - buf);2457break;2458}2459}24602461}2462if(!ret && sb.len)2463die("BUG: reverse reflog parser had leftover data");24642465fclose(logfp);2466strbuf_release(&sb);2467return ret;2468}24692470static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2471const char*refname,2472 each_reflog_ent_fn fn,void*cb_data)2473{2474struct files_ref_store *refs =2475files_downcast(ref_store, REF_STORE_READ,2476"for_each_reflog_ent");2477FILE*logfp;2478struct strbuf sb = STRBUF_INIT;2479int ret =0;24802481files_reflog_path(refs, &sb, refname);2482 logfp =fopen(sb.buf,"r");2483strbuf_release(&sb);2484if(!logfp)2485return-1;24862487while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2488 ret =show_one_reflog_ent(&sb, fn, cb_data);2489fclose(logfp);2490strbuf_release(&sb);2491return ret;2492}24932494struct files_reflog_iterator {2495struct ref_iterator base;24962497struct ref_store *ref_store;2498struct dir_iterator *dir_iterator;2499struct object_id oid;2500};25012502static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2503{2504struct files_reflog_iterator *iter =2505(struct files_reflog_iterator *)ref_iterator;2506struct dir_iterator *diter = iter->dir_iterator;2507int ok;25082509while((ok =dir_iterator_advance(diter)) == ITER_OK) {2510int flags;25112512if(!S_ISREG(diter->st.st_mode))2513continue;2514if(diter->basename[0] =='.')2515continue;2516if(ends_with(diter->basename,".lock"))2517continue;25182519if(refs_read_ref_full(iter->ref_store,2520 diter->relative_path,0,2521 iter->oid.hash, &flags)) {2522error("bad ref for%s", diter->path.buf);2523continue;2524}25252526 iter->base.refname = diter->relative_path;2527 iter->base.oid = &iter->oid;2528 iter->base.flags = flags;2529return ITER_OK;2530}25312532 iter->dir_iterator = NULL;2533if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2534 ok = ITER_ERROR;2535return ok;2536}25372538static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2539struct object_id *peeled)2540{2541die("BUG: ref_iterator_peel() called for reflog_iterator");2542}25432544static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2545{2546struct files_reflog_iterator *iter =2547(struct files_reflog_iterator *)ref_iterator;2548int ok = ITER_DONE;25492550if(iter->dir_iterator)2551 ok =dir_iterator_abort(iter->dir_iterator);25522553base_ref_iterator_free(ref_iterator);2554return ok;2555}25562557static struct ref_iterator_vtable files_reflog_iterator_vtable = {2558 files_reflog_iterator_advance,2559 files_reflog_iterator_peel,2560 files_reflog_iterator_abort2561};25622563static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2564{2565struct files_ref_store *refs =2566files_downcast(ref_store, REF_STORE_READ,2567"reflog_iterator_begin");2568struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2569struct ref_iterator *ref_iterator = &iter->base;2570struct strbuf sb = STRBUF_INIT;25712572base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2573files_reflog_path(refs, &sb, NULL);2574 iter->dir_iterator =dir_iterator_begin(sb.buf);2575 iter->ref_store = ref_store;2576strbuf_release(&sb);2577return ref_iterator;2578}25792580static intref_update_reject_duplicates(struct string_list *refnames,2581struct strbuf *err)2582{2583int i, n = refnames->nr;25842585assert(err);25862587for(i =1; i < n; i++)2588if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2589strbuf_addf(err,2590"multiple updates for ref '%s' not allowed.",2591 refnames->items[i].string);2592return1;2593}2594return0;2595}25962597/*2598 * If update is a direct update of head_ref (the reference pointed to2599 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2600 */2601static intsplit_head_update(struct ref_update *update,2602struct ref_transaction *transaction,2603const char*head_ref,2604struct string_list *affected_refnames,2605struct strbuf *err)2606{2607struct string_list_item *item;2608struct ref_update *new_update;26092610if((update->flags & REF_LOG_ONLY) ||2611(update->flags & REF_ISPRUNING) ||2612(update->flags & REF_UPDATE_VIA_HEAD))2613return0;26142615if(strcmp(update->refname, head_ref))2616return0;26172618/*2619 * First make sure that HEAD is not already in the2620 * transaction. This insertion is O(N) in the transaction2621 * size, but it happens at most once per transaction.2622 */2623 item =string_list_insert(affected_refnames,"HEAD");2624if(item->util) {2625/* An entry already existed */2626strbuf_addf(err,2627"multiple updates for 'HEAD' (including one "2628"via its referent '%s') are not allowed",2629 update->refname);2630return TRANSACTION_NAME_CONFLICT;2631}26322633 new_update =ref_transaction_add_update(2634 transaction,"HEAD",2635 update->flags | REF_LOG_ONLY | REF_NODEREF,2636 update->new_sha1, update->old_sha1,2637 update->msg);26382639 item->util = new_update;26402641return0;2642}26432644/*2645 * update is for a symref that points at referent and doesn't have2646 * REF_NODEREF set. Split it into two updates:2647 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2648 * - A new, separate update for the referent reference2649 * Note that the new update will itself be subject to splitting when2650 * the iteration gets to it.2651 */2652static intsplit_symref_update(struct files_ref_store *refs,2653struct ref_update *update,2654const char*referent,2655struct ref_transaction *transaction,2656struct string_list *affected_refnames,2657struct strbuf *err)2658{2659struct string_list_item *item;2660struct ref_update *new_update;2661unsigned int new_flags;26622663/*2664 * First make sure that referent is not already in the2665 * transaction. This insertion is O(N) in the transaction2666 * size, but it happens at most once per symref in a2667 * transaction.2668 */2669 item =string_list_insert(affected_refnames, referent);2670if(item->util) {2671/* An entry already existed */2672strbuf_addf(err,2673"multiple updates for '%s' (including one "2674"via symref '%s') are not allowed",2675 referent, update->refname);2676return TRANSACTION_NAME_CONFLICT;2677}26782679 new_flags = update->flags;2680if(!strcmp(update->refname,"HEAD")) {2681/*2682 * Record that the new update came via HEAD, so that2683 * when we process it, split_head_update() doesn't try2684 * to add another reflog update for HEAD. Note that2685 * this bit will be propagated if the new_update2686 * itself needs to be split.2687 */2688 new_flags |= REF_UPDATE_VIA_HEAD;2689}26902691 new_update =ref_transaction_add_update(2692 transaction, referent, new_flags,2693 update->new_sha1, update->old_sha1,2694 update->msg);26952696 new_update->parent_update = update;26972698/*2699 * Change the symbolic ref update to log only. Also, it2700 * doesn't need to check its old SHA-1 value, as that will be2701 * done when new_update is processed.2702 */2703 update->flags |= REF_LOG_ONLY | REF_NODEREF;2704 update->flags &= ~REF_HAVE_OLD;27052706 item->util = new_update;27072708return0;2709}27102711/*2712 * Return the refname under which update was originally requested.2713 */2714static const char*original_update_refname(struct ref_update *update)2715{2716while(update->parent_update)2717 update = update->parent_update;27182719return update->refname;2720}27212722/*2723 * Check whether the REF_HAVE_OLD and old_oid values stored in update2724 * are consistent with oid, which is the reference's current value. If2725 * everything is OK, return 0; otherwise, write an error message to2726 * err and return -1.2727 */2728static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2729struct strbuf *err)2730{2731if(!(update->flags & REF_HAVE_OLD) ||2732!hashcmp(oid->hash, update->old_sha1))2733return0;27342735if(is_null_sha1(update->old_sha1))2736strbuf_addf(err,"cannot lock ref '%s': "2737"reference already exists",2738original_update_refname(update));2739else if(is_null_oid(oid))2740strbuf_addf(err,"cannot lock ref '%s': "2741"reference is missing but expected%s",2742original_update_refname(update),2743sha1_to_hex(update->old_sha1));2744else2745strbuf_addf(err,"cannot lock ref '%s': "2746"is at%sbut expected%s",2747original_update_refname(update),2748oid_to_hex(oid),2749sha1_to_hex(update->old_sha1));27502751return-1;2752}27532754/*2755 * Prepare for carrying out update:2756 * - Lock the reference referred to by update.2757 * - Read the reference under lock.2758 * - Check that its old SHA-1 value (if specified) is correct, and in2759 * any case record it in update->lock->old_oid for later use when2760 * writing the reflog.2761 * - If it is a symref update without REF_NODEREF, split it up into a2762 * REF_LOG_ONLY update of the symref and add a separate update for2763 * the referent to transaction.2764 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2765 * update of HEAD.2766 */2767static intlock_ref_for_update(struct files_ref_store *refs,2768struct ref_update *update,2769struct ref_transaction *transaction,2770const char*head_ref,2771struct string_list *affected_refnames,2772struct strbuf *err)2773{2774struct strbuf referent = STRBUF_INIT;2775int mustexist = (update->flags & REF_HAVE_OLD) &&2776!is_null_sha1(update->old_sha1);2777int ret;2778struct ref_lock *lock;27792780files_assert_main_repository(refs,"lock_ref_for_update");27812782if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))2783 update->flags |= REF_DELETING;27842785if(head_ref) {2786 ret =split_head_update(update, transaction, head_ref,2787 affected_refnames, err);2788if(ret)2789return ret;2790}27912792 ret =lock_raw_ref(refs, update->refname, mustexist,2793 affected_refnames, NULL,2794&lock, &referent,2795&update->type, err);2796if(ret) {2797char*reason;27982799 reason =strbuf_detach(err, NULL);2800strbuf_addf(err,"cannot lock ref '%s':%s",2801original_update_refname(update), reason);2802free(reason);2803return ret;2804}28052806 update->backend_data = lock;28072808if(update->type & REF_ISSYMREF) {2809if(update->flags & REF_NODEREF) {2810/*2811 * We won't be reading the referent as part of2812 * the transaction, so we have to read it here2813 * to record and possibly check old_sha1:2814 */2815if(refs_read_ref_full(&refs->base,2816 referent.buf,0,2817 lock->old_oid.hash, NULL)) {2818if(update->flags & REF_HAVE_OLD) {2819strbuf_addf(err,"cannot lock ref '%s': "2820"error reading reference",2821original_update_refname(update));2822return-1;2823}2824}else if(check_old_oid(update, &lock->old_oid, err)) {2825return TRANSACTION_GENERIC_ERROR;2826}2827}else{2828/*2829 * Create a new update for the reference this2830 * symref is pointing at. Also, we will record2831 * and verify old_sha1 for this update as part2832 * of processing the split-off update, so we2833 * don't have to do it here.2834 */2835 ret =split_symref_update(refs, update,2836 referent.buf, transaction,2837 affected_refnames, err);2838if(ret)2839return ret;2840}2841}else{2842struct ref_update *parent_update;28432844if(check_old_oid(update, &lock->old_oid, err))2845return TRANSACTION_GENERIC_ERROR;28462847/*2848 * If this update is happening indirectly because of a2849 * symref update, record the old SHA-1 in the parent2850 * update:2851 */2852for(parent_update = update->parent_update;2853 parent_update;2854 parent_update = parent_update->parent_update) {2855struct ref_lock *parent_lock = parent_update->backend_data;2856oidcpy(&parent_lock->old_oid, &lock->old_oid);2857}2858}28592860if((update->flags & REF_HAVE_NEW) &&2861!(update->flags & REF_DELETING) &&2862!(update->flags & REF_LOG_ONLY)) {2863if(!(update->type & REF_ISSYMREF) &&2864!hashcmp(lock->old_oid.hash, update->new_sha1)) {2865/*2866 * The reference already has the desired2867 * value, so we don't need to write it.2868 */2869}else if(write_ref_to_lockfile(lock, update->new_sha1,2870 err)) {2871char*write_err =strbuf_detach(err, NULL);28722873/*2874 * The lock was freed upon failure of2875 * write_ref_to_lockfile():2876 */2877 update->backend_data = NULL;2878strbuf_addf(err,2879"cannot update ref '%s':%s",2880 update->refname, write_err);2881free(write_err);2882return TRANSACTION_GENERIC_ERROR;2883}else{2884 update->flags |= REF_NEEDS_COMMIT;2885}2886}2887if(!(update->flags & REF_NEEDS_COMMIT)) {2888/*2889 * We didn't call write_ref_to_lockfile(), so2890 * the lockfile is still open. Close it to2891 * free up the file descriptor:2892 */2893if(close_ref(lock)) {2894strbuf_addf(err,"couldn't close '%s.lock'",2895 update->refname);2896return TRANSACTION_GENERIC_ERROR;2897}2898}2899return0;2900}29012902static intfiles_transaction_commit(struct ref_store *ref_store,2903struct ref_transaction *transaction,2904struct strbuf *err)2905{2906struct files_ref_store *refs =2907files_downcast(ref_store, REF_STORE_WRITE,2908"ref_transaction_commit");2909int ret =0, i;2910struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2911struct string_list_item *ref_to_delete;2912struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2913char*head_ref = NULL;2914int head_type;2915struct object_id head_oid;2916struct strbuf sb = STRBUF_INIT;29172918assert(err);29192920if(transaction->state != REF_TRANSACTION_OPEN)2921die("BUG: commit called for transaction that is not open");29222923if(!transaction->nr) {2924 transaction->state = REF_TRANSACTION_CLOSED;2925return0;2926}29272928/*2929 * Fail if a refname appears more than once in the2930 * transaction. (If we end up splitting up any updates using2931 * split_symref_update() or split_head_update(), those2932 * functions will check that the new updates don't have the2933 * same refname as any existing ones.)2934 */2935for(i =0; i < transaction->nr; i++) {2936struct ref_update *update = transaction->updates[i];2937struct string_list_item *item =2938string_list_append(&affected_refnames, update->refname);29392940/*2941 * We store a pointer to update in item->util, but at2942 * the moment we never use the value of this field2943 * except to check whether it is non-NULL.2944 */2945 item->util = update;2946}2947string_list_sort(&affected_refnames);2948if(ref_update_reject_duplicates(&affected_refnames, err)) {2949 ret = TRANSACTION_GENERIC_ERROR;2950goto cleanup;2951}29522953/*2954 * Special hack: If a branch is updated directly and HEAD2955 * points to it (may happen on the remote side of a push2956 * for example) then logically the HEAD reflog should be2957 * updated too.2958 *2959 * A generic solution would require reverse symref lookups,2960 * but finding all symrefs pointing to a given branch would be2961 * rather costly for this rare event (the direct update of a2962 * branch) to be worth it. So let's cheat and check with HEAD2963 * only, which should cover 99% of all usage scenarios (even2964 * 100% of the default ones).2965 *2966 * So if HEAD is a symbolic reference, then record the name of2967 * the reference that it points to. If we see an update of2968 * head_ref within the transaction, then split_head_update()2969 * arranges for the reflog of HEAD to be updated, too.2970 */2971 head_ref =refs_resolve_refdup(ref_store,"HEAD",2972 RESOLVE_REF_NO_RECURSE,2973 head_oid.hash, &head_type);29742975if(head_ref && !(head_type & REF_ISSYMREF)) {2976free(head_ref);2977 head_ref = NULL;2978}29792980/*2981 * Acquire all locks, verify old values if provided, check2982 * that new values are valid, and write new values to the2983 * lockfiles, ready to be activated. Only keep one lockfile2984 * open at a time to avoid running out of file descriptors.2985 */2986for(i =0; i < transaction->nr; i++) {2987struct ref_update *update = transaction->updates[i];29882989 ret =lock_ref_for_update(refs, update, transaction,2990 head_ref, &affected_refnames, err);2991if(ret)2992goto cleanup;2993}29942995/* Perform updates first so live commits remain referenced */2996for(i =0; i < transaction->nr; i++) {2997struct ref_update *update = transaction->updates[i];2998struct ref_lock *lock = update->backend_data;29993000if(update->flags & REF_NEEDS_COMMIT ||3001 update->flags & REF_LOG_ONLY) {3002if(files_log_ref_write(refs,3003 lock->ref_name,3004 lock->old_oid.hash,3005 update->new_sha1,3006 update->msg, update->flags,3007 err)) {3008char*old_msg =strbuf_detach(err, NULL);30093010strbuf_addf(err,"cannot update the ref '%s':%s",3011 lock->ref_name, old_msg);3012free(old_msg);3013unlock_ref(lock);3014 update->backend_data = NULL;3015 ret = TRANSACTION_GENERIC_ERROR;3016goto cleanup;3017}3018}3019if(update->flags & REF_NEEDS_COMMIT) {3020clear_loose_ref_cache(refs);3021if(commit_ref(lock)) {3022strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3023unlock_ref(lock);3024 update->backend_data = NULL;3025 ret = TRANSACTION_GENERIC_ERROR;3026goto cleanup;3027}3028}3029}3030/* Perform deletes now that updates are safely completed */3031for(i =0; i < transaction->nr; i++) {3032struct ref_update *update = transaction->updates[i];3033struct ref_lock *lock = update->backend_data;30343035if(update->flags & REF_DELETING &&3036!(update->flags & REF_LOG_ONLY)) {3037if(!(update->type & REF_ISPACKED) ||3038 update->type & REF_ISSYMREF) {3039/* It is a loose reference. */3040strbuf_reset(&sb);3041files_ref_path(refs, &sb, lock->ref_name);3042if(unlink_or_msg(sb.buf, err)) {3043 ret = TRANSACTION_GENERIC_ERROR;3044goto cleanup;3045}3046 update->flags |= REF_DELETED_LOOSE;3047}30483049if(!(update->flags & REF_ISPRUNING))3050string_list_append(&refs_to_delete,3051 lock->ref_name);3052}3053}30543055if(repack_without_refs(refs, &refs_to_delete, err)) {3056 ret = TRANSACTION_GENERIC_ERROR;3057goto cleanup;3058}30593060/* Delete the reflogs of any references that were deleted: */3061for_each_string_list_item(ref_to_delete, &refs_to_delete) {3062strbuf_reset(&sb);3063files_reflog_path(refs, &sb, ref_to_delete->string);3064if(!unlink_or_warn(sb.buf))3065try_remove_empty_parents(refs, ref_to_delete->string,3066 REMOVE_EMPTY_PARENTS_REFLOG);3067}30683069clear_loose_ref_cache(refs);30703071cleanup:3072strbuf_release(&sb);3073 transaction->state = REF_TRANSACTION_CLOSED;30743075for(i =0; i < transaction->nr; i++) {3076struct ref_update *update = transaction->updates[i];3077struct ref_lock *lock = update->backend_data;30783079if(lock)3080unlock_ref(lock);30813082if(update->flags & REF_DELETED_LOOSE) {3083/*3084 * The loose reference was deleted. Delete any3085 * empty parent directories. (Note that this3086 * can only work because we have already3087 * removed the lockfile.)3088 */3089try_remove_empty_parents(refs, update->refname,3090 REMOVE_EMPTY_PARENTS_REF);3091}3092}30933094string_list_clear(&refs_to_delete,0);3095free(head_ref);3096string_list_clear(&affected_refnames,0);30973098return ret;3099}31003101static intref_present(const char*refname,3102const struct object_id *oid,int flags,void*cb_data)3103{3104struct string_list *affected_refnames = cb_data;31053106returnstring_list_has_string(affected_refnames, refname);3107}31083109static intfiles_initial_transaction_commit(struct ref_store *ref_store,3110struct ref_transaction *transaction,3111struct strbuf *err)3112{3113struct files_ref_store *refs =3114files_downcast(ref_store, REF_STORE_WRITE,3115"initial_ref_transaction_commit");3116int ret =0, i;3117struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31183119assert(err);31203121if(transaction->state != REF_TRANSACTION_OPEN)3122die("BUG: commit called for transaction that is not open");31233124/* Fail if a refname appears more than once in the transaction: */3125for(i =0; i < transaction->nr; i++)3126string_list_append(&affected_refnames,3127 transaction->updates[i]->refname);3128string_list_sort(&affected_refnames);3129if(ref_update_reject_duplicates(&affected_refnames, err)) {3130 ret = TRANSACTION_GENERIC_ERROR;3131goto cleanup;3132}31333134/*3135 * It's really undefined to call this function in an active3136 * repository or when there are existing references: we are3137 * only locking and changing packed-refs, so (1) any3138 * simultaneous processes might try to change a reference at3139 * the same time we do, and (2) any existing loose versions of3140 * the references that we are setting would have precedence3141 * over our values. But some remote helpers create the remote3142 * "HEAD" and "master" branches before calling this function,3143 * so here we really only check that none of the references3144 * that we are creating already exists.3145 */3146if(refs_for_each_rawref(&refs->base, ref_present,3147&affected_refnames))3148die("BUG: initial ref transaction called with existing refs");31493150for(i =0; i < transaction->nr; i++) {3151struct ref_update *update = transaction->updates[i];31523153if((update->flags & REF_HAVE_OLD) &&3154!is_null_sha1(update->old_sha1))3155die("BUG: initial ref transaction with old_sha1 set");3156if(refs_verify_refname_available(&refs->base, update->refname,3157&affected_refnames, NULL,3158 err)) {3159 ret = TRANSACTION_NAME_CONFLICT;3160goto cleanup;3161}3162}31633164if(lock_packed_refs(refs,0)) {3165strbuf_addf(err,"unable to lock packed-refs file:%s",3166strerror(errno));3167 ret = TRANSACTION_GENERIC_ERROR;3168goto cleanup;3169}31703171for(i =0; i < transaction->nr; i++) {3172struct ref_update *update = transaction->updates[i];31733174if((update->flags & REF_HAVE_NEW) &&3175!is_null_sha1(update->new_sha1))3176add_packed_ref(refs, update->refname, update->new_sha1);3177}31783179if(commit_packed_refs(refs)) {3180strbuf_addf(err,"unable to commit packed-refs file:%s",3181strerror(errno));3182 ret = TRANSACTION_GENERIC_ERROR;3183goto cleanup;3184}31853186cleanup:3187 transaction->state = REF_TRANSACTION_CLOSED;3188string_list_clear(&affected_refnames,0);3189return ret;3190}31913192struct expire_reflog_cb {3193unsigned int flags;3194 reflog_expiry_should_prune_fn *should_prune_fn;3195void*policy_cb;3196FILE*newlog;3197struct object_id last_kept_oid;3198};31993200static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3201const char*email,unsigned long timestamp,int tz,3202const char*message,void*cb_data)3203{3204struct expire_reflog_cb *cb = cb_data;3205struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32063207if(cb->flags & EXPIRE_REFLOGS_REWRITE)3208 ooid = &cb->last_kept_oid;32093210if((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,3211 message, policy_cb)) {3212if(!cb->newlog)3213printf("would prune%s", message);3214else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3215printf("prune%s", message);3216}else{3217if(cb->newlog) {3218fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3219oid_to_hex(ooid),oid_to_hex(noid),3220 email, timestamp, tz, message);3221oidcpy(&cb->last_kept_oid, noid);3222}3223if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3224printf("keep%s", message);3225}3226return0;3227}32283229static intfiles_reflog_expire(struct ref_store *ref_store,3230const char*refname,const unsigned char*sha1,3231unsigned int flags,3232 reflog_expiry_prepare_fn prepare_fn,3233 reflog_expiry_should_prune_fn should_prune_fn,3234 reflog_expiry_cleanup_fn cleanup_fn,3235void*policy_cb_data)3236{3237struct files_ref_store *refs =3238files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3239static struct lock_file reflog_lock;3240struct expire_reflog_cb cb;3241struct ref_lock *lock;3242struct strbuf log_file_sb = STRBUF_INIT;3243char*log_file;3244int status =0;3245int type;3246struct strbuf err = STRBUF_INIT;32473248memset(&cb,0,sizeof(cb));3249 cb.flags = flags;3250 cb.policy_cb = policy_cb_data;3251 cb.should_prune_fn = should_prune_fn;32523253/*3254 * The reflog file is locked by holding the lock on the3255 * reference itself, plus we might need to update the3256 * reference if --updateref was specified:3257 */3258 lock =lock_ref_sha1_basic(refs, refname, sha1,3259 NULL, NULL, REF_NODEREF,3260&type, &err);3261if(!lock) {3262error("cannot lock ref '%s':%s", refname, err.buf);3263strbuf_release(&err);3264return-1;3265}3266if(!refs_reflog_exists(ref_store, refname)) {3267unlock_ref(lock);3268return0;3269}32703271files_reflog_path(refs, &log_file_sb, refname);3272 log_file =strbuf_detach(&log_file_sb, NULL);3273if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3274/*3275 * Even though holding $GIT_DIR/logs/$reflog.lock has3276 * no locking implications, we use the lock_file3277 * machinery here anyway because it does a lot of the3278 * work we need, including cleaning up if the program3279 * exits unexpectedly.3280 */3281if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3282struct strbuf err = STRBUF_INIT;3283unable_to_lock_message(log_file, errno, &err);3284error("%s", err.buf);3285strbuf_release(&err);3286goto failure;3287}3288 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3289if(!cb.newlog) {3290error("cannot fdopen%s(%s)",3291get_lock_file_path(&reflog_lock),strerror(errno));3292goto failure;3293}3294}32953296(*prepare_fn)(refname, sha1, cb.policy_cb);3297refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3298(*cleanup_fn)(cb.policy_cb);32993300if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3301/*3302 * It doesn't make sense to adjust a reference pointed3303 * to by a symbolic ref based on expiring entries in3304 * the symbolic reference's reflog. Nor can we update3305 * a reference if there are no remaining reflog3306 * entries.3307 */3308int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3309!(type & REF_ISSYMREF) &&3310!is_null_oid(&cb.last_kept_oid);33113312if(close_lock_file(&reflog_lock)) {3313 status |=error("couldn't write%s:%s", log_file,3314strerror(errno));3315}else if(update &&3316(write_in_full(get_lock_file_fd(lock->lk),3317oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3318write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3319close_ref(lock) <0)) {3320 status |=error("couldn't write%s",3321get_lock_file_path(lock->lk));3322rollback_lock_file(&reflog_lock);3323}else if(commit_lock_file(&reflog_lock)) {3324 status |=error("unable to write reflog '%s' (%s)",3325 log_file,strerror(errno));3326}else if(update &&commit_ref(lock)) {3327 status |=error("couldn't set%s", lock->ref_name);3328}3329}3330free(log_file);3331unlock_ref(lock);3332return status;33333334 failure:3335rollback_lock_file(&reflog_lock);3336free(log_file);3337unlock_ref(lock);3338return-1;3339}33403341static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3342{3343struct files_ref_store *refs =3344files_downcast(ref_store, REF_STORE_WRITE,"init_db");3345struct strbuf sb = STRBUF_INIT;33463347/*3348 * Create .git/refs/{heads,tags}3349 */3350files_ref_path(refs, &sb,"refs/heads");3351safe_create_dir(sb.buf,1);33523353strbuf_reset(&sb);3354files_ref_path(refs, &sb,"refs/tags");3355safe_create_dir(sb.buf,1);33563357strbuf_release(&sb);3358return0;3359}33603361struct ref_storage_be refs_be_files = {3362 NULL,3363"files",3364 files_ref_store_create,3365 files_init_db,3366 files_transaction_commit,3367 files_initial_transaction_commit,33683369 files_pack_refs,3370 files_peel_ref,3371 files_create_symref,3372 files_delete_refs,3373 files_rename_ref,33743375 files_ref_iterator_begin,3376 files_read_raw_ref,33773378 files_reflog_iterator_begin,3379 files_for_each_reflog_ent,3380 files_for_each_reflog_ent_reverse,3381 files_reflog_exists,3382 files_create_reflog,3383 files_delete_reflog,3384 files_reflog_expire3385};