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/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * Future: need to be in "struct repository" 52 * when doing a full libification. 53 */ 54struct files_ref_store { 55struct ref_store base; 56unsigned int store_flags; 57 58char*gitdir; 59char*gitcommondir; 60char*packed_refs_path; 61 62struct ref_cache *loose; 63struct packed_ref_cache *packed; 64 65/* 66 * Lock used for the "packed-refs" file. Note that this (and 67 * thus the enclosing `files_ref_store`) must not be freed. 68 */ 69struct lock_file packed_refs_lock; 70}; 71 72/* 73 * Increment the reference count of *packed_refs. 74 */ 75static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 76{ 77 packed_refs->referrers++; 78} 79 80/* 81 * Decrease the reference count of *packed_refs. If it goes to zero, 82 * free *packed_refs and return true; otherwise return false. 83 */ 84static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 85{ 86if(!--packed_refs->referrers) { 87free_ref_cache(packed_refs->cache); 88stat_validity_clear(&packed_refs->validity); 89free(packed_refs); 90return1; 91}else{ 92return0; 93} 94} 95 96static voidclear_packed_ref_cache(struct files_ref_store *refs) 97{ 98if(refs->packed) { 99struct packed_ref_cache *packed_refs = refs->packed; 100 101if(is_lock_file_locked(&refs->packed_refs_lock)) 102die("BUG: packed-ref cache cleared while locked"); 103 refs->packed = NULL; 104release_packed_ref_cache(packed_refs); 105} 106} 107 108static voidclear_loose_ref_cache(struct files_ref_store *refs) 109{ 110if(refs->loose) { 111free_ref_cache(refs->loose); 112 refs->loose = NULL; 113} 114} 115 116/* 117 * Create a new submodule ref cache and add it to the internal 118 * set of caches. 119 */ 120static struct ref_store *files_ref_store_create(const char*gitdir, 121unsigned int flags) 122{ 123struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 124struct ref_store *ref_store = (struct ref_store *)refs; 125struct strbuf sb = STRBUF_INIT; 126 127base_ref_store_init(ref_store, &refs_be_files); 128 refs->store_flags = flags; 129 130 refs->gitdir =xstrdup(gitdir); 131get_common_dir_noenv(&sb, gitdir); 132 refs->gitcommondir =strbuf_detach(&sb, NULL); 133strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 134 refs->packed_refs_path =strbuf_detach(&sb, NULL); 135 136return ref_store; 137} 138 139/* 140 * Die if refs is not the main ref store. caller is used in any 141 * necessary error messages. 142 */ 143static voidfiles_assert_main_repository(struct files_ref_store *refs, 144const char*caller) 145{ 146if(refs->store_flags & REF_STORE_MAIN) 147return; 148 149die("BUG: operation%sonly allowed for main ref store", caller); 150} 151 152/* 153 * Downcast ref_store to files_ref_store. Die if ref_store is not a 154 * files_ref_store. required_flags is compared with ref_store's 155 * store_flags to ensure the ref_store has all required capabilities. 156 * "caller" is used in any necessary error messages. 157 */ 158static struct files_ref_store *files_downcast(struct ref_store *ref_store, 159unsigned int required_flags, 160const char*caller) 161{ 162struct files_ref_store *refs; 163 164if(ref_store->be != &refs_be_files) 165die("BUG: ref_store is type\"%s\"not\"files\"in%s", 166 ref_store->be->name, caller); 167 168 refs = (struct files_ref_store *)ref_store; 169 170if((refs->store_flags & required_flags) != required_flags) 171die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 172 caller, required_flags, refs->store_flags); 173 174return refs; 175} 176 177/* The length of a peeled reference line in packed-refs, including EOL: */ 178#define PEELED_LINE_LENGTH 42 179 180/* 181 * The packed-refs header line that we write out. Perhaps other 182 * traits will be added later. The trailing space is required. 183 */ 184static const char PACKED_REFS_HEADER[] = 185"# pack-refs with: peeled fully-peeled\n"; 186 187/* 188 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 189 * Return a pointer to the refname within the line (null-terminated), 190 * or NULL if there was a problem. 191 */ 192static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 193{ 194const char*ref; 195 196if(parse_oid_hex(line->buf, oid, &ref) <0) 197return NULL; 198if(!isspace(*ref++)) 199return NULL; 200 201if(isspace(*ref)) 202return NULL; 203 204if(line->buf[line->len -1] !='\n') 205return NULL; 206 line->buf[--line->len] =0; 207 208return ref; 209} 210 211/* 212 * Read from `packed_refs_file` into a newly-allocated 213 * `packed_ref_cache` and return it. The return value will already 214 * have its reference count incremented. 215 * 216 * A comment line of the form "# pack-refs with: " may contain zero or 217 * more traits. We interpret the traits as follows: 218 * 219 * No traits: 220 * 221 * Probably no references are peeled. But if the file contains a 222 * peeled value for a reference, we will use it. 223 * 224 * peeled: 225 * 226 * References under "refs/tags/", if they *can* be peeled, *are* 227 * peeled in this file. References outside of "refs/tags/" are 228 * probably not peeled even if they could have been, but if we find 229 * a peeled value for such a reference we will use it. 230 * 231 * fully-peeled: 232 * 233 * All references in the file that can be peeled are peeled. 234 * Inversely (and this is more important), any references in the 235 * file for which no peeled value is recorded is not peelable. This 236 * trait should typically be written alongside "peeled" for 237 * compatibility with older clients, but we do not require it 238 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 239 */ 240static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 241{ 242FILE*f; 243struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 244struct ref_entry *last = NULL; 245struct strbuf line = STRBUF_INIT; 246enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 247struct ref_dir *dir; 248 249acquire_packed_ref_cache(packed_refs); 250 packed_refs->cache =create_ref_cache(NULL, NULL); 251 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 252 253 f =fopen(packed_refs_file,"r"); 254if(!f) { 255if(errno == ENOENT) { 256/* 257 * This is OK; it just means that no 258 * "packed-refs" file has been written yet, 259 * which is equivalent to it being empty. 260 */ 261return packed_refs; 262}else{ 263die_errno("couldn't read%s", packed_refs_file); 264} 265} 266 267stat_validity_update(&packed_refs->validity,fileno(f)); 268 269 dir =get_ref_dir(packed_refs->cache->root); 270while(strbuf_getwholeline(&line, f,'\n') != EOF) { 271struct object_id oid; 272const char*refname; 273const char*traits; 274 275if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 276if(strstr(traits," fully-peeled ")) 277 peeled = PEELED_FULLY; 278else if(strstr(traits," peeled ")) 279 peeled = PEELED_TAGS; 280/* perhaps other traits later as well */ 281continue; 282} 283 284 refname =parse_ref_line(&line, &oid); 285if(refname) { 286int flag = REF_ISPACKED; 287 288if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 289if(!refname_is_safe(refname)) 290die("packed refname is dangerous:%s", refname); 291oidclr(&oid); 292 flag |= REF_BAD_NAME | REF_ISBROKEN; 293} 294 last =create_ref_entry(refname, &oid, flag); 295if(peeled == PEELED_FULLY || 296(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 297 last->flag |= REF_KNOWS_PEELED; 298add_ref_entry(dir, last); 299continue; 300} 301if(last && 302 line.buf[0] =='^'&& 303 line.len == PEELED_LINE_LENGTH && 304 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 305!get_oid_hex(line.buf +1, &oid)) { 306oidcpy(&last->u.value.peeled, &oid); 307/* 308 * Regardless of what the file header said, 309 * we definitely know the value of *this* 310 * reference: 311 */ 312 last->flag |= REF_KNOWS_PEELED; 313} 314} 315 316fclose(f); 317strbuf_release(&line); 318 319return packed_refs; 320} 321 322static const char*files_packed_refs_path(struct files_ref_store *refs) 323{ 324return refs->packed_refs_path; 325} 326 327static voidfiles_reflog_path(struct files_ref_store *refs, 328struct strbuf *sb, 329const char*refname) 330{ 331if(!refname) { 332/* 333 * FIXME: of course this is wrong in multi worktree 334 * setting. To be fixed real soon. 335 */ 336strbuf_addf(sb,"%s/logs", refs->gitcommondir); 337return; 338} 339 340switch(ref_type(refname)) { 341case REF_TYPE_PER_WORKTREE: 342case REF_TYPE_PSEUDOREF: 343strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 344break; 345case REF_TYPE_NORMAL: 346strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 347break; 348default: 349die("BUG: unknown ref type%dof ref%s", 350ref_type(refname), refname); 351} 352} 353 354static voidfiles_ref_path(struct files_ref_store *refs, 355struct strbuf *sb, 356const char*refname) 357{ 358switch(ref_type(refname)) { 359case REF_TYPE_PER_WORKTREE: 360case REF_TYPE_PSEUDOREF: 361strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 362break; 363case REF_TYPE_NORMAL: 364strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 365break; 366default: 367die("BUG: unknown ref type%dof ref%s", 368ref_type(refname), refname); 369} 370} 371 372/* 373 * Check that the packed refs cache (if any) still reflects the 374 * contents of the file. If not, clear the cache. 375 */ 376static voidvalidate_packed_ref_cache(struct files_ref_store *refs) 377{ 378if(refs->packed && 379!stat_validity_check(&refs->packed->validity, 380files_packed_refs_path(refs))) 381clear_packed_ref_cache(refs); 382} 383 384/* 385 * Get the packed_ref_cache for the specified files_ref_store, 386 * creating and populating it if it hasn't been read before or if the 387 * file has been changed (according to its `validity` field) since it 388 * was last read. On the other hand, if we hold the lock, then assume 389 * that the file hasn't been changed out from under us, so skip the 390 * extra `stat()` call in `stat_validity_check()`. 391 */ 392static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 393{ 394const char*packed_refs_file =files_packed_refs_path(refs); 395 396if(!is_lock_file_locked(&refs->packed_refs_lock)) 397validate_packed_ref_cache(refs); 398 399if(!refs->packed) 400 refs->packed =read_packed_refs(packed_refs_file); 401 402return refs->packed; 403} 404 405static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 406{ 407returnget_ref_dir(packed_ref_cache->cache->root); 408} 409 410static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 411{ 412returnget_packed_ref_dir(get_packed_ref_cache(refs)); 413} 414 415/* 416 * Add or overwrite a reference in the in-memory packed reference 417 * cache. This may only be called while the packed-refs file is locked 418 * (see lock_packed_refs()). To actually write the packed-refs file, 419 * call commit_packed_refs(). 420 */ 421static voidadd_packed_ref(struct files_ref_store *refs, 422const char*refname,const struct object_id *oid) 423{ 424struct ref_dir *packed_refs; 425struct ref_entry *packed_entry; 426 427if(!is_lock_file_locked(&refs->packed_refs_lock)) 428die("BUG: packed refs not locked"); 429 430if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 431die("Reference has invalid format: '%s'", refname); 432 433 packed_refs =get_packed_refs(refs); 434 packed_entry =find_ref_entry(packed_refs, refname); 435if(packed_entry) { 436/* Overwrite the existing entry: */ 437oidcpy(&packed_entry->u.value.oid, oid); 438 packed_entry->flag = REF_ISPACKED; 439oidclr(&packed_entry->u.value.peeled); 440}else{ 441 packed_entry =create_ref_entry(refname, oid, REF_ISPACKED); 442add_ref_entry(packed_refs, packed_entry); 443} 444} 445 446/* 447 * Read the loose references from the namespace dirname into dir 448 * (without recursing). dirname must end with '/'. dir must be the 449 * directory entry corresponding to dirname. 450 */ 451static voidloose_fill_ref_dir(struct ref_store *ref_store, 452struct ref_dir *dir,const char*dirname) 453{ 454struct files_ref_store *refs = 455files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 456DIR*d; 457struct dirent *de; 458int dirnamelen =strlen(dirname); 459struct strbuf refname; 460struct strbuf path = STRBUF_INIT; 461size_t path_baselen; 462 463files_ref_path(refs, &path, dirname); 464 path_baselen = path.len; 465 466 d =opendir(path.buf); 467if(!d) { 468strbuf_release(&path); 469return; 470} 471 472strbuf_init(&refname, dirnamelen +257); 473strbuf_add(&refname, dirname, dirnamelen); 474 475while((de =readdir(d)) != NULL) { 476struct object_id oid; 477struct stat st; 478int flag; 479 480if(de->d_name[0] =='.') 481continue; 482if(ends_with(de->d_name,".lock")) 483continue; 484strbuf_addstr(&refname, de->d_name); 485strbuf_addstr(&path, de->d_name); 486if(stat(path.buf, &st) <0) { 487;/* silently ignore */ 488}else if(S_ISDIR(st.st_mode)) { 489strbuf_addch(&refname,'/'); 490add_entry_to_dir(dir, 491create_dir_entry(dir->cache, refname.buf, 492 refname.len,1)); 493}else{ 494if(!refs_resolve_ref_unsafe(&refs->base, 495 refname.buf, 496 RESOLVE_REF_READING, 497 oid.hash, &flag)) { 498oidclr(&oid); 499 flag |= REF_ISBROKEN; 500}else if(is_null_oid(&oid)) { 501/* 502 * It is so astronomically unlikely 503 * that NULL_SHA1 is the SHA-1 of an 504 * actual object that we consider its 505 * appearance in a loose reference 506 * file to be repo corruption 507 * (probably due to a software bug). 508 */ 509 flag |= REF_ISBROKEN; 510} 511 512if(check_refname_format(refname.buf, 513 REFNAME_ALLOW_ONELEVEL)) { 514if(!refname_is_safe(refname.buf)) 515die("loose refname is dangerous:%s", refname.buf); 516oidclr(&oid); 517 flag |= REF_BAD_NAME | REF_ISBROKEN; 518} 519add_entry_to_dir(dir, 520create_ref_entry(refname.buf, &oid, flag)); 521} 522strbuf_setlen(&refname, dirnamelen); 523strbuf_setlen(&path, path_baselen); 524} 525strbuf_release(&refname); 526strbuf_release(&path); 527closedir(d); 528 529/* 530 * Manually add refs/bisect, which, being per-worktree, might 531 * not appear in the directory listing for refs/ in the main 532 * repo. 533 */ 534if(!strcmp(dirname,"refs/")) { 535int pos =search_ref_dir(dir,"refs/bisect/",12); 536 537if(pos <0) { 538struct ref_entry *child_entry =create_dir_entry( 539 dir->cache,"refs/bisect/",12,1); 540add_entry_to_dir(dir, child_entry); 541} 542} 543} 544 545static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 546{ 547if(!refs->loose) { 548/* 549 * Mark the top-level directory complete because we 550 * are about to read the only subdirectory that can 551 * hold references: 552 */ 553 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 554 555/* We're going to fill the top level ourselves: */ 556 refs->loose->root->flag &= ~REF_INCOMPLETE; 557 558/* 559 * Add an incomplete entry for "refs/" (to be filled 560 * lazily): 561 */ 562add_entry_to_dir(get_ref_dir(refs->loose->root), 563create_dir_entry(refs->loose,"refs/",5,1)); 564} 565return refs->loose; 566} 567 568/* 569 * Return the ref_entry for the given refname from the packed 570 * references. If it does not exist, return NULL. 571 */ 572static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 573const char*refname) 574{ 575returnfind_ref_entry(get_packed_refs(refs), refname); 576} 577 578/* 579 * A loose ref file doesn't exist; check for a packed ref. 580 */ 581static intresolve_packed_ref(struct files_ref_store *refs, 582const char*refname, 583unsigned char*sha1,unsigned int*flags) 584{ 585struct ref_entry *entry; 586 587/* 588 * The loose reference file does not exist; check for a packed 589 * reference. 590 */ 591 entry =get_packed_ref(refs, refname); 592if(entry) { 593hashcpy(sha1, entry->u.value.oid.hash); 594*flags |= REF_ISPACKED; 595return0; 596} 597/* refname is not a packed reference. */ 598return-1; 599} 600 601static intfiles_read_raw_ref(struct ref_store *ref_store, 602const char*refname,unsigned char*sha1, 603struct strbuf *referent,unsigned int*type) 604{ 605struct files_ref_store *refs = 606files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 607struct strbuf sb_contents = STRBUF_INIT; 608struct strbuf sb_path = STRBUF_INIT; 609const char*path; 610const char*buf; 611struct stat st; 612int fd; 613int ret = -1; 614int save_errno; 615int remaining_retries =3; 616 617*type =0; 618strbuf_reset(&sb_path); 619 620files_ref_path(refs, &sb_path, refname); 621 622 path = sb_path.buf; 623 624stat_ref: 625/* 626 * We might have to loop back here to avoid a race 627 * condition: first we lstat() the file, then we try 628 * to read it as a link or as a file. But if somebody 629 * changes the type of the file (file <-> directory 630 * <-> symlink) between the lstat() and reading, then 631 * we don't want to report that as an error but rather 632 * try again starting with the lstat(). 633 * 634 * We'll keep a count of the retries, though, just to avoid 635 * any confusing situation sending us into an infinite loop. 636 */ 637 638if(remaining_retries-- <=0) 639goto out; 640 641if(lstat(path, &st) <0) { 642if(errno != ENOENT) 643goto out; 644if(resolve_packed_ref(refs, refname, sha1, type)) { 645 errno = ENOENT; 646goto out; 647} 648 ret =0; 649goto out; 650} 651 652/* Follow "normalized" - ie "refs/.." symlinks by hand */ 653if(S_ISLNK(st.st_mode)) { 654strbuf_reset(&sb_contents); 655if(strbuf_readlink(&sb_contents, path,0) <0) { 656if(errno == ENOENT || errno == EINVAL) 657/* inconsistent with lstat; retry */ 658goto stat_ref; 659else 660goto out; 661} 662if(starts_with(sb_contents.buf,"refs/") && 663!check_refname_format(sb_contents.buf,0)) { 664strbuf_swap(&sb_contents, referent); 665*type |= REF_ISSYMREF; 666 ret =0; 667goto out; 668} 669/* 670 * It doesn't look like a refname; fall through to just 671 * treating it like a non-symlink, and reading whatever it 672 * points to. 673 */ 674} 675 676/* Is it a directory? */ 677if(S_ISDIR(st.st_mode)) { 678/* 679 * Even though there is a directory where the loose 680 * ref is supposed to be, there could still be a 681 * packed ref: 682 */ 683if(resolve_packed_ref(refs, refname, sha1, type)) { 684 errno = EISDIR; 685goto out; 686} 687 ret =0; 688goto out; 689} 690 691/* 692 * Anything else, just open it and try to use it as 693 * a ref 694 */ 695 fd =open(path, O_RDONLY); 696if(fd <0) { 697if(errno == ENOENT && !S_ISLNK(st.st_mode)) 698/* inconsistent with lstat; retry */ 699goto stat_ref; 700else 701goto out; 702} 703strbuf_reset(&sb_contents); 704if(strbuf_read(&sb_contents, fd,256) <0) { 705int save_errno = errno; 706close(fd); 707 errno = save_errno; 708goto out; 709} 710close(fd); 711strbuf_rtrim(&sb_contents); 712 buf = sb_contents.buf; 713if(starts_with(buf,"ref:")) { 714 buf +=4; 715while(isspace(*buf)) 716 buf++; 717 718strbuf_reset(referent); 719strbuf_addstr(referent, buf); 720*type |= REF_ISSYMREF; 721 ret =0; 722goto out; 723} 724 725/* 726 * Please note that FETCH_HEAD has additional 727 * data after the sha. 728 */ 729if(get_sha1_hex(buf, sha1) || 730(buf[40] !='\0'&& !isspace(buf[40]))) { 731*type |= REF_ISBROKEN; 732 errno = EINVAL; 733goto out; 734} 735 736 ret =0; 737 738out: 739 save_errno = errno; 740strbuf_release(&sb_path); 741strbuf_release(&sb_contents); 742 errno = save_errno; 743return ret; 744} 745 746static voidunlock_ref(struct ref_lock *lock) 747{ 748/* Do not free lock->lk -- atexit() still looks at them */ 749if(lock->lk) 750rollback_lock_file(lock->lk); 751free(lock->ref_name); 752free(lock); 753} 754 755/* 756 * Lock refname, without following symrefs, and set *lock_p to point 757 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 758 * and type similarly to read_raw_ref(). 759 * 760 * The caller must verify that refname is a "safe" reference name (in 761 * the sense of refname_is_safe()) before calling this function. 762 * 763 * If the reference doesn't already exist, verify that refname doesn't 764 * have a D/F conflict with any existing references. extras and skip 765 * are passed to refs_verify_refname_available() for this check. 766 * 767 * If mustexist is not set and the reference is not found or is 768 * broken, lock the reference anyway but clear sha1. 769 * 770 * Return 0 on success. On failure, write an error message to err and 771 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 772 * 773 * Implementation note: This function is basically 774 * 775 * lock reference 776 * read_raw_ref() 777 * 778 * but it includes a lot more code to 779 * - Deal with possible races with other processes 780 * - Avoid calling refs_verify_refname_available() when it can be 781 * avoided, namely if we were successfully able to read the ref 782 * - Generate informative error messages in the case of failure 783 */ 784static intlock_raw_ref(struct files_ref_store *refs, 785const char*refname,int mustexist, 786const struct string_list *extras, 787const struct string_list *skip, 788struct ref_lock **lock_p, 789struct strbuf *referent, 790unsigned int*type, 791struct strbuf *err) 792{ 793struct ref_lock *lock; 794struct strbuf ref_file = STRBUF_INIT; 795int attempts_remaining =3; 796int ret = TRANSACTION_GENERIC_ERROR; 797 798assert(err); 799files_assert_main_repository(refs,"lock_raw_ref"); 800 801*type =0; 802 803/* First lock the file so it can't change out from under us. */ 804 805*lock_p = lock =xcalloc(1,sizeof(*lock)); 806 807 lock->ref_name =xstrdup(refname); 808files_ref_path(refs, &ref_file, refname); 809 810retry: 811switch(safe_create_leading_directories(ref_file.buf)) { 812case SCLD_OK: 813break;/* success */ 814case SCLD_EXISTS: 815/* 816 * Suppose refname is "refs/foo/bar". We just failed 817 * to create the containing directory, "refs/foo", 818 * because there was a non-directory in the way. This 819 * indicates a D/F conflict, probably because of 820 * another reference such as "refs/foo". There is no 821 * reason to expect this error to be transitory. 822 */ 823if(refs_verify_refname_available(&refs->base, refname, 824 extras, skip, err)) { 825if(mustexist) { 826/* 827 * To the user the relevant error is 828 * that the "mustexist" reference is 829 * missing: 830 */ 831strbuf_reset(err); 832strbuf_addf(err,"unable to resolve reference '%s'", 833 refname); 834}else{ 835/* 836 * The error message set by 837 * refs_verify_refname_available() is 838 * OK. 839 */ 840 ret = TRANSACTION_NAME_CONFLICT; 841} 842}else{ 843/* 844 * The file that is in the way isn't a loose 845 * reference. Report it as a low-level 846 * failure. 847 */ 848strbuf_addf(err,"unable to create lock file%s.lock; " 849"non-directory in the way", 850 ref_file.buf); 851} 852goto error_return; 853case SCLD_VANISHED: 854/* Maybe another process was tidying up. Try again. */ 855if(--attempts_remaining >0) 856goto retry; 857/* fall through */ 858default: 859strbuf_addf(err,"unable to create directory for%s", 860 ref_file.buf); 861goto error_return; 862} 863 864if(!lock->lk) 865 lock->lk =xcalloc(1,sizeof(struct lock_file)); 866 867if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 868if(errno == ENOENT && --attempts_remaining >0) { 869/* 870 * Maybe somebody just deleted one of the 871 * directories leading to ref_file. Try 872 * again: 873 */ 874goto retry; 875}else{ 876unable_to_lock_message(ref_file.buf, errno, err); 877goto error_return; 878} 879} 880 881/* 882 * Now we hold the lock and can read the reference without 883 * fear that its value will change. 884 */ 885 886if(files_read_raw_ref(&refs->base, refname, 887 lock->old_oid.hash, referent, type)) { 888if(errno == ENOENT) { 889if(mustexist) { 890/* Garden variety missing reference. */ 891strbuf_addf(err,"unable to resolve reference '%s'", 892 refname); 893goto error_return; 894}else{ 895/* 896 * Reference is missing, but that's OK. We 897 * know that there is not a conflict with 898 * another loose reference because 899 * (supposing that we are trying to lock 900 * reference "refs/foo/bar"): 901 * 902 * - We were successfully able to create 903 * the lockfile refs/foo/bar.lock, so we 904 * know there cannot be a loose reference 905 * named "refs/foo". 906 * 907 * - We got ENOENT and not EISDIR, so we 908 * know that there cannot be a loose 909 * reference named "refs/foo/bar/baz". 910 */ 911} 912}else if(errno == EISDIR) { 913/* 914 * There is a directory in the way. It might have 915 * contained references that have been deleted. If 916 * we don't require that the reference already 917 * exists, try to remove the directory so that it 918 * doesn't cause trouble when we want to rename the 919 * lockfile into place later. 920 */ 921if(mustexist) { 922/* Garden variety missing reference. */ 923strbuf_addf(err,"unable to resolve reference '%s'", 924 refname); 925goto error_return; 926}else if(remove_dir_recursively(&ref_file, 927 REMOVE_DIR_EMPTY_ONLY)) { 928if(refs_verify_refname_available( 929&refs->base, refname, 930 extras, skip, err)) { 931/* 932 * The error message set by 933 * verify_refname_available() is OK. 934 */ 935 ret = TRANSACTION_NAME_CONFLICT; 936goto error_return; 937}else{ 938/* 939 * We can't delete the directory, 940 * but we also don't know of any 941 * references that it should 942 * contain. 943 */ 944strbuf_addf(err,"there is a non-empty directory '%s' " 945"blocking reference '%s'", 946 ref_file.buf, refname); 947goto error_return; 948} 949} 950}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 951strbuf_addf(err,"unable to resolve reference '%s': " 952"reference broken", refname); 953goto error_return; 954}else{ 955strbuf_addf(err,"unable to resolve reference '%s':%s", 956 refname,strerror(errno)); 957goto error_return; 958} 959 960/* 961 * If the ref did not exist and we are creating it, 962 * make sure there is no existing ref that conflicts 963 * with refname: 964 */ 965if(refs_verify_refname_available( 966&refs->base, refname, 967 extras, skip, err)) 968goto error_return; 969} 970 971 ret =0; 972goto out; 973 974error_return: 975unlock_ref(lock); 976*lock_p = NULL; 977 978out: 979strbuf_release(&ref_file); 980return ret; 981} 982 983static intfiles_peel_ref(struct ref_store *ref_store, 984const char*refname,unsigned char*sha1) 985{ 986struct files_ref_store *refs = 987files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 988"peel_ref"); 989int flag; 990unsigned char base[20]; 991 992if(current_ref_iter && current_ref_iter->refname == refname) { 993struct object_id peeled; 994 995if(ref_iterator_peel(current_ref_iter, &peeled)) 996return-1; 997hashcpy(sha1, peeled.hash); 998return0; 999}10001001if(refs_read_ref_full(ref_store, refname,1002 RESOLVE_REF_READING, base, &flag))1003return-1;10041005/*1006 * If the reference is packed, read its ref_entry from the1007 * cache in the hope that we already know its peeled value.1008 * We only try this optimization on packed references because1009 * (a) forcing the filling of the loose reference cache could1010 * be expensive and (b) loose references anyway usually do not1011 * have REF_KNOWS_PEELED.1012 */1013if(flag & REF_ISPACKED) {1014struct ref_entry *r =get_packed_ref(refs, refname);1015if(r) {1016if(peel_entry(r,0))1017return-1;1018hashcpy(sha1, r->u.value.peeled.hash);1019return0;1020}1021}10221023returnpeel_object(base, sha1);1024}10251026struct files_ref_iterator {1027struct ref_iterator base;10281029struct packed_ref_cache *packed_ref_cache;1030struct ref_iterator *iter0;1031unsigned int flags;1032};10331034static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1035{1036struct files_ref_iterator *iter =1037(struct files_ref_iterator *)ref_iterator;1038int ok;10391040while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1041if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1042ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1043continue;10441045if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1046!ref_resolves_to_object(iter->iter0->refname,1047 iter->iter0->oid,1048 iter->iter0->flags))1049continue;10501051 iter->base.refname = iter->iter0->refname;1052 iter->base.oid = iter->iter0->oid;1053 iter->base.flags = iter->iter0->flags;1054return ITER_OK;1055}10561057 iter->iter0 = NULL;1058if(ref_iterator_abort(ref_iterator) != ITER_DONE)1059 ok = ITER_ERROR;10601061return ok;1062}10631064static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1065struct object_id *peeled)1066{1067struct files_ref_iterator *iter =1068(struct files_ref_iterator *)ref_iterator;10691070returnref_iterator_peel(iter->iter0, peeled);1071}10721073static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1074{1075struct files_ref_iterator *iter =1076(struct files_ref_iterator *)ref_iterator;1077int ok = ITER_DONE;10781079if(iter->iter0)1080 ok =ref_iterator_abort(iter->iter0);10811082release_packed_ref_cache(iter->packed_ref_cache);1083base_ref_iterator_free(ref_iterator);1084return ok;1085}10861087static struct ref_iterator_vtable files_ref_iterator_vtable = {1088 files_ref_iterator_advance,1089 files_ref_iterator_peel,1090 files_ref_iterator_abort1091};10921093static struct ref_iterator *files_ref_iterator_begin(1094struct ref_store *ref_store,1095const char*prefix,unsigned int flags)1096{1097struct files_ref_store *refs;1098struct ref_iterator *loose_iter, *packed_iter;1099struct files_ref_iterator *iter;1100struct ref_iterator *ref_iterator;1101unsigned int required_flags = REF_STORE_READ;11021103if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1104 required_flags |= REF_STORE_ODB;11051106 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11071108 iter =xcalloc(1,sizeof(*iter));1109 ref_iterator = &iter->base;1110base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11111112/*1113 * We must make sure that all loose refs are read before1114 * accessing the packed-refs file; this avoids a race1115 * condition if loose refs are migrated to the packed-refs1116 * file by a simultaneous process, but our in-memory view is1117 * from before the migration. We ensure this as follows:1118 * First, we call start the loose refs iteration with its1119 * `prime_ref` argument set to true. This causes the loose1120 * references in the subtree to be pre-read into the cache.1121 * (If they've already been read, that's OK; we only need to1122 * guarantee that they're read before the packed refs, not1123 * *how much* before.) After that, we call1124 * get_packed_ref_cache(), which internally checks whether the1125 * packed-ref cache is up to date with what is on disk, and1126 * re-reads it if not.1127 */11281129 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1130 prefix,1);11311132 iter->packed_ref_cache =get_packed_ref_cache(refs);1133acquire_packed_ref_cache(iter->packed_ref_cache);1134 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1135 prefix,0);11361137 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1138 iter->flags = flags;11391140return ref_iterator;1141}11421143/*1144 * Verify that the reference locked by lock has the value old_sha1.1145 * Fail if the reference doesn't exist and mustexist is set. Return 01146 * on success. On error, write an error message to err, set errno, and1147 * return a negative value.1148 */1149static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1150const unsigned char*old_sha1,int mustexist,1151struct strbuf *err)1152{1153assert(err);11541155if(refs_read_ref_full(ref_store, lock->ref_name,1156 mustexist ? RESOLVE_REF_READING :0,1157 lock->old_oid.hash, NULL)) {1158if(old_sha1) {1159int save_errno = errno;1160strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1161 errno = save_errno;1162return-1;1163}else{1164oidclr(&lock->old_oid);1165return0;1166}1167}1168if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1169strbuf_addf(err,"ref '%s' is at%sbut expected%s",1170 lock->ref_name,1171oid_to_hex(&lock->old_oid),1172sha1_to_hex(old_sha1));1173 errno = EBUSY;1174return-1;1175}1176return0;1177}11781179static intremove_empty_directories(struct strbuf *path)1180{1181/*1182 * we want to create a file but there is a directory there;1183 * if that is an empty directory (or a directory that contains1184 * only empty directories), remove them.1185 */1186returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1187}11881189static intcreate_reflock(const char*path,void*cb)1190{1191struct lock_file *lk = cb;11921193returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1194}11951196/*1197 * Locks a ref returning the lock on success and NULL on failure.1198 * On failure errno is set to something meaningful.1199 */1200static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1201const char*refname,1202const unsigned char*old_sha1,1203const struct string_list *extras,1204const struct string_list *skip,1205unsigned int flags,int*type,1206struct strbuf *err)1207{1208struct strbuf ref_file = STRBUF_INIT;1209struct ref_lock *lock;1210int last_errno =0;1211int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1212int resolve_flags = RESOLVE_REF_NO_RECURSE;1213int resolved;12141215files_assert_main_repository(refs,"lock_ref_sha1_basic");1216assert(err);12171218 lock =xcalloc(1,sizeof(struct ref_lock));12191220if(mustexist)1221 resolve_flags |= RESOLVE_REF_READING;1222if(flags & REF_DELETING)1223 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12241225files_ref_path(refs, &ref_file, refname);1226 resolved = !!refs_resolve_ref_unsafe(&refs->base,1227 refname, resolve_flags,1228 lock->old_oid.hash, type);1229if(!resolved && errno == EISDIR) {1230/*1231 * we are trying to lock foo but we used to1232 * have foo/bar which now does not exist;1233 * it is normal for the empty directory 'foo'1234 * to remain.1235 */1236if(remove_empty_directories(&ref_file)) {1237 last_errno = errno;1238if(!refs_verify_refname_available(1239&refs->base,1240 refname, extras, skip, err))1241strbuf_addf(err,"there are still refs under '%s'",1242 refname);1243goto error_return;1244}1245 resolved = !!refs_resolve_ref_unsafe(&refs->base,1246 refname, resolve_flags,1247 lock->old_oid.hash, type);1248}1249if(!resolved) {1250 last_errno = errno;1251if(last_errno != ENOTDIR ||1252!refs_verify_refname_available(&refs->base, refname,1253 extras, skip, err))1254strbuf_addf(err,"unable to resolve reference '%s':%s",1255 refname,strerror(last_errno));12561257goto error_return;1258}12591260/*1261 * If the ref did not exist and we are creating it, make sure1262 * there is no existing packed ref whose name begins with our1263 * refname, nor a packed ref whose name is a proper prefix of1264 * our refname.1265 */1266if(is_null_oid(&lock->old_oid) &&1267refs_verify_refname_available(&refs->base, refname,1268 extras, skip, err)) {1269 last_errno = ENOTDIR;1270goto error_return;1271}12721273 lock->lk =xcalloc(1,sizeof(struct lock_file));12741275 lock->ref_name =xstrdup(refname);12761277if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1278 last_errno = errno;1279unable_to_lock_message(ref_file.buf, errno, err);1280goto error_return;1281}12821283if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1284 last_errno = errno;1285goto error_return;1286}1287goto out;12881289 error_return:1290unlock_ref(lock);1291 lock = NULL;12921293 out:1294strbuf_release(&ref_file);1295 errno = last_errno;1296return lock;1297}12981299/*1300 * Write an entry to the packed-refs file for the specified refname.1301 * If peeled is non-NULL, write it as the entry's peeled value.1302 */1303static voidwrite_packed_entry(FILE*fh,const char*refname,1304const unsigned char*sha1,1305const unsigned char*peeled)1306{1307fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1308if(peeled)1309fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1310}13111312/*1313 * Lock the packed-refs file for writing. Flags is passed to1314 * hold_lock_file_for_update(). Return 0 on success. On errors, set1315 * errno appropriately and return a nonzero value.1316 */1317static intlock_packed_refs(struct files_ref_store *refs,int flags)1318{1319static int timeout_configured =0;1320static int timeout_value =1000;1321struct packed_ref_cache *packed_ref_cache;13221323files_assert_main_repository(refs,"lock_packed_refs");13241325if(!timeout_configured) {1326git_config_get_int("core.packedrefstimeout", &timeout_value);1327 timeout_configured =1;1328}13291330if(hold_lock_file_for_update_timeout(1331&refs->packed_refs_lock,files_packed_refs_path(refs),1332 flags, timeout_value) <0)1333return-1;13341335/*1336 * Now that we hold the `packed-refs` lock, make sure that our1337 * cache matches the current version of the file. Normally1338 * `get_packed_ref_cache()` does that for us, but that1339 * function assumes that when the file is locked, any existing1340 * cache is still valid. We've just locked the file, but it1341 * might have changed the moment *before* we locked it.1342 */1343validate_packed_ref_cache(refs);13441345 packed_ref_cache =get_packed_ref_cache(refs);1346/* Increment the reference count to prevent it from being freed: */1347acquire_packed_ref_cache(packed_ref_cache);1348return0;1349}13501351/*1352 * Write the current version of the packed refs cache from memory to1353 * disk. The packed-refs file must already be locked for writing (see1354 * lock_packed_refs()). Return zero on success. On errors, set errno1355 * and return a nonzero value1356 */1357static intcommit_packed_refs(struct files_ref_store *refs)1358{1359struct packed_ref_cache *packed_ref_cache =1360get_packed_ref_cache(refs);1361int ok, error =0;1362int save_errno =0;1363FILE*out;1364struct ref_iterator *iter;13651366files_assert_main_repository(refs,"commit_packed_refs");13671368if(!is_lock_file_locked(&refs->packed_refs_lock))1369die("BUG: packed-refs not locked");13701371 out =fdopen_lock_file(&refs->packed_refs_lock,"w");1372if(!out)1373die_errno("unable to fdopen packed-refs descriptor");13741375fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13761377 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1378while((ok =ref_iterator_advance(iter)) == ITER_OK) {1379struct object_id peeled;1380int peel_error =ref_iterator_peel(iter, &peeled);13811382write_packed_entry(out, iter->refname, iter->oid->hash,1383 peel_error ? NULL : peeled.hash);1384}13851386if(ok != ITER_DONE)1387die("error while iterating over references");13881389if(commit_lock_file(&refs->packed_refs_lock)) {1390 save_errno = errno;1391 error = -1;1392}1393release_packed_ref_cache(packed_ref_cache);1394 errno = save_errno;1395return error;1396}13971398/*1399 * Rollback the lockfile for the packed-refs file, and discard the1400 * in-memory packed reference cache. (The packed-refs file will be1401 * read anew if it is needed again after this function is called.)1402 */1403static voidrollback_packed_refs(struct files_ref_store *refs)1404{1405struct packed_ref_cache *packed_ref_cache =1406get_packed_ref_cache(refs);14071408files_assert_main_repository(refs,"rollback_packed_refs");14091410if(!is_lock_file_locked(&refs->packed_refs_lock))1411die("BUG: packed-refs not locked");1412rollback_lock_file(&refs->packed_refs_lock);1413release_packed_ref_cache(packed_ref_cache);1414clear_packed_ref_cache(refs);1415}14161417struct ref_to_prune {1418struct ref_to_prune *next;1419unsigned char sha1[20];1420char name[FLEX_ARRAY];1421};14221423enum{1424 REMOVE_EMPTY_PARENTS_REF =0x01,1425 REMOVE_EMPTY_PARENTS_REFLOG =0x021426};14271428/*1429 * Remove empty parent directories associated with the specified1430 * reference and/or its reflog, but spare [logs/]refs/ and immediate1431 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1432 * REMOVE_EMPTY_PARENTS_REFLOG.1433 */1434static voidtry_remove_empty_parents(struct files_ref_store *refs,1435const char*refname,1436unsigned int flags)1437{1438struct strbuf buf = STRBUF_INIT;1439struct strbuf sb = STRBUF_INIT;1440char*p, *q;1441int i;14421443strbuf_addstr(&buf, refname);1444 p = buf.buf;1445for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1446while(*p && *p !='/')1447 p++;1448/* tolerate duplicate slashes; see check_refname_format() */1449while(*p =='/')1450 p++;1451}1452 q = buf.buf + buf.len;1453while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1454while(q > p && *q !='/')1455 q--;1456while(q > p && *(q-1) =='/')1457 q--;1458if(q == p)1459break;1460strbuf_setlen(&buf, q - buf.buf);14611462strbuf_reset(&sb);1463files_ref_path(refs, &sb, buf.buf);1464if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1465 flags &= ~REMOVE_EMPTY_PARENTS_REF;14661467strbuf_reset(&sb);1468files_reflog_path(refs, &sb, buf.buf);1469if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1470 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1471}1472strbuf_release(&buf);1473strbuf_release(&sb);1474}14751476/* make sure nobody touched the ref, and unlink */1477static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1478{1479struct ref_transaction *transaction;1480struct strbuf err = STRBUF_INIT;14811482if(check_refname_format(r->name,0))1483return;14841485 transaction =ref_store_transaction_begin(&refs->base, &err);1486if(!transaction ||1487ref_transaction_delete(transaction, r->name, r->sha1,1488 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1489ref_transaction_commit(transaction, &err)) {1490ref_transaction_free(transaction);1491error("%s", err.buf);1492strbuf_release(&err);1493return;1494}1495ref_transaction_free(transaction);1496strbuf_release(&err);1497}14981499static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1500{1501while(r) {1502prune_ref(refs, r);1503 r = r->next;1504}1505}15061507/*1508 * Return true if the specified reference should be packed.1509 */1510static intshould_pack_ref(const char*refname,1511const struct object_id *oid,unsigned int ref_flags,1512unsigned int pack_flags)1513{1514/* Do not pack per-worktree refs: */1515if(ref_type(refname) != REF_TYPE_NORMAL)1516return0;15171518/* Do not pack non-tags unless PACK_REFS_ALL is set: */1519if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1520return0;15211522/* Do not pack symbolic refs: */1523if(ref_flags & REF_ISSYMREF)1524return0;15251526/* Do not pack broken refs: */1527if(!ref_resolves_to_object(refname, oid, ref_flags))1528return0;15291530return1;1531}15321533static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1534{1535struct files_ref_store *refs =1536files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1537"pack_refs");1538struct ref_iterator *iter;1539int ok;1540struct ref_to_prune *refs_to_prune = NULL;15411542lock_packed_refs(refs, LOCK_DIE_ON_ERROR);15431544 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1545while((ok =ref_iterator_advance(iter)) == ITER_OK) {1546/*1547 * If the loose reference can be packed, add an entry1548 * in the packed ref cache. If the reference should be1549 * pruned, also add it to refs_to_prune.1550 */1551if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1552 flags))1553continue;15541555/*1556 * Create an entry in the packed-refs cache equivalent1557 * to the one from the loose ref cache, except that1558 * we don't copy the peeled status, because we want it1559 * to be re-peeled.1560 */1561add_packed_ref(refs, iter->refname, iter->oid);15621563/* Schedule the loose reference for pruning if requested. */1564if((flags & PACK_REFS_PRUNE)) {1565struct ref_to_prune *n;1566FLEX_ALLOC_STR(n, name, iter->refname);1567hashcpy(n->sha1, iter->oid->hash);1568 n->next = refs_to_prune;1569 refs_to_prune = n;1570}1571}1572if(ok != ITER_DONE)1573die("error while iterating over references");15741575if(commit_packed_refs(refs))1576die_errno("unable to overwrite old ref-pack file");15771578prune_refs(refs, refs_to_prune);1579return0;1580}15811582/*1583 * Rewrite the packed-refs file, omitting any refs listed in1584 * 'refnames'. On error, leave packed-refs unchanged, write an error1585 * message to 'err', and return a nonzero value.1586 *1587 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1588 */1589static intrepack_without_refs(struct files_ref_store *refs,1590struct string_list *refnames,struct strbuf *err)1591{1592struct ref_dir *packed;1593struct string_list_item *refname;1594int ret, needs_repacking =0, removed =0;15951596files_assert_main_repository(refs,"repack_without_refs");1597assert(err);15981599/* Look for a packed ref */1600for_each_string_list_item(refname, refnames) {1601if(get_packed_ref(refs, refname->string)) {1602 needs_repacking =1;1603break;1604}1605}16061607/* Avoid locking if we have nothing to do */1608if(!needs_repacking)1609return0;/* no refname exists in packed refs */16101611if(lock_packed_refs(refs,0)) {1612unable_to_lock_message(files_packed_refs_path(refs), errno, err);1613return-1;1614}1615 packed =get_packed_refs(refs);16161617/* Remove refnames from the cache */1618for_each_string_list_item(refname, refnames)1619if(remove_entry_from_dir(packed, refname->string) != -1)1620 removed =1;1621if(!removed) {1622/*1623 * All packed entries disappeared while we were1624 * acquiring the lock.1625 */1626rollback_packed_refs(refs);1627return0;1628}16291630/* Write what remains */1631 ret =commit_packed_refs(refs);1632if(ret)1633strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1634strerror(errno));1635return ret;1636}16371638static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1639struct string_list *refnames,unsigned int flags)1640{1641struct files_ref_store *refs =1642files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1643struct strbuf err = STRBUF_INIT;1644int i, result =0;16451646if(!refnames->nr)1647return0;16481649 result =repack_without_refs(refs, refnames, &err);1650if(result) {1651/*1652 * If we failed to rewrite the packed-refs file, then1653 * it is unsafe to try to remove loose refs, because1654 * doing so might expose an obsolete packed value for1655 * a reference that might even point at an object that1656 * has been garbage collected.1657 */1658if(refnames->nr ==1)1659error(_("could not delete reference%s:%s"),1660 refnames->items[0].string, err.buf);1661else1662error(_("could not delete references:%s"), err.buf);16631664goto out;1665}16661667for(i =0; i < refnames->nr; i++) {1668const char*refname = refnames->items[i].string;16691670if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1671 result |=error(_("could not remove reference%s"), refname);1672}16731674out:1675strbuf_release(&err);1676return result;1677}16781679/*1680 * People using contrib's git-new-workdir have .git/logs/refs ->1681 * /some/other/path/.git/logs/refs, and that may live on another device.1682 *1683 * IOW, to avoid cross device rename errors, the temporary renamed log must1684 * live into logs/refs.1685 */1686#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16871688struct rename_cb {1689const char*tmp_renamed_log;1690int true_errno;1691};16921693static intrename_tmp_log_callback(const char*path,void*cb_data)1694{1695struct rename_cb *cb = cb_data;16961697if(rename(cb->tmp_renamed_log, path)) {1698/*1699 * rename(a, b) when b is an existing directory ought1700 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1701 * Sheesh. Record the true errno for error reporting,1702 * but report EISDIR to raceproof_create_file() so1703 * that it knows to retry.1704 */1705 cb->true_errno = errno;1706if(errno == ENOTDIR)1707 errno = EISDIR;1708return-1;1709}else{1710return0;1711}1712}17131714static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1715{1716struct strbuf path = STRBUF_INIT;1717struct strbuf tmp = STRBUF_INIT;1718struct rename_cb cb;1719int ret;17201721files_reflog_path(refs, &path, newrefname);1722files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1723 cb.tmp_renamed_log = tmp.buf;1724 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1725if(ret) {1726if(errno == EISDIR)1727error("directory not empty:%s", path.buf);1728else1729error("unable to move logfile%sto%s:%s",1730 tmp.buf, path.buf,1731strerror(cb.true_errno));1732}17331734strbuf_release(&path);1735strbuf_release(&tmp);1736return ret;1737}17381739static intwrite_ref_to_lockfile(struct ref_lock *lock,1740const struct object_id *oid,struct strbuf *err);1741static intcommit_ref_update(struct files_ref_store *refs,1742struct ref_lock *lock,1743const struct object_id *oid,const char*logmsg,1744struct strbuf *err);17451746static intfiles_rename_ref(struct ref_store *ref_store,1747const char*oldrefname,const char*newrefname,1748const char*logmsg)1749{1750struct files_ref_store *refs =1751files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1752struct object_id oid, orig_oid;1753int flag =0, logmoved =0;1754struct ref_lock *lock;1755struct stat loginfo;1756struct strbuf sb_oldref = STRBUF_INIT;1757struct strbuf sb_newref = STRBUF_INIT;1758struct strbuf tmp_renamed_log = STRBUF_INIT;1759int log, ret;1760struct strbuf err = STRBUF_INIT;17611762files_reflog_path(refs, &sb_oldref, oldrefname);1763files_reflog_path(refs, &sb_newref, newrefname);1764files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17651766 log = !lstat(sb_oldref.buf, &loginfo);1767if(log &&S_ISLNK(loginfo.st_mode)) {1768 ret =error("reflog for%sis a symlink", oldrefname);1769goto out;1770}17711772if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1773 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1774 orig_oid.hash, &flag)) {1775 ret =error("refname%snot found", oldrefname);1776goto out;1777}17781779if(flag & REF_ISSYMREF) {1780 ret =error("refname%sis a symbolic ref, renaming it is not supported",1781 oldrefname);1782goto out;1783}1784if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1785 ret =1;1786goto out;1787}17881789if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1790 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1791 oldrefname,strerror(errno));1792goto out;1793}17941795if(refs_delete_ref(&refs->base, logmsg, oldrefname,1796 orig_oid.hash, REF_NODEREF)) {1797error("unable to delete old%s", oldrefname);1798goto rollback;1799}18001801/*1802 * Since we are doing a shallow lookup, oid is not the1803 * correct value to pass to delete_ref as old_oid. But that1804 * doesn't matter, because an old_oid check wouldn't add to1805 * the safety anyway; we want to delete the reference whatever1806 * its current value.1807 */1808if(!refs_read_ref_full(&refs->base, newrefname,1809 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1810 oid.hash, NULL) &&1811refs_delete_ref(&refs->base, NULL, newrefname,1812 NULL, REF_NODEREF)) {1813if(errno == EISDIR) {1814struct strbuf path = STRBUF_INIT;1815int result;18161817files_ref_path(refs, &path, newrefname);1818 result =remove_empty_directories(&path);1819strbuf_release(&path);18201821if(result) {1822error("Directory not empty:%s", newrefname);1823goto rollback;1824}1825}else{1826error("unable to delete existing%s", newrefname);1827goto rollback;1828}1829}18301831if(log &&rename_tmp_log(refs, newrefname))1832goto rollback;18331834 logmoved = log;18351836 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1837 REF_NODEREF, NULL, &err);1838if(!lock) {1839error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1840strbuf_release(&err);1841goto rollback;1842}1843oidcpy(&lock->old_oid, &orig_oid);18441845if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1846commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1847error("unable to write current sha1 into%s:%s", newrefname, err.buf);1848strbuf_release(&err);1849goto rollback;1850}18511852 ret =0;1853goto out;18541855 rollback:1856 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1857 REF_NODEREF, NULL, &err);1858if(!lock) {1859error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1860strbuf_release(&err);1861goto rollbacklog;1862}18631864 flag = log_all_ref_updates;1865 log_all_ref_updates = LOG_REFS_NONE;1866if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1867commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1868error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1869strbuf_release(&err);1870}1871 log_all_ref_updates = flag;18721873 rollbacklog:1874if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1875error("unable to restore logfile%sfrom%s:%s",1876 oldrefname, newrefname,strerror(errno));1877if(!logmoved && log &&1878rename(tmp_renamed_log.buf, sb_oldref.buf))1879error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1880 oldrefname,strerror(errno));1881 ret =1;1882 out:1883strbuf_release(&sb_newref);1884strbuf_release(&sb_oldref);1885strbuf_release(&tmp_renamed_log);18861887return ret;1888}18891890static intclose_ref(struct ref_lock *lock)1891{1892if(close_lock_file(lock->lk))1893return-1;1894return0;1895}18961897static intcommit_ref(struct ref_lock *lock)1898{1899char*path =get_locked_file_path(lock->lk);1900struct stat st;19011902if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1903/*1904 * There is a directory at the path we want to rename1905 * the lockfile to. Hopefully it is empty; try to1906 * delete it.1907 */1908size_t len =strlen(path);1909struct strbuf sb_path = STRBUF_INIT;19101911strbuf_attach(&sb_path, path, len, len);19121913/*1914 * If this fails, commit_lock_file() will also fail1915 * and will report the problem.1916 */1917remove_empty_directories(&sb_path);1918strbuf_release(&sb_path);1919}else{1920free(path);1921}19221923if(commit_lock_file(lock->lk))1924return-1;1925return0;1926}19271928static intopen_or_create_logfile(const char*path,void*cb)1929{1930int*fd = cb;19311932*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1933return(*fd <0) ? -1:0;1934}19351936/*1937 * Create a reflog for a ref. If force_create = 0, only create the1938 * reflog for certain refs (those for which should_autocreate_reflog1939 * returns non-zero). Otherwise, create it regardless of the reference1940 * name. If the logfile already existed or was created, return 0 and1941 * set *logfd to the file descriptor opened for appending to the file.1942 * If no logfile exists and we decided not to create one, return 0 and1943 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1944 * return -1.1945 */1946static intlog_ref_setup(struct files_ref_store *refs,1947const char*refname,int force_create,1948int*logfd,struct strbuf *err)1949{1950struct strbuf logfile_sb = STRBUF_INIT;1951char*logfile;19521953files_reflog_path(refs, &logfile_sb, refname);1954 logfile =strbuf_detach(&logfile_sb, NULL);19551956if(force_create ||should_autocreate_reflog(refname)) {1957if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1958if(errno == ENOENT)1959strbuf_addf(err,"unable to create directory for '%s': "1960"%s", logfile,strerror(errno));1961else if(errno == EISDIR)1962strbuf_addf(err,"there are still logs under '%s'",1963 logfile);1964else1965strbuf_addf(err,"unable to append to '%s':%s",1966 logfile,strerror(errno));19671968goto error;1969}1970}else{1971*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1972if(*logfd <0) {1973if(errno == ENOENT || errno == EISDIR) {1974/*1975 * The logfile doesn't already exist,1976 * but that is not an error; it only1977 * means that we won't write log1978 * entries to it.1979 */1980;1981}else{1982strbuf_addf(err,"unable to append to '%s':%s",1983 logfile,strerror(errno));1984goto error;1985}1986}1987}19881989if(*logfd >=0)1990adjust_shared_perm(logfile);19911992free(logfile);1993return0;19941995error:1996free(logfile);1997return-1;1998}19992000static intfiles_create_reflog(struct ref_store *ref_store,2001const char*refname,int force_create,2002struct strbuf *err)2003{2004struct files_ref_store *refs =2005files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2006int fd;20072008if(log_ref_setup(refs, refname, force_create, &fd, err))2009return-1;20102011if(fd >=0)2012close(fd);20132014return0;2015}20162017static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2018const struct object_id *new_oid,2019const char*committer,const char*msg)2020{2021int msglen, written;2022unsigned maxlen, len;2023char*logrec;20242025 msglen = msg ?strlen(msg) :0;2026 maxlen =strlen(committer) + msglen +100;2027 logrec =xmalloc(maxlen);2028 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2029oid_to_hex(old_oid),2030oid_to_hex(new_oid),2031 committer);2032if(msglen)2033 len +=copy_reflog_msg(logrec + len -1, msg) -1;20342035 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2036free(logrec);2037if(written != len)2038return-1;20392040return0;2041}20422043static intfiles_log_ref_write(struct files_ref_store *refs,2044const char*refname,const struct object_id *old_oid,2045const struct object_id *new_oid,const char*msg,2046int flags,struct strbuf *err)2047{2048int logfd, result;20492050if(log_all_ref_updates == LOG_REFS_UNSET)2051 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20522053 result =log_ref_setup(refs, refname,2054 flags & REF_FORCE_CREATE_REFLOG,2055&logfd, err);20562057if(result)2058return result;20592060if(logfd <0)2061return0;2062 result =log_ref_write_fd(logfd, old_oid, new_oid,2063git_committer_info(0), msg);2064if(result) {2065struct strbuf sb = STRBUF_INIT;2066int save_errno = errno;20672068files_reflog_path(refs, &sb, refname);2069strbuf_addf(err,"unable to append to '%s':%s",2070 sb.buf,strerror(save_errno));2071strbuf_release(&sb);2072close(logfd);2073return-1;2074}2075if(close(logfd)) {2076struct strbuf sb = STRBUF_INIT;2077int save_errno = errno;20782079files_reflog_path(refs, &sb, refname);2080strbuf_addf(err,"unable to append to '%s':%s",2081 sb.buf,strerror(save_errno));2082strbuf_release(&sb);2083return-1;2084}2085return0;2086}20872088/*2089 * Write sha1 into the open lockfile, then close the lockfile. On2090 * errors, rollback the lockfile, fill in *err and2091 * return -1.2092 */2093static intwrite_ref_to_lockfile(struct ref_lock *lock,2094const struct object_id *oid,struct strbuf *err)2095{2096static char term ='\n';2097struct object *o;2098int fd;20992100 o =parse_object(oid);2101if(!o) {2102strbuf_addf(err,2103"trying to write ref '%s' with nonexistent object%s",2104 lock->ref_name,oid_to_hex(oid));2105unlock_ref(lock);2106return-1;2107}2108if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2109strbuf_addf(err,2110"trying to write non-commit object%sto branch '%s'",2111oid_to_hex(oid), lock->ref_name);2112unlock_ref(lock);2113return-1;2114}2115 fd =get_lock_file_fd(lock->lk);2116if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2117write_in_full(fd, &term,1) !=1||2118close_ref(lock) <0) {2119strbuf_addf(err,2120"couldn't write '%s'",get_lock_file_path(lock->lk));2121unlock_ref(lock);2122return-1;2123}2124return0;2125}21262127/*2128 * Commit a change to a loose reference that has already been written2129 * to the loose reference lockfile. Also update the reflogs if2130 * necessary, using the specified lockmsg (which can be NULL).2131 */2132static intcommit_ref_update(struct files_ref_store *refs,2133struct ref_lock *lock,2134const struct object_id *oid,const char*logmsg,2135struct strbuf *err)2136{2137files_assert_main_repository(refs,"commit_ref_update");21382139clear_loose_ref_cache(refs);2140if(files_log_ref_write(refs, lock->ref_name,2141&lock->old_oid, oid,2142 logmsg,0, err)) {2143char*old_msg =strbuf_detach(err, NULL);2144strbuf_addf(err,"cannot update the ref '%s':%s",2145 lock->ref_name, old_msg);2146free(old_msg);2147unlock_ref(lock);2148return-1;2149}21502151if(strcmp(lock->ref_name,"HEAD") !=0) {2152/*2153 * Special hack: If a branch is updated directly and HEAD2154 * points to it (may happen on the remote side of a push2155 * for example) then logically the HEAD reflog should be2156 * updated too.2157 * A generic solution implies reverse symref information,2158 * but finding all symrefs pointing to the given branch2159 * would be rather costly for this rare event (the direct2160 * update of a branch) to be worth it. So let's cheat and2161 * check with HEAD only which should cover 99% of all usage2162 * scenarios (even 100% of the default ones).2163 */2164struct object_id head_oid;2165int head_flag;2166const char*head_ref;21672168 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2169 RESOLVE_REF_READING,2170 head_oid.hash, &head_flag);2171if(head_ref && (head_flag & REF_ISSYMREF) &&2172!strcmp(head_ref, lock->ref_name)) {2173struct strbuf log_err = STRBUF_INIT;2174if(files_log_ref_write(refs,"HEAD",2175&lock->old_oid, oid,2176 logmsg,0, &log_err)) {2177error("%s", log_err.buf);2178strbuf_release(&log_err);2179}2180}2181}21822183if(commit_ref(lock)) {2184strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2185unlock_ref(lock);2186return-1;2187}21882189unlock_ref(lock);2190return0;2191}21922193static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2194{2195int ret = -1;2196#ifndef NO_SYMLINK_HEAD2197char*ref_path =get_locked_file_path(lock->lk);2198unlink(ref_path);2199 ret =symlink(target, ref_path);2200free(ref_path);22012202if(ret)2203fprintf(stderr,"no symlink - falling back to symbolic ref\n");2204#endif2205return ret;2206}22072208static voidupdate_symref_reflog(struct files_ref_store *refs,2209struct ref_lock *lock,const char*refname,2210const char*target,const char*logmsg)2211{2212struct strbuf err = STRBUF_INIT;2213struct object_id new_oid;2214if(logmsg &&2215!refs_read_ref_full(&refs->base, target,2216 RESOLVE_REF_READING, new_oid.hash, NULL) &&2217files_log_ref_write(refs, refname, &lock->old_oid,2218&new_oid, logmsg,0, &err)) {2219error("%s", err.buf);2220strbuf_release(&err);2221}2222}22232224static intcreate_symref_locked(struct files_ref_store *refs,2225struct ref_lock *lock,const char*refname,2226const char*target,const char*logmsg)2227{2228if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2229update_symref_reflog(refs, lock, refname, target, logmsg);2230return0;2231}22322233if(!fdopen_lock_file(lock->lk,"w"))2234returnerror("unable to fdopen%s:%s",2235 lock->lk->tempfile.filename.buf,strerror(errno));22362237update_symref_reflog(refs, lock, refname, target, logmsg);22382239/* no error check; commit_ref will check ferror */2240fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2241if(commit_ref(lock) <0)2242returnerror("unable to write symref for%s:%s", refname,2243strerror(errno));2244return0;2245}22462247static intfiles_create_symref(struct ref_store *ref_store,2248const char*refname,const char*target,2249const char*logmsg)2250{2251struct files_ref_store *refs =2252files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2253struct strbuf err = STRBUF_INIT;2254struct ref_lock *lock;2255int ret;22562257 lock =lock_ref_sha1_basic(refs, refname, NULL,2258 NULL, NULL, REF_NODEREF, NULL,2259&err);2260if(!lock) {2261error("%s", err.buf);2262strbuf_release(&err);2263return-1;2264}22652266 ret =create_symref_locked(refs, lock, refname, target, logmsg);2267unlock_ref(lock);2268return ret;2269}22702271static intfiles_reflog_exists(struct ref_store *ref_store,2272const char*refname)2273{2274struct files_ref_store *refs =2275files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2276struct strbuf sb = STRBUF_INIT;2277struct stat st;2278int ret;22792280files_reflog_path(refs, &sb, refname);2281 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2282strbuf_release(&sb);2283return ret;2284}22852286static intfiles_delete_reflog(struct ref_store *ref_store,2287const char*refname)2288{2289struct files_ref_store *refs =2290files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2291struct strbuf sb = STRBUF_INIT;2292int ret;22932294files_reflog_path(refs, &sb, refname);2295 ret =remove_path(sb.buf);2296strbuf_release(&sb);2297return ret;2298}22992300static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2301{2302struct object_id ooid, noid;2303char*email_end, *message;2304 timestamp_t timestamp;2305int tz;2306const char*p = sb->buf;23072308/* old SP new SP name <email> SP time TAB msg LF */2309if(!sb->len || sb->buf[sb->len -1] !='\n'||2310parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2311parse_oid_hex(p, &noid, &p) || *p++ !=' '||2312!(email_end =strchr(p,'>')) ||2313 email_end[1] !=' '||2314!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2315!message || message[0] !=' '||2316(message[1] !='+'&& message[1] !='-') ||2317!isdigit(message[2]) || !isdigit(message[3]) ||2318!isdigit(message[4]) || !isdigit(message[5]))2319return0;/* corrupt? */2320 email_end[1] ='\0';2321 tz =strtol(message +1, NULL,10);2322if(message[6] !='\t')2323 message +=6;2324else2325 message +=7;2326returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2327}23282329static char*find_beginning_of_line(char*bob,char*scan)2330{2331while(bob < scan && *(--scan) !='\n')2332;/* keep scanning backwards */2333/*2334 * Return either beginning of the buffer, or LF at the end of2335 * the previous line.2336 */2337return scan;2338}23392340static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2341const char*refname,2342 each_reflog_ent_fn fn,2343void*cb_data)2344{2345struct files_ref_store *refs =2346files_downcast(ref_store, REF_STORE_READ,2347"for_each_reflog_ent_reverse");2348struct strbuf sb = STRBUF_INIT;2349FILE*logfp;2350long pos;2351int ret =0, at_tail =1;23522353files_reflog_path(refs, &sb, refname);2354 logfp =fopen(sb.buf,"r");2355strbuf_release(&sb);2356if(!logfp)2357return-1;23582359/* Jump to the end */2360if(fseek(logfp,0, SEEK_END) <0)2361 ret =error("cannot seek back reflog for%s:%s",2362 refname,strerror(errno));2363 pos =ftell(logfp);2364while(!ret &&0< pos) {2365int cnt;2366size_t nread;2367char buf[BUFSIZ];2368char*endp, *scanp;23692370/* Fill next block from the end */2371 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2372if(fseek(logfp, pos - cnt, SEEK_SET)) {2373 ret =error("cannot seek back reflog for%s:%s",2374 refname,strerror(errno));2375break;2376}2377 nread =fread(buf, cnt,1, logfp);2378if(nread !=1) {2379 ret =error("cannot read%dbytes from reflog for%s:%s",2380 cnt, refname,strerror(errno));2381break;2382}2383 pos -= cnt;23842385 scanp = endp = buf + cnt;2386if(at_tail && scanp[-1] =='\n')2387/* Looking at the final LF at the end of the file */2388 scanp--;2389 at_tail =0;23902391while(buf < scanp) {2392/*2393 * terminating LF of the previous line, or the beginning2394 * of the buffer.2395 */2396char*bp;23972398 bp =find_beginning_of_line(buf, scanp);23992400if(*bp =='\n') {2401/*2402 * The newline is the end of the previous line,2403 * so we know we have complete line starting2404 * at (bp + 1). Prefix it onto any prior data2405 * we collected for the line and process it.2406 */2407strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2408 scanp = bp;2409 endp = bp +1;2410 ret =show_one_reflog_ent(&sb, fn, cb_data);2411strbuf_reset(&sb);2412if(ret)2413break;2414}else if(!pos) {2415/*2416 * We are at the start of the buffer, and the2417 * start of the file; there is no previous2418 * line, and we have everything for this one.2419 * Process it, and we can end the loop.2420 */2421strbuf_splice(&sb,0,0, buf, endp - buf);2422 ret =show_one_reflog_ent(&sb, fn, cb_data);2423strbuf_reset(&sb);2424break;2425}24262427if(bp == buf) {2428/*2429 * We are at the start of the buffer, and there2430 * is more file to read backwards. Which means2431 * we are in the middle of a line. Note that we2432 * may get here even if *bp was a newline; that2433 * just means we are at the exact end of the2434 * previous line, rather than some spot in the2435 * middle.2436 *2437 * Save away what we have to be combined with2438 * the data from the next read.2439 */2440strbuf_splice(&sb,0,0, buf, endp - buf);2441break;2442}2443}24442445}2446if(!ret && sb.len)2447die("BUG: reverse reflog parser had leftover data");24482449fclose(logfp);2450strbuf_release(&sb);2451return ret;2452}24532454static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2455const char*refname,2456 each_reflog_ent_fn fn,void*cb_data)2457{2458struct files_ref_store *refs =2459files_downcast(ref_store, REF_STORE_READ,2460"for_each_reflog_ent");2461FILE*logfp;2462struct strbuf sb = STRBUF_INIT;2463int ret =0;24642465files_reflog_path(refs, &sb, refname);2466 logfp =fopen(sb.buf,"r");2467strbuf_release(&sb);2468if(!logfp)2469return-1;24702471while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2472 ret =show_one_reflog_ent(&sb, fn, cb_data);2473fclose(logfp);2474strbuf_release(&sb);2475return ret;2476}24772478struct files_reflog_iterator {2479struct ref_iterator base;24802481struct ref_store *ref_store;2482struct dir_iterator *dir_iterator;2483struct object_id oid;2484};24852486static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2487{2488struct files_reflog_iterator *iter =2489(struct files_reflog_iterator *)ref_iterator;2490struct dir_iterator *diter = iter->dir_iterator;2491int ok;24922493while((ok =dir_iterator_advance(diter)) == ITER_OK) {2494int flags;24952496if(!S_ISREG(diter->st.st_mode))2497continue;2498if(diter->basename[0] =='.')2499continue;2500if(ends_with(diter->basename,".lock"))2501continue;25022503if(refs_read_ref_full(iter->ref_store,2504 diter->relative_path,0,2505 iter->oid.hash, &flags)) {2506error("bad ref for%s", diter->path.buf);2507continue;2508}25092510 iter->base.refname = diter->relative_path;2511 iter->base.oid = &iter->oid;2512 iter->base.flags = flags;2513return ITER_OK;2514}25152516 iter->dir_iterator = NULL;2517if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2518 ok = ITER_ERROR;2519return ok;2520}25212522static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2523struct object_id *peeled)2524{2525die("BUG: ref_iterator_peel() called for reflog_iterator");2526}25272528static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2529{2530struct files_reflog_iterator *iter =2531(struct files_reflog_iterator *)ref_iterator;2532int ok = ITER_DONE;25332534if(iter->dir_iterator)2535 ok =dir_iterator_abort(iter->dir_iterator);25362537base_ref_iterator_free(ref_iterator);2538return ok;2539}25402541static struct ref_iterator_vtable files_reflog_iterator_vtable = {2542 files_reflog_iterator_advance,2543 files_reflog_iterator_peel,2544 files_reflog_iterator_abort2545};25462547static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2548{2549struct files_ref_store *refs =2550files_downcast(ref_store, REF_STORE_READ,2551"reflog_iterator_begin");2552struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2553struct ref_iterator *ref_iterator = &iter->base;2554struct strbuf sb = STRBUF_INIT;25552556base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2557files_reflog_path(refs, &sb, NULL);2558 iter->dir_iterator =dir_iterator_begin(sb.buf);2559 iter->ref_store = ref_store;2560strbuf_release(&sb);2561return ref_iterator;2562}25632564/*2565 * If update is a direct update of head_ref (the reference pointed to2566 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2567 */2568static intsplit_head_update(struct ref_update *update,2569struct ref_transaction *transaction,2570const char*head_ref,2571struct string_list *affected_refnames,2572struct strbuf *err)2573{2574struct string_list_item *item;2575struct ref_update *new_update;25762577if((update->flags & REF_LOG_ONLY) ||2578(update->flags & REF_ISPRUNING) ||2579(update->flags & REF_UPDATE_VIA_HEAD))2580return0;25812582if(strcmp(update->refname, head_ref))2583return0;25842585/*2586 * First make sure that HEAD is not already in the2587 * transaction. This insertion is O(N) in the transaction2588 * size, but it happens at most once per transaction.2589 */2590 item =string_list_insert(affected_refnames,"HEAD");2591if(item->util) {2592/* An entry already existed */2593strbuf_addf(err,2594"multiple updates for 'HEAD' (including one "2595"via its referent '%s') are not allowed",2596 update->refname);2597return TRANSACTION_NAME_CONFLICT;2598}25992600 new_update =ref_transaction_add_update(2601 transaction,"HEAD",2602 update->flags | REF_LOG_ONLY | REF_NODEREF,2603 update->new_oid.hash, update->old_oid.hash,2604 update->msg);26052606 item->util = new_update;26072608return0;2609}26102611/*2612 * update is for a symref that points at referent and doesn't have2613 * REF_NODEREF set. Split it into two updates:2614 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2615 * - A new, separate update for the referent reference2616 * Note that the new update will itself be subject to splitting when2617 * the iteration gets to it.2618 */2619static intsplit_symref_update(struct files_ref_store *refs,2620struct ref_update *update,2621const char*referent,2622struct ref_transaction *transaction,2623struct string_list *affected_refnames,2624struct strbuf *err)2625{2626struct string_list_item *item;2627struct ref_update *new_update;2628unsigned int new_flags;26292630/*2631 * First make sure that referent is not already in the2632 * transaction. This insertion is O(N) in the transaction2633 * size, but it happens at most once per symref in a2634 * transaction.2635 */2636 item =string_list_insert(affected_refnames, referent);2637if(item->util) {2638/* An entry already existed */2639strbuf_addf(err,2640"multiple updates for '%s' (including one "2641"via symref '%s') are not allowed",2642 referent, update->refname);2643return TRANSACTION_NAME_CONFLICT;2644}26452646 new_flags = update->flags;2647if(!strcmp(update->refname,"HEAD")) {2648/*2649 * Record that the new update came via HEAD, so that2650 * when we process it, split_head_update() doesn't try2651 * to add another reflog update for HEAD. Note that2652 * this bit will be propagated if the new_update2653 * itself needs to be split.2654 */2655 new_flags |= REF_UPDATE_VIA_HEAD;2656}26572658 new_update =ref_transaction_add_update(2659 transaction, referent, new_flags,2660 update->new_oid.hash, update->old_oid.hash,2661 update->msg);26622663 new_update->parent_update = update;26642665/*2666 * Change the symbolic ref update to log only. Also, it2667 * doesn't need to check its old SHA-1 value, as that will be2668 * done when new_update is processed.2669 */2670 update->flags |= REF_LOG_ONLY | REF_NODEREF;2671 update->flags &= ~REF_HAVE_OLD;26722673 item->util = new_update;26742675return0;2676}26772678/*2679 * Return the refname under which update was originally requested.2680 */2681static const char*original_update_refname(struct ref_update *update)2682{2683while(update->parent_update)2684 update = update->parent_update;26852686return update->refname;2687}26882689/*2690 * Check whether the REF_HAVE_OLD and old_oid values stored in update2691 * are consistent with oid, which is the reference's current value. If2692 * everything is OK, return 0; otherwise, write an error message to2693 * err and return -1.2694 */2695static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2696struct strbuf *err)2697{2698if(!(update->flags & REF_HAVE_OLD) ||2699!oidcmp(oid, &update->old_oid))2700return0;27012702if(is_null_oid(&update->old_oid))2703strbuf_addf(err,"cannot lock ref '%s': "2704"reference already exists",2705original_update_refname(update));2706else if(is_null_oid(oid))2707strbuf_addf(err,"cannot lock ref '%s': "2708"reference is missing but expected%s",2709original_update_refname(update),2710oid_to_hex(&update->old_oid));2711else2712strbuf_addf(err,"cannot lock ref '%s': "2713"is at%sbut expected%s",2714original_update_refname(update),2715oid_to_hex(oid),2716oid_to_hex(&update->old_oid));27172718return-1;2719}27202721/*2722 * Prepare for carrying out update:2723 * - Lock the reference referred to by update.2724 * - Read the reference under lock.2725 * - Check that its old SHA-1 value (if specified) is correct, and in2726 * any case record it in update->lock->old_oid for later use when2727 * writing the reflog.2728 * - If it is a symref update without REF_NODEREF, split it up into a2729 * REF_LOG_ONLY update of the symref and add a separate update for2730 * the referent to transaction.2731 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2732 * update of HEAD.2733 */2734static intlock_ref_for_update(struct files_ref_store *refs,2735struct ref_update *update,2736struct ref_transaction *transaction,2737const char*head_ref,2738struct string_list *affected_refnames,2739struct strbuf *err)2740{2741struct strbuf referent = STRBUF_INIT;2742int mustexist = (update->flags & REF_HAVE_OLD) &&2743!is_null_oid(&update->old_oid);2744int ret;2745struct ref_lock *lock;27462747files_assert_main_repository(refs,"lock_ref_for_update");27482749if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2750 update->flags |= REF_DELETING;27512752if(head_ref) {2753 ret =split_head_update(update, transaction, head_ref,2754 affected_refnames, err);2755if(ret)2756return ret;2757}27582759 ret =lock_raw_ref(refs, update->refname, mustexist,2760 affected_refnames, NULL,2761&lock, &referent,2762&update->type, err);2763if(ret) {2764char*reason;27652766 reason =strbuf_detach(err, NULL);2767strbuf_addf(err,"cannot lock ref '%s':%s",2768original_update_refname(update), reason);2769free(reason);2770return ret;2771}27722773 update->backend_data = lock;27742775if(update->type & REF_ISSYMREF) {2776if(update->flags & REF_NODEREF) {2777/*2778 * We won't be reading the referent as part of2779 * the transaction, so we have to read it here2780 * to record and possibly check old_sha1:2781 */2782if(refs_read_ref_full(&refs->base,2783 referent.buf,0,2784 lock->old_oid.hash, NULL)) {2785if(update->flags & REF_HAVE_OLD) {2786strbuf_addf(err,"cannot lock ref '%s': "2787"error reading reference",2788original_update_refname(update));2789return-1;2790}2791}else if(check_old_oid(update, &lock->old_oid, err)) {2792return TRANSACTION_GENERIC_ERROR;2793}2794}else{2795/*2796 * Create a new update for the reference this2797 * symref is pointing at. Also, we will record2798 * and verify old_sha1 for this update as part2799 * of processing the split-off update, so we2800 * don't have to do it here.2801 */2802 ret =split_symref_update(refs, update,2803 referent.buf, transaction,2804 affected_refnames, err);2805if(ret)2806return ret;2807}2808}else{2809struct ref_update *parent_update;28102811if(check_old_oid(update, &lock->old_oid, err))2812return TRANSACTION_GENERIC_ERROR;28132814/*2815 * If this update is happening indirectly because of a2816 * symref update, record the old SHA-1 in the parent2817 * update:2818 */2819for(parent_update = update->parent_update;2820 parent_update;2821 parent_update = parent_update->parent_update) {2822struct ref_lock *parent_lock = parent_update->backend_data;2823oidcpy(&parent_lock->old_oid, &lock->old_oid);2824}2825}28262827if((update->flags & REF_HAVE_NEW) &&2828!(update->flags & REF_DELETING) &&2829!(update->flags & REF_LOG_ONLY)) {2830if(!(update->type & REF_ISSYMREF) &&2831!oidcmp(&lock->old_oid, &update->new_oid)) {2832/*2833 * The reference already has the desired2834 * value, so we don't need to write it.2835 */2836}else if(write_ref_to_lockfile(lock, &update->new_oid,2837 err)) {2838char*write_err =strbuf_detach(err, NULL);28392840/*2841 * The lock was freed upon failure of2842 * write_ref_to_lockfile():2843 */2844 update->backend_data = NULL;2845strbuf_addf(err,2846"cannot update ref '%s':%s",2847 update->refname, write_err);2848free(write_err);2849return TRANSACTION_GENERIC_ERROR;2850}else{2851 update->flags |= REF_NEEDS_COMMIT;2852}2853}2854if(!(update->flags & REF_NEEDS_COMMIT)) {2855/*2856 * We didn't call write_ref_to_lockfile(), so2857 * the lockfile is still open. Close it to2858 * free up the file descriptor:2859 */2860if(close_ref(lock)) {2861strbuf_addf(err,"couldn't close '%s.lock'",2862 update->refname);2863return TRANSACTION_GENERIC_ERROR;2864}2865}2866return0;2867}28682869/*2870 * Unlock any references in `transaction` that are still locked, and2871 * mark the transaction closed.2872 */2873static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2874{2875size_t i;28762877for(i =0; i < transaction->nr; i++) {2878struct ref_update *update = transaction->updates[i];2879struct ref_lock *lock = update->backend_data;28802881if(lock) {2882unlock_ref(lock);2883 update->backend_data = NULL;2884}2885}28862887 transaction->state = REF_TRANSACTION_CLOSED;2888}28892890static intfiles_transaction_prepare(struct ref_store *ref_store,2891struct ref_transaction *transaction,2892struct strbuf *err)2893{2894struct files_ref_store *refs =2895files_downcast(ref_store, REF_STORE_WRITE,2896"ref_transaction_prepare");2897size_t i;2898int ret =0;2899struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2900char*head_ref = NULL;2901int head_type;2902struct object_id head_oid;29032904assert(err);29052906if(!transaction->nr)2907goto cleanup;29082909/*2910 * Fail if a refname appears more than once in the2911 * transaction. (If we end up splitting up any updates using2912 * split_symref_update() or split_head_update(), those2913 * functions will check that the new updates don't have the2914 * same refname as any existing ones.)2915 */2916for(i =0; i < transaction->nr; i++) {2917struct ref_update *update = transaction->updates[i];2918struct string_list_item *item =2919string_list_append(&affected_refnames, update->refname);29202921/*2922 * We store a pointer to update in item->util, but at2923 * the moment we never use the value of this field2924 * except to check whether it is non-NULL.2925 */2926 item->util = update;2927}2928string_list_sort(&affected_refnames);2929if(ref_update_reject_duplicates(&affected_refnames, err)) {2930 ret = TRANSACTION_GENERIC_ERROR;2931goto cleanup;2932}29332934/*2935 * Special hack: If a branch is updated directly and HEAD2936 * points to it (may happen on the remote side of a push2937 * for example) then logically the HEAD reflog should be2938 * updated too.2939 *2940 * A generic solution would require reverse symref lookups,2941 * but finding all symrefs pointing to a given branch would be2942 * rather costly for this rare event (the direct update of a2943 * branch) to be worth it. So let's cheat and check with HEAD2944 * only, which should cover 99% of all usage scenarios (even2945 * 100% of the default ones).2946 *2947 * So if HEAD is a symbolic reference, then record the name of2948 * the reference that it points to. If we see an update of2949 * head_ref within the transaction, then split_head_update()2950 * arranges for the reflog of HEAD to be updated, too.2951 */2952 head_ref =refs_resolve_refdup(ref_store,"HEAD",2953 RESOLVE_REF_NO_RECURSE,2954 head_oid.hash, &head_type);29552956if(head_ref && !(head_type & REF_ISSYMREF)) {2957free(head_ref);2958 head_ref = NULL;2959}29602961/*2962 * Acquire all locks, verify old values if provided, check2963 * that new values are valid, and write new values to the2964 * lockfiles, ready to be activated. Only keep one lockfile2965 * open at a time to avoid running out of file descriptors.2966 * Note that lock_ref_for_update() might append more updates2967 * to the transaction.2968 */2969for(i =0; i < transaction->nr; i++) {2970struct ref_update *update = transaction->updates[i];29712972 ret =lock_ref_for_update(refs, update, transaction,2973 head_ref, &affected_refnames, err);2974if(ret)2975break;2976}29772978cleanup:2979free(head_ref);2980string_list_clear(&affected_refnames,0);29812982if(ret)2983files_transaction_cleanup(transaction);2984else2985 transaction->state = REF_TRANSACTION_PREPARED;29862987return ret;2988}29892990static intfiles_transaction_finish(struct ref_store *ref_store,2991struct ref_transaction *transaction,2992struct strbuf *err)2993{2994struct files_ref_store *refs =2995files_downcast(ref_store,0,"ref_transaction_finish");2996size_t i;2997int ret =0;2998struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2999struct string_list_item *ref_to_delete;3000struct strbuf sb = STRBUF_INIT;30013002assert(err);30033004if(!transaction->nr) {3005 transaction->state = REF_TRANSACTION_CLOSED;3006return0;3007}30083009/* Perform updates first so live commits remain referenced */3010for(i =0; i < transaction->nr; i++) {3011struct ref_update *update = transaction->updates[i];3012struct ref_lock *lock = update->backend_data;30133014if(update->flags & REF_NEEDS_COMMIT ||3015 update->flags & REF_LOG_ONLY) {3016if(files_log_ref_write(refs,3017 lock->ref_name,3018&lock->old_oid,3019&update->new_oid,3020 update->msg, update->flags,3021 err)) {3022char*old_msg =strbuf_detach(err, NULL);30233024strbuf_addf(err,"cannot update the ref '%s':%s",3025 lock->ref_name, old_msg);3026free(old_msg);3027unlock_ref(lock);3028 update->backend_data = NULL;3029 ret = TRANSACTION_GENERIC_ERROR;3030goto cleanup;3031}3032}3033if(update->flags & REF_NEEDS_COMMIT) {3034clear_loose_ref_cache(refs);3035if(commit_ref(lock)) {3036strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3037unlock_ref(lock);3038 update->backend_data = NULL;3039 ret = TRANSACTION_GENERIC_ERROR;3040goto cleanup;3041}3042}3043}3044/* Perform deletes now that updates are safely completed */3045for(i =0; i < transaction->nr; i++) {3046struct ref_update *update = transaction->updates[i];3047struct ref_lock *lock = update->backend_data;30483049if(update->flags & REF_DELETING &&3050!(update->flags & REF_LOG_ONLY)) {3051if(!(update->type & REF_ISPACKED) ||3052 update->type & REF_ISSYMREF) {3053/* It is a loose reference. */3054strbuf_reset(&sb);3055files_ref_path(refs, &sb, lock->ref_name);3056if(unlink_or_msg(sb.buf, err)) {3057 ret = TRANSACTION_GENERIC_ERROR;3058goto cleanup;3059}3060 update->flags |= REF_DELETED_LOOSE;3061}30623063if(!(update->flags & REF_ISPRUNING))3064string_list_append(&refs_to_delete,3065 lock->ref_name);3066}3067}30683069if(repack_without_refs(refs, &refs_to_delete, err)) {3070 ret = TRANSACTION_GENERIC_ERROR;3071goto cleanup;3072}30733074/* Delete the reflogs of any references that were deleted: */3075for_each_string_list_item(ref_to_delete, &refs_to_delete) {3076strbuf_reset(&sb);3077files_reflog_path(refs, &sb, ref_to_delete->string);3078if(!unlink_or_warn(sb.buf))3079try_remove_empty_parents(refs, ref_to_delete->string,3080 REMOVE_EMPTY_PARENTS_REFLOG);3081}30823083clear_loose_ref_cache(refs);30843085cleanup:3086files_transaction_cleanup(transaction);30873088for(i =0; i < transaction->nr; i++) {3089struct ref_update *update = transaction->updates[i];30903091if(update->flags & REF_DELETED_LOOSE) {3092/*3093 * The loose reference was deleted. Delete any3094 * empty parent directories. (Note that this3095 * can only work because we have already3096 * removed the lockfile.)3097 */3098try_remove_empty_parents(refs, update->refname,3099 REMOVE_EMPTY_PARENTS_REF);3100}3101}31023103strbuf_release(&sb);3104string_list_clear(&refs_to_delete,0);3105return ret;3106}31073108static intfiles_transaction_abort(struct ref_store *ref_store,3109struct ref_transaction *transaction,3110struct strbuf *err)3111{3112files_transaction_cleanup(transaction);3113return0;3114}31153116static intref_present(const char*refname,3117const struct object_id *oid,int flags,void*cb_data)3118{3119struct string_list *affected_refnames = cb_data;31203121returnstring_list_has_string(affected_refnames, refname);3122}31233124static intfiles_initial_transaction_commit(struct ref_store *ref_store,3125struct ref_transaction *transaction,3126struct strbuf *err)3127{3128struct files_ref_store *refs =3129files_downcast(ref_store, REF_STORE_WRITE,3130"initial_ref_transaction_commit");3131size_t i;3132int ret =0;3133struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31343135assert(err);31363137if(transaction->state != REF_TRANSACTION_OPEN)3138die("BUG: commit called for transaction that is not open");31393140/* Fail if a refname appears more than once in the transaction: */3141for(i =0; i < transaction->nr; i++)3142string_list_append(&affected_refnames,3143 transaction->updates[i]->refname);3144string_list_sort(&affected_refnames);3145if(ref_update_reject_duplicates(&affected_refnames, err)) {3146 ret = TRANSACTION_GENERIC_ERROR;3147goto cleanup;3148}31493150/*3151 * It's really undefined to call this function in an active3152 * repository or when there are existing references: we are3153 * only locking and changing packed-refs, so (1) any3154 * simultaneous processes might try to change a reference at3155 * the same time we do, and (2) any existing loose versions of3156 * the references that we are setting would have precedence3157 * over our values. But some remote helpers create the remote3158 * "HEAD" and "master" branches before calling this function,3159 * so here we really only check that none of the references3160 * that we are creating already exists.3161 */3162if(refs_for_each_rawref(&refs->base, ref_present,3163&affected_refnames))3164die("BUG: initial ref transaction called with existing refs");31653166for(i =0; i < transaction->nr; i++) {3167struct ref_update *update = transaction->updates[i];31683169if((update->flags & REF_HAVE_OLD) &&3170!is_null_oid(&update->old_oid))3171die("BUG: initial ref transaction with old_sha1 set");3172if(refs_verify_refname_available(&refs->base, update->refname,3173&affected_refnames, NULL,3174 err)) {3175 ret = TRANSACTION_NAME_CONFLICT;3176goto cleanup;3177}3178}31793180if(lock_packed_refs(refs,0)) {3181strbuf_addf(err,"unable to lock packed-refs file:%s",3182strerror(errno));3183 ret = TRANSACTION_GENERIC_ERROR;3184goto cleanup;3185}31863187for(i =0; i < transaction->nr; i++) {3188struct ref_update *update = transaction->updates[i];31893190if((update->flags & REF_HAVE_NEW) &&3191!is_null_oid(&update->new_oid))3192add_packed_ref(refs, update->refname,3193&update->new_oid);3194}31953196if(commit_packed_refs(refs)) {3197strbuf_addf(err,"unable to commit packed-refs file:%s",3198strerror(errno));3199 ret = TRANSACTION_GENERIC_ERROR;3200goto cleanup;3201}32023203cleanup:3204 transaction->state = REF_TRANSACTION_CLOSED;3205string_list_clear(&affected_refnames,0);3206return ret;3207}32083209struct expire_reflog_cb {3210unsigned int flags;3211 reflog_expiry_should_prune_fn *should_prune_fn;3212void*policy_cb;3213FILE*newlog;3214struct object_id last_kept_oid;3215};32163217static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3218const char*email, timestamp_t timestamp,int tz,3219const char*message,void*cb_data)3220{3221struct expire_reflog_cb *cb = cb_data;3222struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32233224if(cb->flags & EXPIRE_REFLOGS_REWRITE)3225 ooid = &cb->last_kept_oid;32263227if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3228 message, policy_cb)) {3229if(!cb->newlog)3230printf("would prune%s", message);3231else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3232printf("prune%s", message);3233}else{3234if(cb->newlog) {3235fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3236oid_to_hex(ooid),oid_to_hex(noid),3237 email, timestamp, tz, message);3238oidcpy(&cb->last_kept_oid, noid);3239}3240if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3241printf("keep%s", message);3242}3243return0;3244}32453246static intfiles_reflog_expire(struct ref_store *ref_store,3247const char*refname,const unsigned char*sha1,3248unsigned int flags,3249 reflog_expiry_prepare_fn prepare_fn,3250 reflog_expiry_should_prune_fn should_prune_fn,3251 reflog_expiry_cleanup_fn cleanup_fn,3252void*policy_cb_data)3253{3254struct files_ref_store *refs =3255files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3256static struct lock_file reflog_lock;3257struct expire_reflog_cb cb;3258struct ref_lock *lock;3259struct strbuf log_file_sb = STRBUF_INIT;3260char*log_file;3261int status =0;3262int type;3263struct strbuf err = STRBUF_INIT;3264struct object_id oid;32653266memset(&cb,0,sizeof(cb));3267 cb.flags = flags;3268 cb.policy_cb = policy_cb_data;3269 cb.should_prune_fn = should_prune_fn;32703271/*3272 * The reflog file is locked by holding the lock on the3273 * reference itself, plus we might need to update the3274 * reference if --updateref was specified:3275 */3276 lock =lock_ref_sha1_basic(refs, refname, sha1,3277 NULL, NULL, REF_NODEREF,3278&type, &err);3279if(!lock) {3280error("cannot lock ref '%s':%s", refname, err.buf);3281strbuf_release(&err);3282return-1;3283}3284if(!refs_reflog_exists(ref_store, refname)) {3285unlock_ref(lock);3286return0;3287}32883289files_reflog_path(refs, &log_file_sb, refname);3290 log_file =strbuf_detach(&log_file_sb, NULL);3291if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3292/*3293 * Even though holding $GIT_DIR/logs/$reflog.lock has3294 * no locking implications, we use the lock_file3295 * machinery here anyway because it does a lot of the3296 * work we need, including cleaning up if the program3297 * exits unexpectedly.3298 */3299if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3300struct strbuf err = STRBUF_INIT;3301unable_to_lock_message(log_file, errno, &err);3302error("%s", err.buf);3303strbuf_release(&err);3304goto failure;3305}3306 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3307if(!cb.newlog) {3308error("cannot fdopen%s(%s)",3309get_lock_file_path(&reflog_lock),strerror(errno));3310goto failure;3311}3312}33133314hashcpy(oid.hash, sha1);33153316(*prepare_fn)(refname, &oid, cb.policy_cb);3317refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3318(*cleanup_fn)(cb.policy_cb);33193320if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3321/*3322 * It doesn't make sense to adjust a reference pointed3323 * to by a symbolic ref based on expiring entries in3324 * the symbolic reference's reflog. Nor can we update3325 * a reference if there are no remaining reflog3326 * entries.3327 */3328int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3329!(type & REF_ISSYMREF) &&3330!is_null_oid(&cb.last_kept_oid);33313332if(close_lock_file(&reflog_lock)) {3333 status |=error("couldn't write%s:%s", log_file,3334strerror(errno));3335}else if(update &&3336(write_in_full(get_lock_file_fd(lock->lk),3337oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3338write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3339close_ref(lock) <0)) {3340 status |=error("couldn't write%s",3341get_lock_file_path(lock->lk));3342rollback_lock_file(&reflog_lock);3343}else if(commit_lock_file(&reflog_lock)) {3344 status |=error("unable to write reflog '%s' (%s)",3345 log_file,strerror(errno));3346}else if(update &&commit_ref(lock)) {3347 status |=error("couldn't set%s", lock->ref_name);3348}3349}3350free(log_file);3351unlock_ref(lock);3352return status;33533354 failure:3355rollback_lock_file(&reflog_lock);3356free(log_file);3357unlock_ref(lock);3358return-1;3359}33603361static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3362{3363struct files_ref_store *refs =3364files_downcast(ref_store, REF_STORE_WRITE,"init_db");3365struct strbuf sb = STRBUF_INIT;33663367/*3368 * Create .git/refs/{heads,tags}3369 */3370files_ref_path(refs, &sb,"refs/heads");3371safe_create_dir(sb.buf,1);33723373strbuf_reset(&sb);3374files_ref_path(refs, &sb,"refs/tags");3375safe_create_dir(sb.buf,1);33763377strbuf_release(&sb);3378return0;3379}33803381struct ref_storage_be refs_be_files = {3382 NULL,3383"files",3384 files_ref_store_create,3385 files_init_db,3386 files_transaction_prepare,3387 files_transaction_finish,3388 files_transaction_abort,3389 files_initial_transaction_commit,33903391 files_pack_refs,3392 files_peel_ref,3393 files_create_symref,3394 files_delete_refs,3395 files_rename_ref,33963397 files_ref_iterator_begin,3398 files_read_raw_ref,33993400 files_reflog_iterator_begin,3401 files_for_each_reflog_ent,3402 files_for_each_reflog_ent_reverse,3403 files_reflog_exists,3404 files_create_reflog,3405 files_delete_reflog,3406 files_reflog_expire3407};