1#include"../cache.h" 2#include"../config.h" 3#include"../refs.h" 4#include"refs-internal.h" 5#include"ref-cache.h" 6#include"../iterator.h" 7#include"../dir-iterator.h" 8#include"../lockfile.h" 9#include"../object.h" 10#include"../dir.h" 11 12struct ref_lock { 13char*ref_name; 14struct lock_file *lk; 15struct object_id old_oid; 16}; 17 18/* 19 * Return true if refname, which has the specified oid and flags, can 20 * be resolved to an object in the database. If the referred-to object 21 * does not exist, emit a warning and return false. 22 */ 23static intref_resolves_to_object(const char*refname, 24const struct object_id *oid, 25unsigned int flags) 26{ 27if(flags & REF_ISBROKEN) 28return0; 29if(!has_sha1_file(oid->hash)) { 30error("%sdoes not point to a valid object!", refname); 31return0; 32} 33return1; 34} 35 36struct packed_ref_cache { 37struct ref_cache *cache; 38 39/* 40 * Count of references to the data structure in this instance, 41 * including the pointer from files_ref_store::packed if any. 42 * The data will not be freed as long as the reference count 43 * is nonzero. 44 */ 45unsigned int referrers; 46 47/* 48 * Iff the packed-refs file associated with this instance is 49 * currently locked for writing, this points at the associated 50 * lock (which is owned by somebody else). The referrer count 51 * is also incremented when the file is locked and decremented 52 * when it is unlocked. 53 */ 54struct lock_file *lock; 55 56/* The metadata from when this packed-refs cache was read */ 57struct stat_validity validity; 58}; 59 60/* 61 * Future: need to be in "struct repository" 62 * when doing a full libification. 63 */ 64struct files_ref_store { 65struct ref_store base; 66unsigned int store_flags; 67 68char*gitdir; 69char*gitcommondir; 70char*packed_refs_path; 71 72struct ref_cache *loose; 73struct packed_ref_cache *packed; 74}; 75 76/* Lock used for the main packed-refs file: */ 77static struct lock_file packlock; 78 79/* 80 * Increment the reference count of *packed_refs. 81 */ 82static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 83{ 84 packed_refs->referrers++; 85} 86 87/* 88 * Decrease the reference count of *packed_refs. If it goes to zero, 89 * free *packed_refs and return true; otherwise return false. 90 */ 91static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 92{ 93if(!--packed_refs->referrers) { 94free_ref_cache(packed_refs->cache); 95stat_validity_clear(&packed_refs->validity); 96free(packed_refs); 97return1; 98}else{ 99return0; 100} 101} 102 103static voidclear_packed_ref_cache(struct files_ref_store *refs) 104{ 105if(refs->packed) { 106struct packed_ref_cache *packed_refs = refs->packed; 107 108if(packed_refs->lock) 109die("internal error: packed-ref cache cleared while locked"); 110 refs->packed = NULL; 111release_packed_ref_cache(packed_refs); 112} 113} 114 115static voidclear_loose_ref_cache(struct files_ref_store *refs) 116{ 117if(refs->loose) { 118free_ref_cache(refs->loose); 119 refs->loose = NULL; 120} 121} 122 123/* 124 * Create a new submodule ref cache and add it to the internal 125 * set of caches. 126 */ 127static struct ref_store *files_ref_store_create(const char*gitdir, 128unsigned int flags) 129{ 130struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 131struct ref_store *ref_store = (struct ref_store *)refs; 132struct strbuf sb = STRBUF_INIT; 133 134base_ref_store_init(ref_store, &refs_be_files); 135 refs->store_flags = flags; 136 137 refs->gitdir =xstrdup(gitdir); 138get_common_dir_noenv(&sb, gitdir); 139 refs->gitcommondir =strbuf_detach(&sb, NULL); 140strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 141 refs->packed_refs_path =strbuf_detach(&sb, NULL); 142 143return ref_store; 144} 145 146/* 147 * Die if refs is not the main ref store. caller is used in any 148 * necessary error messages. 149 */ 150static voidfiles_assert_main_repository(struct files_ref_store *refs, 151const char*caller) 152{ 153if(refs->store_flags & REF_STORE_MAIN) 154return; 155 156die("BUG: operation%sonly allowed for main ref store", caller); 157} 158 159/* 160 * Downcast ref_store to files_ref_store. Die if ref_store is not a 161 * files_ref_store. required_flags is compared with ref_store's 162 * store_flags to ensure the ref_store has all required capabilities. 163 * "caller" is used in any necessary error messages. 164 */ 165static struct files_ref_store *files_downcast(struct ref_store *ref_store, 166unsigned int required_flags, 167const char*caller) 168{ 169struct files_ref_store *refs; 170 171if(ref_store->be != &refs_be_files) 172die("BUG: ref_store is type\"%s\"not\"files\"in%s", 173 ref_store->be->name, caller); 174 175 refs = (struct files_ref_store *)ref_store; 176 177if((refs->store_flags & required_flags) != required_flags) 178die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 179 caller, required_flags, refs->store_flags); 180 181return refs; 182} 183 184/* The length of a peeled reference line in packed-refs, including EOL: */ 185#define PEELED_LINE_LENGTH 42 186 187/* 188 * The packed-refs header line that we write out. Perhaps other 189 * traits will be added later. The trailing space is required. 190 */ 191static const char PACKED_REFS_HEADER[] = 192"# pack-refs with: peeled fully-peeled\n"; 193 194/* 195 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 196 * Return a pointer to the refname within the line (null-terminated), 197 * or NULL if there was a problem. 198 */ 199static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 200{ 201const char*ref; 202 203/* 204 * 42: the answer to everything. 205 * 206 * In this case, it happens to be the answer to 207 * 40 (length of sha1 hex representation) 208 * +1 (space in between hex and name) 209 * +1 (newline at the end of the line) 210 */ 211if(line->len <=42) 212return NULL; 213 214if(get_sha1_hex(line->buf, sha1) <0) 215return NULL; 216if(!isspace(line->buf[40])) 217return NULL; 218 219 ref = line->buf +41; 220if(isspace(*ref)) 221return NULL; 222 223if(line->buf[line->len -1] !='\n') 224return NULL; 225 line->buf[--line->len] =0; 226 227return ref; 228} 229 230/* 231 * Read f, which is a packed-refs file, into dir. 232 * 233 * A comment line of the form "# pack-refs with: " may contain zero or 234 * more traits. We interpret the traits as follows: 235 * 236 * No traits: 237 * 238 * Probably no references are peeled. But if the file contains a 239 * peeled value for a reference, we will use it. 240 * 241 * peeled: 242 * 243 * References under "refs/tags/", if they *can* be peeled, *are* 244 * peeled in this file. References outside of "refs/tags/" are 245 * probably not peeled even if they could have been, but if we find 246 * a peeled value for such a reference we will use it. 247 * 248 * fully-peeled: 249 * 250 * All references in the file that can be peeled are peeled. 251 * Inversely (and this is more important), any references in the 252 * file for which no peeled value is recorded is not peelable. This 253 * trait should typically be written alongside "peeled" for 254 * compatibility with older clients, but we do not require it 255 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 256 */ 257static voidread_packed_refs(FILE*f,struct ref_dir *dir) 258{ 259struct ref_entry *last = NULL; 260struct strbuf line = STRBUF_INIT; 261enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 262 263while(strbuf_getwholeline(&line, f,'\n') != EOF) { 264unsigned char sha1[20]; 265const char*refname; 266const char*traits; 267 268if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 269if(strstr(traits," fully-peeled ")) 270 peeled = PEELED_FULLY; 271else if(strstr(traits," peeled ")) 272 peeled = PEELED_TAGS; 273/* perhaps other traits later as well */ 274continue; 275} 276 277 refname =parse_ref_line(&line, sha1); 278if(refname) { 279int flag = REF_ISPACKED; 280 281if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 282if(!refname_is_safe(refname)) 283die("packed refname is dangerous:%s", refname); 284hashclr(sha1); 285 flag |= REF_BAD_NAME | REF_ISBROKEN; 286} 287 last =create_ref_entry(refname, sha1, flag,0); 288if(peeled == PEELED_FULLY || 289(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 290 last->flag |= REF_KNOWS_PEELED; 291add_ref_entry(dir, last); 292continue; 293} 294if(last && 295 line.buf[0] =='^'&& 296 line.len == PEELED_LINE_LENGTH && 297 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 298!get_sha1_hex(line.buf +1, sha1)) { 299hashcpy(last->u.value.peeled.hash, sha1); 300/* 301 * Regardless of what the file header said, 302 * we definitely know the value of *this* 303 * reference: 304 */ 305 last->flag |= REF_KNOWS_PEELED; 306} 307} 308 309strbuf_release(&line); 310} 311 312static const char*files_packed_refs_path(struct files_ref_store *refs) 313{ 314return refs->packed_refs_path; 315} 316 317static voidfiles_reflog_path(struct files_ref_store *refs, 318struct strbuf *sb, 319const char*refname) 320{ 321if(!refname) { 322/* 323 * FIXME: of course this is wrong in multi worktree 324 * setting. To be fixed real soon. 325 */ 326strbuf_addf(sb,"%s/logs", refs->gitcommondir); 327return; 328} 329 330switch(ref_type(refname)) { 331case REF_TYPE_PER_WORKTREE: 332case REF_TYPE_PSEUDOREF: 333strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 334break; 335case REF_TYPE_NORMAL: 336strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 337break; 338default: 339die("BUG: unknown ref type%dof ref%s", 340ref_type(refname), refname); 341} 342} 343 344static voidfiles_ref_path(struct files_ref_store *refs, 345struct strbuf *sb, 346const char*refname) 347{ 348switch(ref_type(refname)) { 349case REF_TYPE_PER_WORKTREE: 350case REF_TYPE_PSEUDOREF: 351strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 352break; 353case REF_TYPE_NORMAL: 354strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 355break; 356default: 357die("BUG: unknown ref type%dof ref%s", 358ref_type(refname), refname); 359} 360} 361 362/* 363 * Get the packed_ref_cache for the specified files_ref_store, 364 * creating it if necessary. 365 */ 366static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 367{ 368const char*packed_refs_file =files_packed_refs_path(refs); 369 370if(refs->packed && 371!stat_validity_check(&refs->packed->validity, packed_refs_file)) 372clear_packed_ref_cache(refs); 373 374if(!refs->packed) { 375FILE*f; 376 377 refs->packed =xcalloc(1,sizeof(*refs->packed)); 378acquire_packed_ref_cache(refs->packed); 379 refs->packed->cache =create_ref_cache(&refs->base, NULL); 380 refs->packed->cache->root->flag &= ~REF_INCOMPLETE; 381 f =fopen(packed_refs_file,"r"); 382if(f) { 383stat_validity_update(&refs->packed->validity,fileno(f)); 384read_packed_refs(f,get_ref_dir(refs->packed->cache->root)); 385fclose(f); 386} 387} 388return refs->packed; 389} 390 391static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 392{ 393returnget_ref_dir(packed_ref_cache->cache->root); 394} 395 396static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 397{ 398returnget_packed_ref_dir(get_packed_ref_cache(refs)); 399} 400 401/* 402 * Add a reference to the in-memory packed reference cache. This may 403 * only be called while the packed-refs file is locked (see 404 * lock_packed_refs()). To actually write the packed-refs file, call 405 * commit_packed_refs(). 406 */ 407static voidadd_packed_ref(struct files_ref_store *refs, 408const char*refname,const unsigned char*sha1) 409{ 410struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs); 411 412if(!packed_ref_cache->lock) 413die("internal error: packed refs not locked"); 414add_ref_entry(get_packed_ref_dir(packed_ref_cache), 415create_ref_entry(refname, sha1, REF_ISPACKED,1)); 416} 417 418/* 419 * Read the loose references from the namespace dirname into dir 420 * (without recursing). dirname must end with '/'. dir must be the 421 * directory entry corresponding to dirname. 422 */ 423static voidloose_fill_ref_dir(struct ref_store *ref_store, 424struct ref_dir *dir,const char*dirname) 425{ 426struct files_ref_store *refs = 427files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 428DIR*d; 429struct dirent *de; 430int dirnamelen =strlen(dirname); 431struct strbuf refname; 432struct strbuf path = STRBUF_INIT; 433size_t path_baselen; 434 435files_ref_path(refs, &path, dirname); 436 path_baselen = path.len; 437 438 d =opendir(path.buf); 439if(!d) { 440strbuf_release(&path); 441return; 442} 443 444strbuf_init(&refname, dirnamelen +257); 445strbuf_add(&refname, dirname, dirnamelen); 446 447while((de =readdir(d)) != NULL) { 448unsigned char sha1[20]; 449struct stat st; 450int flag; 451 452if(de->d_name[0] =='.') 453continue; 454if(ends_with(de->d_name,".lock")) 455continue; 456strbuf_addstr(&refname, de->d_name); 457strbuf_addstr(&path, de->d_name); 458if(stat(path.buf, &st) <0) { 459;/* silently ignore */ 460}else if(S_ISDIR(st.st_mode)) { 461strbuf_addch(&refname,'/'); 462add_entry_to_dir(dir, 463create_dir_entry(dir->cache, refname.buf, 464 refname.len,1)); 465}else{ 466if(!refs_resolve_ref_unsafe(&refs->base, 467 refname.buf, 468 RESOLVE_REF_READING, 469 sha1, &flag)) { 470hashclr(sha1); 471 flag |= REF_ISBROKEN; 472}else if(is_null_sha1(sha1)) { 473/* 474 * It is so astronomically unlikely 475 * that NULL_SHA1 is the SHA-1 of an 476 * actual object that we consider its 477 * appearance in a loose reference 478 * file to be repo corruption 479 * (probably due to a software bug). 480 */ 481 flag |= REF_ISBROKEN; 482} 483 484if(check_refname_format(refname.buf, 485 REFNAME_ALLOW_ONELEVEL)) { 486if(!refname_is_safe(refname.buf)) 487die("loose refname is dangerous:%s", refname.buf); 488hashclr(sha1); 489 flag |= REF_BAD_NAME | REF_ISBROKEN; 490} 491add_entry_to_dir(dir, 492create_ref_entry(refname.buf, sha1, flag,0)); 493} 494strbuf_setlen(&refname, dirnamelen); 495strbuf_setlen(&path, path_baselen); 496} 497strbuf_release(&refname); 498strbuf_release(&path); 499closedir(d); 500 501/* 502 * Manually add refs/bisect, which, being per-worktree, might 503 * not appear in the directory listing for refs/ in the main 504 * repo. 505 */ 506if(!strcmp(dirname,"refs/")) { 507int pos =search_ref_dir(dir,"refs/bisect/",12); 508 509if(pos <0) { 510struct ref_entry *child_entry =create_dir_entry( 511 dir->cache,"refs/bisect/",12,1); 512add_entry_to_dir(dir, child_entry); 513} 514} 515} 516 517static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 518{ 519if(!refs->loose) { 520/* 521 * Mark the top-level directory complete because we 522 * are about to read the only subdirectory that can 523 * hold references: 524 */ 525 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 526 527/* We're going to fill the top level ourselves: */ 528 refs->loose->root->flag &= ~REF_INCOMPLETE; 529 530/* 531 * Add an incomplete entry for "refs/" (to be filled 532 * lazily): 533 */ 534add_entry_to_dir(get_ref_dir(refs->loose->root), 535create_dir_entry(refs->loose,"refs/",5,1)); 536} 537return refs->loose; 538} 539 540/* 541 * Return the ref_entry for the given refname from the packed 542 * references. If it does not exist, return NULL. 543 */ 544static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 545const char*refname) 546{ 547returnfind_ref_entry(get_packed_refs(refs), refname); 548} 549 550/* 551 * A loose ref file doesn't exist; check for a packed ref. 552 */ 553static intresolve_packed_ref(struct files_ref_store *refs, 554const char*refname, 555unsigned char*sha1,unsigned int*flags) 556{ 557struct ref_entry *entry; 558 559/* 560 * The loose reference file does not exist; check for a packed 561 * reference. 562 */ 563 entry =get_packed_ref(refs, refname); 564if(entry) { 565hashcpy(sha1, entry->u.value.oid.hash); 566*flags |= REF_ISPACKED; 567return0; 568} 569/* refname is not a packed reference. */ 570return-1; 571} 572 573static intfiles_read_raw_ref(struct ref_store *ref_store, 574const char*refname,unsigned char*sha1, 575struct strbuf *referent,unsigned int*type) 576{ 577struct files_ref_store *refs = 578files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 579struct strbuf sb_contents = STRBUF_INIT; 580struct strbuf sb_path = STRBUF_INIT; 581const char*path; 582const char*buf; 583struct stat st; 584int fd; 585int ret = -1; 586int save_errno; 587int remaining_retries =3; 588 589*type =0; 590strbuf_reset(&sb_path); 591 592files_ref_path(refs, &sb_path, refname); 593 594 path = sb_path.buf; 595 596stat_ref: 597/* 598 * We might have to loop back here to avoid a race 599 * condition: first we lstat() the file, then we try 600 * to read it as a link or as a file. But if somebody 601 * changes the type of the file (file <-> directory 602 * <-> symlink) between the lstat() and reading, then 603 * we don't want to report that as an error but rather 604 * try again starting with the lstat(). 605 * 606 * We'll keep a count of the retries, though, just to avoid 607 * any confusing situation sending us into an infinite loop. 608 */ 609 610if(remaining_retries-- <=0) 611goto out; 612 613if(lstat(path, &st) <0) { 614if(errno != ENOENT) 615goto out; 616if(resolve_packed_ref(refs, refname, sha1, type)) { 617 errno = ENOENT; 618goto out; 619} 620 ret =0; 621goto out; 622} 623 624/* Follow "normalized" - ie "refs/.." symlinks by hand */ 625if(S_ISLNK(st.st_mode)) { 626strbuf_reset(&sb_contents); 627if(strbuf_readlink(&sb_contents, path,0) <0) { 628if(errno == ENOENT || errno == EINVAL) 629/* inconsistent with lstat; retry */ 630goto stat_ref; 631else 632goto out; 633} 634if(starts_with(sb_contents.buf,"refs/") && 635!check_refname_format(sb_contents.buf,0)) { 636strbuf_swap(&sb_contents, referent); 637*type |= REF_ISSYMREF; 638 ret =0; 639goto out; 640} 641/* 642 * It doesn't look like a refname; fall through to just 643 * treating it like a non-symlink, and reading whatever it 644 * points to. 645 */ 646} 647 648/* Is it a directory? */ 649if(S_ISDIR(st.st_mode)) { 650/* 651 * Even though there is a directory where the loose 652 * ref is supposed to be, there could still be a 653 * packed ref: 654 */ 655if(resolve_packed_ref(refs, refname, sha1, type)) { 656 errno = EISDIR; 657goto out; 658} 659 ret =0; 660goto out; 661} 662 663/* 664 * Anything else, just open it and try to use it as 665 * a ref 666 */ 667 fd =open(path, O_RDONLY); 668if(fd <0) { 669if(errno == ENOENT && !S_ISLNK(st.st_mode)) 670/* inconsistent with lstat; retry */ 671goto stat_ref; 672else 673goto out; 674} 675strbuf_reset(&sb_contents); 676if(strbuf_read(&sb_contents, fd,256) <0) { 677int save_errno = errno; 678close(fd); 679 errno = save_errno; 680goto out; 681} 682close(fd); 683strbuf_rtrim(&sb_contents); 684 buf = sb_contents.buf; 685if(starts_with(buf,"ref:")) { 686 buf +=4; 687while(isspace(*buf)) 688 buf++; 689 690strbuf_reset(referent); 691strbuf_addstr(referent, buf); 692*type |= REF_ISSYMREF; 693 ret =0; 694goto out; 695} 696 697/* 698 * Please note that FETCH_HEAD has additional 699 * data after the sha. 700 */ 701if(get_sha1_hex(buf, sha1) || 702(buf[40] !='\0'&& !isspace(buf[40]))) { 703*type |= REF_ISBROKEN; 704 errno = EINVAL; 705goto out; 706} 707 708 ret =0; 709 710out: 711 save_errno = errno; 712strbuf_release(&sb_path); 713strbuf_release(&sb_contents); 714 errno = save_errno; 715return ret; 716} 717 718static voidunlock_ref(struct ref_lock *lock) 719{ 720/* Do not free lock->lk -- atexit() still looks at them */ 721if(lock->lk) 722rollback_lock_file(lock->lk); 723free(lock->ref_name); 724free(lock); 725} 726 727/* 728 * Lock refname, without following symrefs, and set *lock_p to point 729 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 730 * and type similarly to read_raw_ref(). 731 * 732 * The caller must verify that refname is a "safe" reference name (in 733 * the sense of refname_is_safe()) before calling this function. 734 * 735 * If the reference doesn't already exist, verify that refname doesn't 736 * have a D/F conflict with any existing references. extras and skip 737 * are passed to refs_verify_refname_available() for this check. 738 * 739 * If mustexist is not set and the reference is not found or is 740 * broken, lock the reference anyway but clear sha1. 741 * 742 * Return 0 on success. On failure, write an error message to err and 743 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 744 * 745 * Implementation note: This function is basically 746 * 747 * lock reference 748 * read_raw_ref() 749 * 750 * but it includes a lot more code to 751 * - Deal with possible races with other processes 752 * - Avoid calling refs_verify_refname_available() when it can be 753 * avoided, namely if we were successfully able to read the ref 754 * - Generate informative error messages in the case of failure 755 */ 756static intlock_raw_ref(struct files_ref_store *refs, 757const char*refname,int mustexist, 758const struct string_list *extras, 759const struct string_list *skip, 760struct ref_lock **lock_p, 761struct strbuf *referent, 762unsigned int*type, 763struct strbuf *err) 764{ 765struct ref_lock *lock; 766struct strbuf ref_file = STRBUF_INIT; 767int attempts_remaining =3; 768int ret = TRANSACTION_GENERIC_ERROR; 769 770assert(err); 771files_assert_main_repository(refs,"lock_raw_ref"); 772 773*type =0; 774 775/* First lock the file so it can't change out from under us. */ 776 777*lock_p = lock =xcalloc(1,sizeof(*lock)); 778 779 lock->ref_name =xstrdup(refname); 780files_ref_path(refs, &ref_file, refname); 781 782retry: 783switch(safe_create_leading_directories(ref_file.buf)) { 784case SCLD_OK: 785break;/* success */ 786case SCLD_EXISTS: 787/* 788 * Suppose refname is "refs/foo/bar". We just failed 789 * to create the containing directory, "refs/foo", 790 * because there was a non-directory in the way. This 791 * indicates a D/F conflict, probably because of 792 * another reference such as "refs/foo". There is no 793 * reason to expect this error to be transitory. 794 */ 795if(refs_verify_refname_available(&refs->base, refname, 796 extras, skip, err)) { 797if(mustexist) { 798/* 799 * To the user the relevant error is 800 * that the "mustexist" reference is 801 * missing: 802 */ 803strbuf_reset(err); 804strbuf_addf(err,"unable to resolve reference '%s'", 805 refname); 806}else{ 807/* 808 * The error message set by 809 * refs_verify_refname_available() is 810 * OK. 811 */ 812 ret = TRANSACTION_NAME_CONFLICT; 813} 814}else{ 815/* 816 * The file that is in the way isn't a loose 817 * reference. Report it as a low-level 818 * failure. 819 */ 820strbuf_addf(err,"unable to create lock file%s.lock; " 821"non-directory in the way", 822 ref_file.buf); 823} 824goto error_return; 825case SCLD_VANISHED: 826/* Maybe another process was tidying up. Try again. */ 827if(--attempts_remaining >0) 828goto retry; 829/* fall through */ 830default: 831strbuf_addf(err,"unable to create directory for%s", 832 ref_file.buf); 833goto error_return; 834} 835 836if(!lock->lk) 837 lock->lk =xcalloc(1,sizeof(struct lock_file)); 838 839if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 840if(errno == ENOENT && --attempts_remaining >0) { 841/* 842 * Maybe somebody just deleted one of the 843 * directories leading to ref_file. Try 844 * again: 845 */ 846goto retry; 847}else{ 848unable_to_lock_message(ref_file.buf, errno, err); 849goto error_return; 850} 851} 852 853/* 854 * Now we hold the lock and can read the reference without 855 * fear that its value will change. 856 */ 857 858if(files_read_raw_ref(&refs->base, refname, 859 lock->old_oid.hash, referent, type)) { 860if(errno == ENOENT) { 861if(mustexist) { 862/* Garden variety missing reference. */ 863strbuf_addf(err,"unable to resolve reference '%s'", 864 refname); 865goto error_return; 866}else{ 867/* 868 * Reference is missing, but that's OK. We 869 * know that there is not a conflict with 870 * another loose reference because 871 * (supposing that we are trying to lock 872 * reference "refs/foo/bar"): 873 * 874 * - We were successfully able to create 875 * the lockfile refs/foo/bar.lock, so we 876 * know there cannot be a loose reference 877 * named "refs/foo". 878 * 879 * - We got ENOENT and not EISDIR, so we 880 * know that there cannot be a loose 881 * reference named "refs/foo/bar/baz". 882 */ 883} 884}else if(errno == EISDIR) { 885/* 886 * There is a directory in the way. It might have 887 * contained references that have been deleted. If 888 * we don't require that the reference already 889 * exists, try to remove the directory so that it 890 * doesn't cause trouble when we want to rename the 891 * lockfile into place later. 892 */ 893if(mustexist) { 894/* Garden variety missing reference. */ 895strbuf_addf(err,"unable to resolve reference '%s'", 896 refname); 897goto error_return; 898}else if(remove_dir_recursively(&ref_file, 899 REMOVE_DIR_EMPTY_ONLY)) { 900if(refs_verify_refname_available( 901&refs->base, refname, 902 extras, skip, err)) { 903/* 904 * The error message set by 905 * verify_refname_available() is OK. 906 */ 907 ret = TRANSACTION_NAME_CONFLICT; 908goto error_return; 909}else{ 910/* 911 * We can't delete the directory, 912 * but we also don't know of any 913 * references that it should 914 * contain. 915 */ 916strbuf_addf(err,"there is a non-empty directory '%s' " 917"blocking reference '%s'", 918 ref_file.buf, refname); 919goto error_return; 920} 921} 922}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 923strbuf_addf(err,"unable to resolve reference '%s': " 924"reference broken", refname); 925goto error_return; 926}else{ 927strbuf_addf(err,"unable to resolve reference '%s':%s", 928 refname,strerror(errno)); 929goto error_return; 930} 931 932/* 933 * If the ref did not exist and we are creating it, 934 * make sure there is no existing ref that conflicts 935 * with refname: 936 */ 937if(refs_verify_refname_available( 938&refs->base, refname, 939 extras, skip, err)) 940goto error_return; 941} 942 943 ret =0; 944goto out; 945 946error_return: 947unlock_ref(lock); 948*lock_p = NULL; 949 950out: 951strbuf_release(&ref_file); 952return ret; 953} 954 955static intfiles_peel_ref(struct ref_store *ref_store, 956const char*refname,unsigned char*sha1) 957{ 958struct files_ref_store *refs = 959files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 960"peel_ref"); 961int flag; 962unsigned char base[20]; 963 964if(current_ref_iter && current_ref_iter->refname == refname) { 965struct object_id peeled; 966 967if(ref_iterator_peel(current_ref_iter, &peeled)) 968return-1; 969hashcpy(sha1, peeled.hash); 970return0; 971} 972 973if(refs_read_ref_full(ref_store, refname, 974 RESOLVE_REF_READING, base, &flag)) 975return-1; 976 977/* 978 * If the reference is packed, read its ref_entry from the 979 * cache in the hope that we already know its peeled value. 980 * We only try this optimization on packed references because 981 * (a) forcing the filling of the loose reference cache could 982 * be expensive and (b) loose references anyway usually do not 983 * have REF_KNOWS_PEELED. 984 */ 985if(flag & REF_ISPACKED) { 986struct ref_entry *r =get_packed_ref(refs, refname); 987if(r) { 988if(peel_entry(r,0)) 989return-1; 990hashcpy(sha1, r->u.value.peeled.hash); 991return0; 992} 993} 994 995returnpeel_object(base, sha1); 996} 997 998struct files_ref_iterator { 999struct ref_iterator base;10001001struct packed_ref_cache *packed_ref_cache;1002struct ref_iterator *iter0;1003unsigned int flags;1004};10051006static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1007{1008struct files_ref_iterator *iter =1009(struct files_ref_iterator *)ref_iterator;1010int ok;10111012while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1013if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1014ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1015continue;10161017if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1018!ref_resolves_to_object(iter->iter0->refname,1019 iter->iter0->oid,1020 iter->iter0->flags))1021continue;10221023 iter->base.refname = iter->iter0->refname;1024 iter->base.oid = iter->iter0->oid;1025 iter->base.flags = iter->iter0->flags;1026return ITER_OK;1027}10281029 iter->iter0 = NULL;1030if(ref_iterator_abort(ref_iterator) != ITER_DONE)1031 ok = ITER_ERROR;10321033return ok;1034}10351036static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1037struct object_id *peeled)1038{1039struct files_ref_iterator *iter =1040(struct files_ref_iterator *)ref_iterator;10411042returnref_iterator_peel(iter->iter0, peeled);1043}10441045static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1046{1047struct files_ref_iterator *iter =1048(struct files_ref_iterator *)ref_iterator;1049int ok = ITER_DONE;10501051if(iter->iter0)1052 ok =ref_iterator_abort(iter->iter0);10531054release_packed_ref_cache(iter->packed_ref_cache);1055base_ref_iterator_free(ref_iterator);1056return ok;1057}10581059static struct ref_iterator_vtable files_ref_iterator_vtable = {1060 files_ref_iterator_advance,1061 files_ref_iterator_peel,1062 files_ref_iterator_abort1063};10641065static struct ref_iterator *files_ref_iterator_begin(1066struct ref_store *ref_store,1067const char*prefix,unsigned int flags)1068{1069struct files_ref_store *refs;1070struct ref_iterator *loose_iter, *packed_iter;1071struct files_ref_iterator *iter;1072struct ref_iterator *ref_iterator;10731074if(ref_paranoia <0)1075 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1076if(ref_paranoia)1077 flags |= DO_FOR_EACH_INCLUDE_BROKEN;10781079 refs =files_downcast(ref_store,1080 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1081"ref_iterator_begin");10821083 iter =xcalloc(1,sizeof(*iter));1084 ref_iterator = &iter->base;1085base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);10861087/*1088 * We must make sure that all loose refs are read before1089 * accessing the packed-refs file; this avoids a race1090 * condition if loose refs are migrated to the packed-refs1091 * file by a simultaneous process, but our in-memory view is1092 * from before the migration. We ensure this as follows:1093 * First, we call start the loose refs iteration with its1094 * `prime_ref` argument set to true. This causes the loose1095 * references in the subtree to be pre-read into the cache.1096 * (If they've already been read, that's OK; we only need to1097 * guarantee that they're read before the packed refs, not1098 * *how much* before.) After that, we call1099 * get_packed_ref_cache(), which internally checks whether the1100 * packed-ref cache is up to date with what is on disk, and1101 * re-reads it if not.1102 */11031104 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1105 prefix,1);11061107 iter->packed_ref_cache =get_packed_ref_cache(refs);1108acquire_packed_ref_cache(iter->packed_ref_cache);1109 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1110 prefix,0);11111112 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1113 iter->flags = flags;11141115return ref_iterator;1116}11171118/*1119 * Verify that the reference locked by lock has the value old_sha1.1120 * Fail if the reference doesn't exist and mustexist is set. Return 01121 * on success. On error, write an error message to err, set errno, and1122 * return a negative value.1123 */1124static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1125const unsigned char*old_sha1,int mustexist,1126struct strbuf *err)1127{1128assert(err);11291130if(refs_read_ref_full(ref_store, lock->ref_name,1131 mustexist ? RESOLVE_REF_READING :0,1132 lock->old_oid.hash, NULL)) {1133if(old_sha1) {1134int save_errno = errno;1135strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1136 errno = save_errno;1137return-1;1138}else{1139oidclr(&lock->old_oid);1140return0;1141}1142}1143if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1144strbuf_addf(err,"ref '%s' is at%sbut expected%s",1145 lock->ref_name,1146oid_to_hex(&lock->old_oid),1147sha1_to_hex(old_sha1));1148 errno = EBUSY;1149return-1;1150}1151return0;1152}11531154static intremove_empty_directories(struct strbuf *path)1155{1156/*1157 * we want to create a file but there is a directory there;1158 * if that is an empty directory (or a directory that contains1159 * only empty directories), remove them.1160 */1161returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1162}11631164static intcreate_reflock(const char*path,void*cb)1165{1166struct lock_file *lk = cb;11671168returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1169}11701171/*1172 * Locks a ref returning the lock on success and NULL on failure.1173 * On failure errno is set to something meaningful.1174 */1175static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1176const char*refname,1177const unsigned char*old_sha1,1178const struct string_list *extras,1179const struct string_list *skip,1180unsigned int flags,int*type,1181struct strbuf *err)1182{1183struct strbuf ref_file = STRBUF_INIT;1184struct ref_lock *lock;1185int last_errno =0;1186int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1187int resolve_flags = RESOLVE_REF_NO_RECURSE;1188int resolved;11891190files_assert_main_repository(refs,"lock_ref_sha1_basic");1191assert(err);11921193 lock =xcalloc(1,sizeof(struct ref_lock));11941195if(mustexist)1196 resolve_flags |= RESOLVE_REF_READING;1197if(flags & REF_DELETING)1198 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;11991200files_ref_path(refs, &ref_file, refname);1201 resolved = !!refs_resolve_ref_unsafe(&refs->base,1202 refname, resolve_flags,1203 lock->old_oid.hash, type);1204if(!resolved && errno == EISDIR) {1205/*1206 * we are trying to lock foo but we used to1207 * have foo/bar which now does not exist;1208 * it is normal for the empty directory 'foo'1209 * to remain.1210 */1211if(remove_empty_directories(&ref_file)) {1212 last_errno = errno;1213if(!refs_verify_refname_available(1214&refs->base,1215 refname, extras, skip, err))1216strbuf_addf(err,"there are still refs under '%s'",1217 refname);1218goto error_return;1219}1220 resolved = !!refs_resolve_ref_unsafe(&refs->base,1221 refname, resolve_flags,1222 lock->old_oid.hash, type);1223}1224if(!resolved) {1225 last_errno = errno;1226if(last_errno != ENOTDIR ||1227!refs_verify_refname_available(&refs->base, refname,1228 extras, skip, err))1229strbuf_addf(err,"unable to resolve reference '%s':%s",1230 refname,strerror(last_errno));12311232goto error_return;1233}12341235/*1236 * If the ref did not exist and we are creating it, make sure1237 * there is no existing packed ref whose name begins with our1238 * refname, nor a packed ref whose name is a proper prefix of1239 * our refname.1240 */1241if(is_null_oid(&lock->old_oid) &&1242refs_verify_refname_available(&refs->base, refname,1243 extras, skip, err)) {1244 last_errno = ENOTDIR;1245goto error_return;1246}12471248 lock->lk =xcalloc(1,sizeof(struct lock_file));12491250 lock->ref_name =xstrdup(refname);12511252if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1253 last_errno = errno;1254unable_to_lock_message(ref_file.buf, errno, err);1255goto error_return;1256}12571258if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1259 last_errno = errno;1260goto error_return;1261}1262goto out;12631264 error_return:1265unlock_ref(lock);1266 lock = NULL;12671268 out:1269strbuf_release(&ref_file);1270 errno = last_errno;1271return lock;1272}12731274/*1275 * Write an entry to the packed-refs file for the specified refname.1276 * If peeled is non-NULL, write it as the entry's peeled value.1277 */1278static voidwrite_packed_entry(FILE*fh,const char*refname,1279const unsigned char*sha1,1280const unsigned char*peeled)1281{1282fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1283if(peeled)1284fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1285}12861287/*1288 * Lock the packed-refs file for writing. Flags is passed to1289 * hold_lock_file_for_update(). Return 0 on success. On errors, set1290 * errno appropriately and return a nonzero value.1291 */1292static intlock_packed_refs(struct files_ref_store *refs,int flags)1293{1294static int timeout_configured =0;1295static int timeout_value =1000;1296struct packed_ref_cache *packed_ref_cache;12971298files_assert_main_repository(refs,"lock_packed_refs");12991300if(!timeout_configured) {1301git_config_get_int("core.packedrefstimeout", &timeout_value);1302 timeout_configured =1;1303}13041305if(hold_lock_file_for_update_timeout(1306&packlock,files_packed_refs_path(refs),1307 flags, timeout_value) <0)1308return-1;1309/*1310 * Get the current packed-refs while holding the lock. If the1311 * packed-refs file has been modified since we last read it,1312 * this will automatically invalidate the cache and re-read1313 * the packed-refs file.1314 */1315 packed_ref_cache =get_packed_ref_cache(refs);1316 packed_ref_cache->lock = &packlock;1317/* Increment the reference count to prevent it from being freed: */1318acquire_packed_ref_cache(packed_ref_cache);1319return0;1320}13211322/*1323 * Write the current version of the packed refs cache from memory to1324 * disk. The packed-refs file must already be locked for writing (see1325 * lock_packed_refs()). Return zero on success. On errors, set errno1326 * and return a nonzero value1327 */1328static intcommit_packed_refs(struct files_ref_store *refs)1329{1330struct packed_ref_cache *packed_ref_cache =1331get_packed_ref_cache(refs);1332int ok, error =0;1333int save_errno =0;1334FILE*out;1335struct ref_iterator *iter;13361337files_assert_main_repository(refs,"commit_packed_refs");13381339if(!packed_ref_cache->lock)1340die("internal error: packed-refs not locked");13411342 out =fdopen_lock_file(packed_ref_cache->lock,"w");1343if(!out)1344die_errno("unable to fdopen packed-refs descriptor");13451346fprintf_or_die(out,"%s", PACKED_REFS_HEADER);13471348 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1349while((ok =ref_iterator_advance(iter)) == ITER_OK) {1350struct object_id peeled;1351int peel_error =ref_iterator_peel(iter, &peeled);13521353write_packed_entry(out, iter->refname, iter->oid->hash,1354 peel_error ? NULL : peeled.hash);1355}13561357if(ok != ITER_DONE)1358die("error while iterating over references");13591360if(commit_lock_file(packed_ref_cache->lock)) {1361 save_errno = errno;1362 error = -1;1363}1364 packed_ref_cache->lock = NULL;1365release_packed_ref_cache(packed_ref_cache);1366 errno = save_errno;1367return error;1368}13691370/*1371 * Rollback the lockfile for the packed-refs file, and discard the1372 * in-memory packed reference cache. (The packed-refs file will be1373 * read anew if it is needed again after this function is called.)1374 */1375static voidrollback_packed_refs(struct files_ref_store *refs)1376{1377struct packed_ref_cache *packed_ref_cache =1378get_packed_ref_cache(refs);13791380files_assert_main_repository(refs,"rollback_packed_refs");13811382if(!packed_ref_cache->lock)1383die("internal error: packed-refs not locked");1384rollback_lock_file(packed_ref_cache->lock);1385 packed_ref_cache->lock = NULL;1386release_packed_ref_cache(packed_ref_cache);1387clear_packed_ref_cache(refs);1388}13891390struct ref_to_prune {1391struct ref_to_prune *next;1392unsigned char sha1[20];1393char name[FLEX_ARRAY];1394};13951396enum{1397 REMOVE_EMPTY_PARENTS_REF =0x01,1398 REMOVE_EMPTY_PARENTS_REFLOG =0x021399};14001401/*1402 * Remove empty parent directories associated with the specified1403 * reference and/or its reflog, but spare [logs/]refs/ and immediate1404 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1405 * REMOVE_EMPTY_PARENTS_REFLOG.1406 */1407static voidtry_remove_empty_parents(struct files_ref_store *refs,1408const char*refname,1409unsigned int flags)1410{1411struct strbuf buf = STRBUF_INIT;1412struct strbuf sb = STRBUF_INIT;1413char*p, *q;1414int i;14151416strbuf_addstr(&buf, refname);1417 p = buf.buf;1418for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1419while(*p && *p !='/')1420 p++;1421/* tolerate duplicate slashes; see check_refname_format() */1422while(*p =='/')1423 p++;1424}1425 q = buf.buf + buf.len;1426while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1427while(q > p && *q !='/')1428 q--;1429while(q > p && *(q-1) =='/')1430 q--;1431if(q == p)1432break;1433strbuf_setlen(&buf, q - buf.buf);14341435strbuf_reset(&sb);1436files_ref_path(refs, &sb, buf.buf);1437if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1438 flags &= ~REMOVE_EMPTY_PARENTS_REF;14391440strbuf_reset(&sb);1441files_reflog_path(refs, &sb, buf.buf);1442if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1443 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1444}1445strbuf_release(&buf);1446strbuf_release(&sb);1447}14481449/* make sure nobody touched the ref, and unlink */1450static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1451{1452struct ref_transaction *transaction;1453struct strbuf err = STRBUF_INIT;14541455if(check_refname_format(r->name,0))1456return;14571458 transaction =ref_store_transaction_begin(&refs->base, &err);1459if(!transaction ||1460ref_transaction_delete(transaction, r->name, r->sha1,1461 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1462ref_transaction_commit(transaction, &err)) {1463ref_transaction_free(transaction);1464error("%s", err.buf);1465strbuf_release(&err);1466return;1467}1468ref_transaction_free(transaction);1469strbuf_release(&err);1470}14711472static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1473{1474while(r) {1475prune_ref(refs, r);1476 r = r->next;1477}1478}14791480static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1481{1482struct files_ref_store *refs =1483files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1484"pack_refs");1485struct ref_iterator *iter;1486struct ref_dir *packed_refs;1487int ok;1488struct ref_to_prune *refs_to_prune = NULL;14891490lock_packed_refs(refs, LOCK_DIE_ON_ERROR);1491 packed_refs =get_packed_refs(refs);14921493 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1494while((ok =ref_iterator_advance(iter)) == ITER_OK) {1495/*1496 * If the loose reference can be packed, add an entry1497 * in the packed ref cache. If the reference should be1498 * pruned, also add it to refs_to_prune.1499 */1500struct ref_entry *packed_entry;1501int is_tag_ref =starts_with(iter->refname,"refs/tags/");15021503/* Do not pack per-worktree refs: */1504if(ref_type(iter->refname) != REF_TYPE_NORMAL)1505continue;15061507/* ALWAYS pack tags */1508if(!(flags & PACK_REFS_ALL) && !is_tag_ref)1509continue;15101511/* Do not pack symbolic or broken refs: */1512if(iter->flags & REF_ISSYMREF)1513continue;15141515if(!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))1516continue;15171518/*1519 * Create an entry in the packed-refs cache equivalent1520 * to the one from the loose ref cache, except that1521 * we don't copy the peeled status, because we want it1522 * to be re-peeled.1523 */1524 packed_entry =find_ref_entry(packed_refs, iter->refname);1525if(packed_entry) {1526/* Overwrite existing packed entry with info from loose entry */1527 packed_entry->flag = REF_ISPACKED;1528oidcpy(&packed_entry->u.value.oid, iter->oid);1529}else{1530 packed_entry =create_ref_entry(iter->refname, iter->oid->hash,1531 REF_ISPACKED,0);1532add_ref_entry(packed_refs, packed_entry);1533}1534oidclr(&packed_entry->u.value.peeled);15351536/* Schedule the loose reference for pruning if requested. */1537if((flags & PACK_REFS_PRUNE)) {1538struct ref_to_prune *n;1539FLEX_ALLOC_STR(n, name, iter->refname);1540hashcpy(n->sha1, iter->oid->hash);1541 n->next = refs_to_prune;1542 refs_to_prune = n;1543}1544}1545if(ok != ITER_DONE)1546die("error while iterating over references");15471548if(commit_packed_refs(refs))1549die_errno("unable to overwrite old ref-pack file");15501551prune_refs(refs, refs_to_prune);1552return0;1553}15541555/*1556 * Rewrite the packed-refs file, omitting any refs listed in1557 * 'refnames'. On error, leave packed-refs unchanged, write an error1558 * message to 'err', and return a nonzero value.1559 *1560 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1561 */1562static intrepack_without_refs(struct files_ref_store *refs,1563struct string_list *refnames,struct strbuf *err)1564{1565struct ref_dir *packed;1566struct string_list_item *refname;1567int ret, needs_repacking =0, removed =0;15681569files_assert_main_repository(refs,"repack_without_refs");1570assert(err);15711572/* Look for a packed ref */1573for_each_string_list_item(refname, refnames) {1574if(get_packed_ref(refs, refname->string)) {1575 needs_repacking =1;1576break;1577}1578}15791580/* Avoid locking if we have nothing to do */1581if(!needs_repacking)1582return0;/* no refname exists in packed refs */15831584if(lock_packed_refs(refs,0)) {1585unable_to_lock_message(files_packed_refs_path(refs), errno, err);1586return-1;1587}1588 packed =get_packed_refs(refs);15891590/* Remove refnames from the cache */1591for_each_string_list_item(refname, refnames)1592if(remove_entry_from_dir(packed, refname->string) != -1)1593 removed =1;1594if(!removed) {1595/*1596 * All packed entries disappeared while we were1597 * acquiring the lock.1598 */1599rollback_packed_refs(refs);1600return0;1601}16021603/* Write what remains */1604 ret =commit_packed_refs(refs);1605if(ret)1606strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1607strerror(errno));1608return ret;1609}16101611static intfiles_delete_refs(struct ref_store *ref_store,1612struct string_list *refnames,unsigned int flags)1613{1614struct files_ref_store *refs =1615files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1616struct strbuf err = STRBUF_INIT;1617int i, result =0;16181619if(!refnames->nr)1620return0;16211622 result =repack_without_refs(refs, refnames, &err);1623if(result) {1624/*1625 * If we failed to rewrite the packed-refs file, then1626 * it is unsafe to try to remove loose refs, because1627 * doing so might expose an obsolete packed value for1628 * a reference that might even point at an object that1629 * has been garbage collected.1630 */1631if(refnames->nr ==1)1632error(_("could not delete reference%s:%s"),1633 refnames->items[0].string, err.buf);1634else1635error(_("could not delete references:%s"), err.buf);16361637goto out;1638}16391640for(i =0; i < refnames->nr; i++) {1641const char*refname = refnames->items[i].string;16421643if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))1644 result |=error(_("could not remove reference%s"), refname);1645}16461647out:1648strbuf_release(&err);1649return result;1650}16511652/*1653 * People using contrib's git-new-workdir have .git/logs/refs ->1654 * /some/other/path/.git/logs/refs, and that may live on another device.1655 *1656 * IOW, to avoid cross device rename errors, the temporary renamed log must1657 * live into logs/refs.1658 */1659#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"16601661struct rename_cb {1662const char*tmp_renamed_log;1663int true_errno;1664};16651666static intrename_tmp_log_callback(const char*path,void*cb_data)1667{1668struct rename_cb *cb = cb_data;16691670if(rename(cb->tmp_renamed_log, path)) {1671/*1672 * rename(a, b) when b is an existing directory ought1673 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1674 * Sheesh. Record the true errno for error reporting,1675 * but report EISDIR to raceproof_create_file() so1676 * that it knows to retry.1677 */1678 cb->true_errno = errno;1679if(errno == ENOTDIR)1680 errno = EISDIR;1681return-1;1682}else{1683return0;1684}1685}16861687static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1688{1689struct strbuf path = STRBUF_INIT;1690struct strbuf tmp = STRBUF_INIT;1691struct rename_cb cb;1692int ret;16931694files_reflog_path(refs, &path, newrefname);1695files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1696 cb.tmp_renamed_log = tmp.buf;1697 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1698if(ret) {1699if(errno == EISDIR)1700error("directory not empty:%s", path.buf);1701else1702error("unable to move logfile%sto%s:%s",1703 tmp.buf, path.buf,1704strerror(cb.true_errno));1705}17061707strbuf_release(&path);1708strbuf_release(&tmp);1709return ret;1710}17111712static intwrite_ref_to_lockfile(struct ref_lock *lock,1713const unsigned char*sha1,struct strbuf *err);1714static intcommit_ref_update(struct files_ref_store *refs,1715struct ref_lock *lock,1716const unsigned char*sha1,const char*logmsg,1717struct strbuf *err);17181719static intfiles_rename_ref(struct ref_store *ref_store,1720const char*oldrefname,const char*newrefname,1721const char*logmsg)1722{1723struct files_ref_store *refs =1724files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1725unsigned char sha1[20], orig_sha1[20];1726int flag =0, logmoved =0;1727struct ref_lock *lock;1728struct stat loginfo;1729struct strbuf sb_oldref = STRBUF_INIT;1730struct strbuf sb_newref = STRBUF_INIT;1731struct strbuf tmp_renamed_log = STRBUF_INIT;1732int log, ret;1733struct strbuf err = STRBUF_INIT;17341735files_reflog_path(refs, &sb_oldref, oldrefname);1736files_reflog_path(refs, &sb_newref, newrefname);1737files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17381739 log = !lstat(sb_oldref.buf, &loginfo);1740if(log &&S_ISLNK(loginfo.st_mode)) {1741 ret =error("reflog for%sis a symlink", oldrefname);1742goto out;1743}17441745if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1746 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1747 orig_sha1, &flag)) {1748 ret =error("refname%snot found", oldrefname);1749goto out;1750}17511752if(flag & REF_ISSYMREF) {1753 ret =error("refname%sis a symbolic ref, renaming it is not supported",1754 oldrefname);1755goto out;1756}1757if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1758 ret =1;1759goto out;1760}17611762if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1763 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1764 oldrefname,strerror(errno));1765goto out;1766}17671768if(refs_delete_ref(&refs->base, logmsg, oldrefname,1769 orig_sha1, REF_NODEREF)) {1770error("unable to delete old%s", oldrefname);1771goto rollback;1772}17731774/*1775 * Since we are doing a shallow lookup, sha1 is not the1776 * correct value to pass to delete_ref as old_sha1. But that1777 * doesn't matter, because an old_sha1 check wouldn't add to1778 * the safety anyway; we want to delete the reference whatever1779 * its current value.1780 */1781if(!refs_read_ref_full(&refs->base, newrefname,1782 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1783 sha1, NULL) &&1784refs_delete_ref(&refs->base, NULL, newrefname,1785 NULL, REF_NODEREF)) {1786if(errno == EISDIR) {1787struct strbuf path = STRBUF_INIT;1788int result;17891790files_ref_path(refs, &path, newrefname);1791 result =remove_empty_directories(&path);1792strbuf_release(&path);17931794if(result) {1795error("Directory not empty:%s", newrefname);1796goto rollback;1797}1798}else{1799error("unable to delete existing%s", newrefname);1800goto rollback;1801}1802}18031804if(log &&rename_tmp_log(refs, newrefname))1805goto rollback;18061807 logmoved = log;18081809 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1810 REF_NODEREF, NULL, &err);1811if(!lock) {1812error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1813strbuf_release(&err);1814goto rollback;1815}1816hashcpy(lock->old_oid.hash, orig_sha1);18171818if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1819commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {1820error("unable to write current sha1 into%s:%s", newrefname, err.buf);1821strbuf_release(&err);1822goto rollback;1823}18241825 ret =0;1826goto out;18271828 rollback:1829 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1830 REF_NODEREF, NULL, &err);1831if(!lock) {1832error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1833strbuf_release(&err);1834goto rollbacklog;1835}18361837 flag = log_all_ref_updates;1838 log_all_ref_updates = LOG_REFS_NONE;1839if(write_ref_to_lockfile(lock, orig_sha1, &err) ||1840commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {1841error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1842strbuf_release(&err);1843}1844 log_all_ref_updates = flag;18451846 rollbacklog:1847if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1848error("unable to restore logfile%sfrom%s:%s",1849 oldrefname, newrefname,strerror(errno));1850if(!logmoved && log &&1851rename(tmp_renamed_log.buf, sb_oldref.buf))1852error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1853 oldrefname,strerror(errno));1854 ret =1;1855 out:1856strbuf_release(&sb_newref);1857strbuf_release(&sb_oldref);1858strbuf_release(&tmp_renamed_log);18591860return ret;1861}18621863static intclose_ref(struct ref_lock *lock)1864{1865if(close_lock_file(lock->lk))1866return-1;1867return0;1868}18691870static intcommit_ref(struct ref_lock *lock)1871{1872char*path =get_locked_file_path(lock->lk);1873struct stat st;18741875if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1876/*1877 * There is a directory at the path we want to rename1878 * the lockfile to. Hopefully it is empty; try to1879 * delete it.1880 */1881size_t len =strlen(path);1882struct strbuf sb_path = STRBUF_INIT;18831884strbuf_attach(&sb_path, path, len, len);18851886/*1887 * If this fails, commit_lock_file() will also fail1888 * and will report the problem.1889 */1890remove_empty_directories(&sb_path);1891strbuf_release(&sb_path);1892}else{1893free(path);1894}18951896if(commit_lock_file(lock->lk))1897return-1;1898return0;1899}19001901static intopen_or_create_logfile(const char*path,void*cb)1902{1903int*fd = cb;19041905*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1906return(*fd <0) ? -1:0;1907}19081909/*1910 * Create a reflog for a ref. If force_create = 0, only create the1911 * reflog for certain refs (those for which should_autocreate_reflog1912 * returns non-zero). Otherwise, create it regardless of the reference1913 * name. If the logfile already existed or was created, return 0 and1914 * set *logfd to the file descriptor opened for appending to the file.1915 * If no logfile exists and we decided not to create one, return 0 and1916 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1917 * return -1.1918 */1919static intlog_ref_setup(struct files_ref_store *refs,1920const char*refname,int force_create,1921int*logfd,struct strbuf *err)1922{1923struct strbuf logfile_sb = STRBUF_INIT;1924char*logfile;19251926files_reflog_path(refs, &logfile_sb, refname);1927 logfile =strbuf_detach(&logfile_sb, NULL);19281929if(force_create ||should_autocreate_reflog(refname)) {1930if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1931if(errno == ENOENT)1932strbuf_addf(err,"unable to create directory for '%s': "1933"%s", logfile,strerror(errno));1934else if(errno == EISDIR)1935strbuf_addf(err,"there are still logs under '%s'",1936 logfile);1937else1938strbuf_addf(err,"unable to append to '%s':%s",1939 logfile,strerror(errno));19401941goto error;1942}1943}else{1944*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1945if(*logfd <0) {1946if(errno == ENOENT || errno == EISDIR) {1947/*1948 * The logfile doesn't already exist,1949 * but that is not an error; it only1950 * means that we won't write log1951 * entries to it.1952 */1953;1954}else{1955strbuf_addf(err,"unable to append to '%s':%s",1956 logfile,strerror(errno));1957goto error;1958}1959}1960}19611962if(*logfd >=0)1963adjust_shared_perm(logfile);19641965free(logfile);1966return0;19671968error:1969free(logfile);1970return-1;1971}19721973static intfiles_create_reflog(struct ref_store *ref_store,1974const char*refname,int force_create,1975struct strbuf *err)1976{1977struct files_ref_store *refs =1978files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1979int fd;19801981if(log_ref_setup(refs, refname, force_create, &fd, err))1982return-1;19831984if(fd >=0)1985close(fd);19861987return0;1988}19891990static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,1991const unsigned char*new_sha1,1992const char*committer,const char*msg)1993{1994int msglen, written;1995unsigned maxlen, len;1996char*logrec;19971998 msglen = msg ?strlen(msg) :0;1999 maxlen =strlen(committer) + msglen +100;2000 logrec =xmalloc(maxlen);2001 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2002sha1_to_hex(old_sha1),2003sha1_to_hex(new_sha1),2004 committer);2005if(msglen)2006 len +=copy_reflog_msg(logrec + len -1, msg) -1;20072008 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2009free(logrec);2010if(written != len)2011return-1;20122013return0;2014}20152016static intfiles_log_ref_write(struct files_ref_store *refs,2017const char*refname,const unsigned char*old_sha1,2018const unsigned char*new_sha1,const char*msg,2019int flags,struct strbuf *err)2020{2021int logfd, result;20222023if(log_all_ref_updates == LOG_REFS_UNSET)2024 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20252026 result =log_ref_setup(refs, refname,2027 flags & REF_FORCE_CREATE_REFLOG,2028&logfd, err);20292030if(result)2031return result;20322033if(logfd <0)2034return0;2035 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2036git_committer_info(0), msg);2037if(result) {2038struct strbuf sb = STRBUF_INIT;2039int save_errno = errno;20402041files_reflog_path(refs, &sb, refname);2042strbuf_addf(err,"unable to append to '%s':%s",2043 sb.buf,strerror(save_errno));2044strbuf_release(&sb);2045close(logfd);2046return-1;2047}2048if(close(logfd)) {2049struct strbuf sb = STRBUF_INIT;2050int save_errno = errno;20512052files_reflog_path(refs, &sb, refname);2053strbuf_addf(err,"unable to append to '%s':%s",2054 sb.buf,strerror(save_errno));2055strbuf_release(&sb);2056return-1;2057}2058return0;2059}20602061/*2062 * Write sha1 into the open lockfile, then close the lockfile. On2063 * errors, rollback the lockfile, fill in *err and2064 * return -1.2065 */2066static intwrite_ref_to_lockfile(struct ref_lock *lock,2067const unsigned char*sha1,struct strbuf *err)2068{2069static char term ='\n';2070struct object *o;2071int fd;20722073 o =parse_object(sha1);2074if(!o) {2075strbuf_addf(err,2076"trying to write ref '%s' with nonexistent object%s",2077 lock->ref_name,sha1_to_hex(sha1));2078unlock_ref(lock);2079return-1;2080}2081if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2082strbuf_addf(err,2083"trying to write non-commit object%sto branch '%s'",2084sha1_to_hex(sha1), lock->ref_name);2085unlock_ref(lock);2086return-1;2087}2088 fd =get_lock_file_fd(lock->lk);2089if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2090write_in_full(fd, &term,1) !=1||2091close_ref(lock) <0) {2092strbuf_addf(err,2093"couldn't write '%s'",get_lock_file_path(lock->lk));2094unlock_ref(lock);2095return-1;2096}2097return0;2098}20992100/*2101 * Commit a change to a loose reference that has already been written2102 * to the loose reference lockfile. Also update the reflogs if2103 * necessary, using the specified lockmsg (which can be NULL).2104 */2105static intcommit_ref_update(struct files_ref_store *refs,2106struct ref_lock *lock,2107const unsigned char*sha1,const char*logmsg,2108struct strbuf *err)2109{2110files_assert_main_repository(refs,"commit_ref_update");21112112clear_loose_ref_cache(refs);2113if(files_log_ref_write(refs, lock->ref_name,2114 lock->old_oid.hash, sha1,2115 logmsg,0, err)) {2116char*old_msg =strbuf_detach(err, NULL);2117strbuf_addf(err,"cannot update the ref '%s':%s",2118 lock->ref_name, old_msg);2119free(old_msg);2120unlock_ref(lock);2121return-1;2122}21232124if(strcmp(lock->ref_name,"HEAD") !=0) {2125/*2126 * Special hack: If a branch is updated directly and HEAD2127 * points to it (may happen on the remote side of a push2128 * for example) then logically the HEAD reflog should be2129 * updated too.2130 * A generic solution implies reverse symref information,2131 * but finding all symrefs pointing to the given branch2132 * would be rather costly for this rare event (the direct2133 * update of a branch) to be worth it. So let's cheat and2134 * check with HEAD only which should cover 99% of all usage2135 * scenarios (even 100% of the default ones).2136 */2137unsigned char head_sha1[20];2138int head_flag;2139const char*head_ref;21402141 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2142 RESOLVE_REF_READING,2143 head_sha1, &head_flag);2144if(head_ref && (head_flag & REF_ISSYMREF) &&2145!strcmp(head_ref, lock->ref_name)) {2146struct strbuf log_err = STRBUF_INIT;2147if(files_log_ref_write(refs,"HEAD",2148 lock->old_oid.hash, sha1,2149 logmsg,0, &log_err)) {2150error("%s", log_err.buf);2151strbuf_release(&log_err);2152}2153}2154}21552156if(commit_ref(lock)) {2157strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2158unlock_ref(lock);2159return-1;2160}21612162unlock_ref(lock);2163return0;2164}21652166static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2167{2168int ret = -1;2169#ifndef NO_SYMLINK_HEAD2170char*ref_path =get_locked_file_path(lock->lk);2171unlink(ref_path);2172 ret =symlink(target, ref_path);2173free(ref_path);21742175if(ret)2176fprintf(stderr,"no symlink - falling back to symbolic ref\n");2177#endif2178return ret;2179}21802181static voidupdate_symref_reflog(struct files_ref_store *refs,2182struct ref_lock *lock,const char*refname,2183const char*target,const char*logmsg)2184{2185struct strbuf err = STRBUF_INIT;2186unsigned char new_sha1[20];2187if(logmsg &&2188!refs_read_ref_full(&refs->base, target,2189 RESOLVE_REF_READING, new_sha1, NULL) &&2190files_log_ref_write(refs, refname, lock->old_oid.hash,2191 new_sha1, logmsg,0, &err)) {2192error("%s", err.buf);2193strbuf_release(&err);2194}2195}21962197static intcreate_symref_locked(struct files_ref_store *refs,2198struct ref_lock *lock,const char*refname,2199const char*target,const char*logmsg)2200{2201if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2202update_symref_reflog(refs, lock, refname, target, logmsg);2203return0;2204}22052206if(!fdopen_lock_file(lock->lk,"w"))2207returnerror("unable to fdopen%s:%s",2208 lock->lk->tempfile.filename.buf,strerror(errno));22092210update_symref_reflog(refs, lock, refname, target, logmsg);22112212/* no error check; commit_ref will check ferror */2213fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2214if(commit_ref(lock) <0)2215returnerror("unable to write symref for%s:%s", refname,2216strerror(errno));2217return0;2218}22192220static intfiles_create_symref(struct ref_store *ref_store,2221const char*refname,const char*target,2222const char*logmsg)2223{2224struct files_ref_store *refs =2225files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2226struct strbuf err = STRBUF_INIT;2227struct ref_lock *lock;2228int ret;22292230 lock =lock_ref_sha1_basic(refs, refname, NULL,2231 NULL, NULL, REF_NODEREF, NULL,2232&err);2233if(!lock) {2234error("%s", err.buf);2235strbuf_release(&err);2236return-1;2237}22382239 ret =create_symref_locked(refs, lock, refname, target, logmsg);2240unlock_ref(lock);2241return ret;2242}22432244intset_worktree_head_symref(const char*gitdir,const char*target,const char*logmsg)2245{2246/*2247 * FIXME: this obviously will not work well for future refs2248 * backends. This function needs to die.2249 */2250struct files_ref_store *refs =2251files_downcast(get_main_ref_store(),2252 REF_STORE_WRITE,2253"set_head_symref");22542255static struct lock_file head_lock;2256struct ref_lock *lock;2257struct strbuf head_path = STRBUF_INIT;2258const char*head_rel;2259int ret;22602261strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2262if(hold_lock_file_for_update(&head_lock, head_path.buf,2263 LOCK_NO_DEREF) <0) {2264struct strbuf err = STRBUF_INIT;2265unable_to_lock_message(head_path.buf, errno, &err);2266error("%s", err.buf);2267strbuf_release(&err);2268strbuf_release(&head_path);2269return-1;2270}22712272/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2273 linked trees */2274 head_rel =remove_leading_path(head_path.buf,2275absolute_path(get_git_common_dir()));2276/* to make use of create_symref_locked(), initialize ref_lock */2277 lock =xcalloc(1,sizeof(struct ref_lock));2278 lock->lk = &head_lock;2279 lock->ref_name =xstrdup(head_rel);22802281 ret =create_symref_locked(refs, lock, head_rel, target, logmsg);22822283unlock_ref(lock);/* will free lock */2284strbuf_release(&head_path);2285return ret;2286}22872288static intfiles_reflog_exists(struct ref_store *ref_store,2289const char*refname)2290{2291struct files_ref_store *refs =2292files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2293struct strbuf sb = STRBUF_INIT;2294struct stat st;2295int ret;22962297files_reflog_path(refs, &sb, refname);2298 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2299strbuf_release(&sb);2300return ret;2301}23022303static intfiles_delete_reflog(struct ref_store *ref_store,2304const char*refname)2305{2306struct files_ref_store *refs =2307files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2308struct strbuf sb = STRBUF_INIT;2309int ret;23102311files_reflog_path(refs, &sb, refname);2312 ret =remove_path(sb.buf);2313strbuf_release(&sb);2314return ret;2315}23162317static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2318{2319struct object_id ooid, noid;2320char*email_end, *message;2321unsigned long timestamp;2322int tz;2323const char*p = sb->buf;23242325/* old SP new SP name <email> SP time TAB msg LF */2326if(!sb->len || sb->buf[sb->len -1] !='\n'||2327parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2328parse_oid_hex(p, &noid, &p) || *p++ !=' '||2329!(email_end =strchr(p,'>')) ||2330 email_end[1] !=' '||2331!(timestamp =strtoul(email_end +2, &message,10)) ||2332!message || message[0] !=' '||2333(message[1] !='+'&& message[1] !='-') ||2334!isdigit(message[2]) || !isdigit(message[3]) ||2335!isdigit(message[4]) || !isdigit(message[5]))2336return0;/* corrupt? */2337 email_end[1] ='\0';2338 tz =strtol(message +1, NULL,10);2339if(message[6] !='\t')2340 message +=6;2341else2342 message +=7;2343returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2344}23452346static char*find_beginning_of_line(char*bob,char*scan)2347{2348while(bob < scan && *(--scan) !='\n')2349;/* keep scanning backwards */2350/*2351 * Return either beginning of the buffer, or LF at the end of2352 * the previous line.2353 */2354return scan;2355}23562357static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2358const char*refname,2359 each_reflog_ent_fn fn,2360void*cb_data)2361{2362struct files_ref_store *refs =2363files_downcast(ref_store, REF_STORE_READ,2364"for_each_reflog_ent_reverse");2365struct strbuf sb = STRBUF_INIT;2366FILE*logfp;2367long pos;2368int ret =0, at_tail =1;23692370files_reflog_path(refs, &sb, refname);2371 logfp =fopen(sb.buf,"r");2372strbuf_release(&sb);2373if(!logfp)2374return-1;23752376/* Jump to the end */2377if(fseek(logfp,0, SEEK_END) <0)2378 ret =error("cannot seek back reflog for%s:%s",2379 refname,strerror(errno));2380 pos =ftell(logfp);2381while(!ret &&0< pos) {2382int cnt;2383size_t nread;2384char buf[BUFSIZ];2385char*endp, *scanp;23862387/* Fill next block from the end */2388 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2389if(fseek(logfp, pos - cnt, SEEK_SET)) {2390 ret =error("cannot seek back reflog for%s:%s",2391 refname,strerror(errno));2392break;2393}2394 nread =fread(buf, cnt,1, logfp);2395if(nread !=1) {2396 ret =error("cannot read%dbytes from reflog for%s:%s",2397 cnt, refname,strerror(errno));2398break;2399}2400 pos -= cnt;24012402 scanp = endp = buf + cnt;2403if(at_tail && scanp[-1] =='\n')2404/* Looking at the final LF at the end of the file */2405 scanp--;2406 at_tail =0;24072408while(buf < scanp) {2409/*2410 * terminating LF of the previous line, or the beginning2411 * of the buffer.2412 */2413char*bp;24142415 bp =find_beginning_of_line(buf, scanp);24162417if(*bp =='\n') {2418/*2419 * The newline is the end of the previous line,2420 * so we know we have complete line starting2421 * at (bp + 1). Prefix it onto any prior data2422 * we collected for the line and process it.2423 */2424strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2425 scanp = bp;2426 endp = bp +1;2427 ret =show_one_reflog_ent(&sb, fn, cb_data);2428strbuf_reset(&sb);2429if(ret)2430break;2431}else if(!pos) {2432/*2433 * We are at the start of the buffer, and the2434 * start of the file; there is no previous2435 * line, and we have everything for this one.2436 * Process it, and we can end the loop.2437 */2438strbuf_splice(&sb,0,0, buf, endp - buf);2439 ret =show_one_reflog_ent(&sb, fn, cb_data);2440strbuf_reset(&sb);2441break;2442}24432444if(bp == buf) {2445/*2446 * We are at the start of the buffer, and there2447 * is more file to read backwards. Which means2448 * we are in the middle of a line. Note that we2449 * may get here even if *bp was a newline; that2450 * just means we are at the exact end of the2451 * previous line, rather than some spot in the2452 * middle.2453 *2454 * Save away what we have to be combined with2455 * the data from the next read.2456 */2457strbuf_splice(&sb,0,0, buf, endp - buf);2458break;2459}2460}24612462}2463if(!ret && sb.len)2464die("BUG: reverse reflog parser had leftover data");24652466fclose(logfp);2467strbuf_release(&sb);2468return ret;2469}24702471static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2472const char*refname,2473 each_reflog_ent_fn fn,void*cb_data)2474{2475struct files_ref_store *refs =2476files_downcast(ref_store, REF_STORE_READ,2477"for_each_reflog_ent");2478FILE*logfp;2479struct strbuf sb = STRBUF_INIT;2480int ret =0;24812482files_reflog_path(refs, &sb, refname);2483 logfp =fopen(sb.buf,"r");2484strbuf_release(&sb);2485if(!logfp)2486return-1;24872488while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2489 ret =show_one_reflog_ent(&sb, fn, cb_data);2490fclose(logfp);2491strbuf_release(&sb);2492return ret;2493}24942495struct files_reflog_iterator {2496struct ref_iterator base;24972498struct ref_store *ref_store;2499struct dir_iterator *dir_iterator;2500struct object_id oid;2501};25022503static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2504{2505struct files_reflog_iterator *iter =2506(struct files_reflog_iterator *)ref_iterator;2507struct dir_iterator *diter = iter->dir_iterator;2508int ok;25092510while((ok =dir_iterator_advance(diter)) == ITER_OK) {2511int flags;25122513if(!S_ISREG(diter->st.st_mode))2514continue;2515if(diter->basename[0] =='.')2516continue;2517if(ends_with(diter->basename,".lock"))2518continue;25192520if(refs_read_ref_full(iter->ref_store,2521 diter->relative_path,0,2522 iter->oid.hash, &flags)) {2523error("bad ref for%s", diter->path.buf);2524continue;2525}25262527 iter->base.refname = diter->relative_path;2528 iter->base.oid = &iter->oid;2529 iter->base.flags = flags;2530return ITER_OK;2531}25322533 iter->dir_iterator = NULL;2534if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2535 ok = ITER_ERROR;2536return ok;2537}25382539static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2540struct object_id *peeled)2541{2542die("BUG: ref_iterator_peel() called for reflog_iterator");2543}25442545static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2546{2547struct files_reflog_iterator *iter =2548(struct files_reflog_iterator *)ref_iterator;2549int ok = ITER_DONE;25502551if(iter->dir_iterator)2552 ok =dir_iterator_abort(iter->dir_iterator);25532554base_ref_iterator_free(ref_iterator);2555return ok;2556}25572558static struct ref_iterator_vtable files_reflog_iterator_vtable = {2559 files_reflog_iterator_advance,2560 files_reflog_iterator_peel,2561 files_reflog_iterator_abort2562};25632564static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2565{2566struct files_ref_store *refs =2567files_downcast(ref_store, REF_STORE_READ,2568"reflog_iterator_begin");2569struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2570struct ref_iterator *ref_iterator = &iter->base;2571struct strbuf sb = STRBUF_INIT;25722573base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2574files_reflog_path(refs, &sb, NULL);2575 iter->dir_iterator =dir_iterator_begin(sb.buf);2576 iter->ref_store = ref_store;2577strbuf_release(&sb);2578return ref_iterator;2579}25802581static intref_update_reject_duplicates(struct string_list *refnames,2582struct strbuf *err)2583{2584int i, n = refnames->nr;25852586assert(err);25872588for(i =1; i < n; i++)2589if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {2590strbuf_addf(err,2591"multiple updates for ref '%s' not allowed.",2592 refnames->items[i].string);2593return1;2594}2595return0;2596}25972598/*2599 * If update is a direct update of head_ref (the reference pointed to2600 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2601 */2602static intsplit_head_update(struct ref_update *update,2603struct ref_transaction *transaction,2604const char*head_ref,2605struct string_list *affected_refnames,2606struct strbuf *err)2607{2608struct string_list_item *item;2609struct ref_update *new_update;26102611if((update->flags & REF_LOG_ONLY) ||2612(update->flags & REF_ISPRUNING) ||2613(update->flags & REF_UPDATE_VIA_HEAD))2614return0;26152616if(strcmp(update->refname, head_ref))2617return0;26182619/*2620 * First make sure that HEAD is not already in the2621 * transaction. This insertion is O(N) in the transaction2622 * size, but it happens at most once per transaction.2623 */2624 item =string_list_insert(affected_refnames,"HEAD");2625if(item->util) {2626/* An entry already existed */2627strbuf_addf(err,2628"multiple updates for 'HEAD' (including one "2629"via its referent '%s') are not allowed",2630 update->refname);2631return TRANSACTION_NAME_CONFLICT;2632}26332634 new_update =ref_transaction_add_update(2635 transaction,"HEAD",2636 update->flags | REF_LOG_ONLY | REF_NODEREF,2637 update->new_sha1, update->old_sha1,2638 update->msg);26392640 item->util = new_update;26412642return0;2643}26442645/*2646 * update is for a symref that points at referent and doesn't have2647 * REF_NODEREF set. Split it into two updates:2648 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2649 * - A new, separate update for the referent reference2650 * Note that the new update will itself be subject to splitting when2651 * the iteration gets to it.2652 */2653static intsplit_symref_update(struct files_ref_store *refs,2654struct ref_update *update,2655const char*referent,2656struct ref_transaction *transaction,2657struct string_list *affected_refnames,2658struct strbuf *err)2659{2660struct string_list_item *item;2661struct ref_update *new_update;2662unsigned int new_flags;26632664/*2665 * First make sure that referent is not already in the2666 * transaction. This insertion is O(N) in the transaction2667 * size, but it happens at most once per symref in a2668 * transaction.2669 */2670 item =string_list_insert(affected_refnames, referent);2671if(item->util) {2672/* An entry already existed */2673strbuf_addf(err,2674"multiple updates for '%s' (including one "2675"via symref '%s') are not allowed",2676 referent, update->refname);2677return TRANSACTION_NAME_CONFLICT;2678}26792680 new_flags = update->flags;2681if(!strcmp(update->refname,"HEAD")) {2682/*2683 * Record that the new update came via HEAD, so that2684 * when we process it, split_head_update() doesn't try2685 * to add another reflog update for HEAD. Note that2686 * this bit will be propagated if the new_update2687 * itself needs to be split.2688 */2689 new_flags |= REF_UPDATE_VIA_HEAD;2690}26912692 new_update =ref_transaction_add_update(2693 transaction, referent, new_flags,2694 update->new_sha1, update->old_sha1,2695 update->msg);26962697 new_update->parent_update = update;26982699/*2700 * Change the symbolic ref update to log only. Also, it2701 * doesn't need to check its old SHA-1 value, as that will be2702 * done when new_update is processed.2703 */2704 update->flags |= REF_LOG_ONLY | REF_NODEREF;2705 update->flags &= ~REF_HAVE_OLD;27062707 item->util = new_update;27082709return0;2710}27112712/*2713 * Return the refname under which update was originally requested.2714 */2715static const char*original_update_refname(struct ref_update *update)2716{2717while(update->parent_update)2718 update = update->parent_update;27192720return update->refname;2721}27222723/*2724 * Check whether the REF_HAVE_OLD and old_oid values stored in update2725 * are consistent with oid, which is the reference's current value. If2726 * everything is OK, return 0; otherwise, write an error message to2727 * err and return -1.2728 */2729static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2730struct strbuf *err)2731{2732if(!(update->flags & REF_HAVE_OLD) ||2733!hashcmp(oid->hash, update->old_sha1))2734return0;27352736if(is_null_sha1(update->old_sha1))2737strbuf_addf(err,"cannot lock ref '%s': "2738"reference already exists",2739original_update_refname(update));2740else if(is_null_oid(oid))2741strbuf_addf(err,"cannot lock ref '%s': "2742"reference is missing but expected%s",2743original_update_refname(update),2744sha1_to_hex(update->old_sha1));2745else2746strbuf_addf(err,"cannot lock ref '%s': "2747"is at%sbut expected%s",2748original_update_refname(update),2749oid_to_hex(oid),2750sha1_to_hex(update->old_sha1));27512752return-1;2753}27542755/*2756 * Prepare for carrying out update:2757 * - Lock the reference referred to by update.2758 * - Read the reference under lock.2759 * - Check that its old SHA-1 value (if specified) is correct, and in2760 * any case record it in update->lock->old_oid for later use when2761 * writing the reflog.2762 * - If it is a symref update without REF_NODEREF, split it up into a2763 * REF_LOG_ONLY update of the symref and add a separate update for2764 * the referent to transaction.2765 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2766 * update of HEAD.2767 */2768static intlock_ref_for_update(struct files_ref_store *refs,2769struct ref_update *update,2770struct ref_transaction *transaction,2771const char*head_ref,2772struct string_list *affected_refnames,2773struct strbuf *err)2774{2775struct strbuf referent = STRBUF_INIT;2776int mustexist = (update->flags & REF_HAVE_OLD) &&2777!is_null_sha1(update->old_sha1);2778int ret;2779struct ref_lock *lock;27802781files_assert_main_repository(refs,"lock_ref_for_update");27822783if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))2784 update->flags |= REF_DELETING;27852786if(head_ref) {2787 ret =split_head_update(update, transaction, head_ref,2788 affected_refnames, err);2789if(ret)2790return ret;2791}27922793 ret =lock_raw_ref(refs, update->refname, mustexist,2794 affected_refnames, NULL,2795&lock, &referent,2796&update->type, err);2797if(ret) {2798char*reason;27992800 reason =strbuf_detach(err, NULL);2801strbuf_addf(err,"cannot lock ref '%s':%s",2802original_update_refname(update), reason);2803free(reason);2804return ret;2805}28062807 update->backend_data = lock;28082809if(update->type & REF_ISSYMREF) {2810if(update->flags & REF_NODEREF) {2811/*2812 * We won't be reading the referent as part of2813 * the transaction, so we have to read it here2814 * to record and possibly check old_sha1:2815 */2816if(refs_read_ref_full(&refs->base,2817 referent.buf,0,2818 lock->old_oid.hash, NULL)) {2819if(update->flags & REF_HAVE_OLD) {2820strbuf_addf(err,"cannot lock ref '%s': "2821"error reading reference",2822original_update_refname(update));2823return-1;2824}2825}else if(check_old_oid(update, &lock->old_oid, err)) {2826return TRANSACTION_GENERIC_ERROR;2827}2828}else{2829/*2830 * Create a new update for the reference this2831 * symref is pointing at. Also, we will record2832 * and verify old_sha1 for this update as part2833 * of processing the split-off update, so we2834 * don't have to do it here.2835 */2836 ret =split_symref_update(refs, update,2837 referent.buf, transaction,2838 affected_refnames, err);2839if(ret)2840return ret;2841}2842}else{2843struct ref_update *parent_update;28442845if(check_old_oid(update, &lock->old_oid, err))2846return TRANSACTION_GENERIC_ERROR;28472848/*2849 * If this update is happening indirectly because of a2850 * symref update, record the old SHA-1 in the parent2851 * update:2852 */2853for(parent_update = update->parent_update;2854 parent_update;2855 parent_update = parent_update->parent_update) {2856struct ref_lock *parent_lock = parent_update->backend_data;2857oidcpy(&parent_lock->old_oid, &lock->old_oid);2858}2859}28602861if((update->flags & REF_HAVE_NEW) &&2862!(update->flags & REF_DELETING) &&2863!(update->flags & REF_LOG_ONLY)) {2864if(!(update->type & REF_ISSYMREF) &&2865!hashcmp(lock->old_oid.hash, update->new_sha1)) {2866/*2867 * The reference already has the desired2868 * value, so we don't need to write it.2869 */2870}else if(write_ref_to_lockfile(lock, update->new_sha1,2871 err)) {2872char*write_err =strbuf_detach(err, NULL);28732874/*2875 * The lock was freed upon failure of2876 * write_ref_to_lockfile():2877 */2878 update->backend_data = NULL;2879strbuf_addf(err,2880"cannot update ref '%s':%s",2881 update->refname, write_err);2882free(write_err);2883return TRANSACTION_GENERIC_ERROR;2884}else{2885 update->flags |= REF_NEEDS_COMMIT;2886}2887}2888if(!(update->flags & REF_NEEDS_COMMIT)) {2889/*2890 * We didn't call write_ref_to_lockfile(), so2891 * the lockfile is still open. Close it to2892 * free up the file descriptor:2893 */2894if(close_ref(lock)) {2895strbuf_addf(err,"couldn't close '%s.lock'",2896 update->refname);2897return TRANSACTION_GENERIC_ERROR;2898}2899}2900return0;2901}29022903static intfiles_transaction_commit(struct ref_store *ref_store,2904struct ref_transaction *transaction,2905struct strbuf *err)2906{2907struct files_ref_store *refs =2908files_downcast(ref_store, REF_STORE_WRITE,2909"ref_transaction_commit");2910int ret =0, i;2911struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2912struct string_list_item *ref_to_delete;2913struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2914char*head_ref = NULL;2915int head_type;2916struct object_id head_oid;2917struct strbuf sb = STRBUF_INIT;29182919assert(err);29202921if(transaction->state != REF_TRANSACTION_OPEN)2922die("BUG: commit called for transaction that is not open");29232924if(!transaction->nr) {2925 transaction->state = REF_TRANSACTION_CLOSED;2926return0;2927}29282929/*2930 * Fail if a refname appears more than once in the2931 * transaction. (If we end up splitting up any updates using2932 * split_symref_update() or split_head_update(), those2933 * functions will check that the new updates don't have the2934 * same refname as any existing ones.)2935 */2936for(i =0; i < transaction->nr; i++) {2937struct ref_update *update = transaction->updates[i];2938struct string_list_item *item =2939string_list_append(&affected_refnames, update->refname);29402941/*2942 * We store a pointer to update in item->util, but at2943 * the moment we never use the value of this field2944 * except to check whether it is non-NULL.2945 */2946 item->util = update;2947}2948string_list_sort(&affected_refnames);2949if(ref_update_reject_duplicates(&affected_refnames, err)) {2950 ret = TRANSACTION_GENERIC_ERROR;2951goto cleanup;2952}29532954/*2955 * Special hack: If a branch is updated directly and HEAD2956 * points to it (may happen on the remote side of a push2957 * for example) then logically the HEAD reflog should be2958 * updated too.2959 *2960 * A generic solution would require reverse symref lookups,2961 * but finding all symrefs pointing to a given branch would be2962 * rather costly for this rare event (the direct update of a2963 * branch) to be worth it. So let's cheat and check with HEAD2964 * only, which should cover 99% of all usage scenarios (even2965 * 100% of the default ones).2966 *2967 * So if HEAD is a symbolic reference, then record the name of2968 * the reference that it points to. If we see an update of2969 * head_ref within the transaction, then split_head_update()2970 * arranges for the reflog of HEAD to be updated, too.2971 */2972 head_ref =refs_resolve_refdup(ref_store,"HEAD",2973 RESOLVE_REF_NO_RECURSE,2974 head_oid.hash, &head_type);29752976if(head_ref && !(head_type & REF_ISSYMREF)) {2977free(head_ref);2978 head_ref = NULL;2979}29802981/*2982 * Acquire all locks, verify old values if provided, check2983 * that new values are valid, and write new values to the2984 * lockfiles, ready to be activated. Only keep one lockfile2985 * open at a time to avoid running out of file descriptors.2986 */2987for(i =0; i < transaction->nr; i++) {2988struct ref_update *update = transaction->updates[i];29892990 ret =lock_ref_for_update(refs, update, transaction,2991 head_ref, &affected_refnames, err);2992if(ret)2993goto cleanup;2994}29952996/* Perform updates first so live commits remain referenced */2997for(i =0; i < transaction->nr; i++) {2998struct ref_update *update = transaction->updates[i];2999struct ref_lock *lock = update->backend_data;30003001if(update->flags & REF_NEEDS_COMMIT ||3002 update->flags & REF_LOG_ONLY) {3003if(files_log_ref_write(refs,3004 lock->ref_name,3005 lock->old_oid.hash,3006 update->new_sha1,3007 update->msg, update->flags,3008 err)) {3009char*old_msg =strbuf_detach(err, NULL);30103011strbuf_addf(err,"cannot update the ref '%s':%s",3012 lock->ref_name, old_msg);3013free(old_msg);3014unlock_ref(lock);3015 update->backend_data = NULL;3016 ret = TRANSACTION_GENERIC_ERROR;3017goto cleanup;3018}3019}3020if(update->flags & REF_NEEDS_COMMIT) {3021clear_loose_ref_cache(refs);3022if(commit_ref(lock)) {3023strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3024unlock_ref(lock);3025 update->backend_data = NULL;3026 ret = TRANSACTION_GENERIC_ERROR;3027goto cleanup;3028}3029}3030}3031/* Perform deletes now that updates are safely completed */3032for(i =0; i < transaction->nr; i++) {3033struct ref_update *update = transaction->updates[i];3034struct ref_lock *lock = update->backend_data;30353036if(update->flags & REF_DELETING &&3037!(update->flags & REF_LOG_ONLY)) {3038if(!(update->type & REF_ISPACKED) ||3039 update->type & REF_ISSYMREF) {3040/* It is a loose reference. */3041strbuf_reset(&sb);3042files_ref_path(refs, &sb, lock->ref_name);3043if(unlink_or_msg(sb.buf, err)) {3044 ret = TRANSACTION_GENERIC_ERROR;3045goto cleanup;3046}3047 update->flags |= REF_DELETED_LOOSE;3048}30493050if(!(update->flags & REF_ISPRUNING))3051string_list_append(&refs_to_delete,3052 lock->ref_name);3053}3054}30553056if(repack_without_refs(refs, &refs_to_delete, err)) {3057 ret = TRANSACTION_GENERIC_ERROR;3058goto cleanup;3059}30603061/* Delete the reflogs of any references that were deleted: */3062for_each_string_list_item(ref_to_delete, &refs_to_delete) {3063strbuf_reset(&sb);3064files_reflog_path(refs, &sb, ref_to_delete->string);3065if(!unlink_or_warn(sb.buf))3066try_remove_empty_parents(refs, ref_to_delete->string,3067 REMOVE_EMPTY_PARENTS_REFLOG);3068}30693070clear_loose_ref_cache(refs);30713072cleanup:3073strbuf_release(&sb);3074 transaction->state = REF_TRANSACTION_CLOSED;30753076for(i =0; i < transaction->nr; i++) {3077struct ref_update *update = transaction->updates[i];3078struct ref_lock *lock = update->backend_data;30793080if(lock)3081unlock_ref(lock);30823083if(update->flags & REF_DELETED_LOOSE) {3084/*3085 * The loose reference was deleted. Delete any3086 * empty parent directories. (Note that this3087 * can only work because we have already3088 * removed the lockfile.)3089 */3090try_remove_empty_parents(refs, update->refname,3091 REMOVE_EMPTY_PARENTS_REF);3092}3093}30943095string_list_clear(&refs_to_delete,0);3096free(head_ref);3097string_list_clear(&affected_refnames,0);30983099return ret;3100}31013102static intref_present(const char*refname,3103const struct object_id *oid,int flags,void*cb_data)3104{3105struct string_list *affected_refnames = cb_data;31063107returnstring_list_has_string(affected_refnames, refname);3108}31093110static intfiles_initial_transaction_commit(struct ref_store *ref_store,3111struct ref_transaction *transaction,3112struct strbuf *err)3113{3114struct files_ref_store *refs =3115files_downcast(ref_store, REF_STORE_WRITE,3116"initial_ref_transaction_commit");3117int ret =0, i;3118struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31193120assert(err);31213122if(transaction->state != REF_TRANSACTION_OPEN)3123die("BUG: commit called for transaction that is not open");31243125/* Fail if a refname appears more than once in the transaction: */3126for(i =0; i < transaction->nr; i++)3127string_list_append(&affected_refnames,3128 transaction->updates[i]->refname);3129string_list_sort(&affected_refnames);3130if(ref_update_reject_duplicates(&affected_refnames, err)) {3131 ret = TRANSACTION_GENERIC_ERROR;3132goto cleanup;3133}31343135/*3136 * It's really undefined to call this function in an active3137 * repository or when there are existing references: we are3138 * only locking and changing packed-refs, so (1) any3139 * simultaneous processes might try to change a reference at3140 * the same time we do, and (2) any existing loose versions of3141 * the references that we are setting would have precedence3142 * over our values. But some remote helpers create the remote3143 * "HEAD" and "master" branches before calling this function,3144 * so here we really only check that none of the references3145 * that we are creating already exists.3146 */3147if(refs_for_each_rawref(&refs->base, ref_present,3148&affected_refnames))3149die("BUG: initial ref transaction called with existing refs");31503151for(i =0; i < transaction->nr; i++) {3152struct ref_update *update = transaction->updates[i];31533154if((update->flags & REF_HAVE_OLD) &&3155!is_null_sha1(update->old_sha1))3156die("BUG: initial ref transaction with old_sha1 set");3157if(refs_verify_refname_available(&refs->base, update->refname,3158&affected_refnames, NULL,3159 err)) {3160 ret = TRANSACTION_NAME_CONFLICT;3161goto cleanup;3162}3163}31643165if(lock_packed_refs(refs,0)) {3166strbuf_addf(err,"unable to lock packed-refs file:%s",3167strerror(errno));3168 ret = TRANSACTION_GENERIC_ERROR;3169goto cleanup;3170}31713172for(i =0; i < transaction->nr; i++) {3173struct ref_update *update = transaction->updates[i];31743175if((update->flags & REF_HAVE_NEW) &&3176!is_null_sha1(update->new_sha1))3177add_packed_ref(refs, update->refname, update->new_sha1);3178}31793180if(commit_packed_refs(refs)) {3181strbuf_addf(err,"unable to commit packed-refs file:%s",3182strerror(errno));3183 ret = TRANSACTION_GENERIC_ERROR;3184goto cleanup;3185}31863187cleanup:3188 transaction->state = REF_TRANSACTION_CLOSED;3189string_list_clear(&affected_refnames,0);3190return ret;3191}31923193struct expire_reflog_cb {3194unsigned int flags;3195 reflog_expiry_should_prune_fn *should_prune_fn;3196void*policy_cb;3197FILE*newlog;3198struct object_id last_kept_oid;3199};32003201static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3202const char*email,unsigned long timestamp,int tz,3203const char*message,void*cb_data)3204{3205struct expire_reflog_cb *cb = cb_data;3206struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32073208if(cb->flags & EXPIRE_REFLOGS_REWRITE)3209 ooid = &cb->last_kept_oid;32103211if((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,3212 message, policy_cb)) {3213if(!cb->newlog)3214printf("would prune%s", message);3215else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3216printf("prune%s", message);3217}else{3218if(cb->newlog) {3219fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3220oid_to_hex(ooid),oid_to_hex(noid),3221 email, timestamp, tz, message);3222oidcpy(&cb->last_kept_oid, noid);3223}3224if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3225printf("keep%s", message);3226}3227return0;3228}32293230static intfiles_reflog_expire(struct ref_store *ref_store,3231const char*refname,const unsigned char*sha1,3232unsigned int flags,3233 reflog_expiry_prepare_fn prepare_fn,3234 reflog_expiry_should_prune_fn should_prune_fn,3235 reflog_expiry_cleanup_fn cleanup_fn,3236void*policy_cb_data)3237{3238struct files_ref_store *refs =3239files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3240static struct lock_file reflog_lock;3241struct expire_reflog_cb cb;3242struct ref_lock *lock;3243struct strbuf log_file_sb = STRBUF_INIT;3244char*log_file;3245int status =0;3246int type;3247struct strbuf err = STRBUF_INIT;32483249memset(&cb,0,sizeof(cb));3250 cb.flags = flags;3251 cb.policy_cb = policy_cb_data;3252 cb.should_prune_fn = should_prune_fn;32533254/*3255 * The reflog file is locked by holding the lock on the3256 * reference itself, plus we might need to update the3257 * reference if --updateref was specified:3258 */3259 lock =lock_ref_sha1_basic(refs, refname, sha1,3260 NULL, NULL, REF_NODEREF,3261&type, &err);3262if(!lock) {3263error("cannot lock ref '%s':%s", refname, err.buf);3264strbuf_release(&err);3265return-1;3266}3267if(!refs_reflog_exists(ref_store, refname)) {3268unlock_ref(lock);3269return0;3270}32713272files_reflog_path(refs, &log_file_sb, refname);3273 log_file =strbuf_detach(&log_file_sb, NULL);3274if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3275/*3276 * Even though holding $GIT_DIR/logs/$reflog.lock has3277 * no locking implications, we use the lock_file3278 * machinery here anyway because it does a lot of the3279 * work we need, including cleaning up if the program3280 * exits unexpectedly.3281 */3282if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3283struct strbuf err = STRBUF_INIT;3284unable_to_lock_message(log_file, errno, &err);3285error("%s", err.buf);3286strbuf_release(&err);3287goto failure;3288}3289 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3290if(!cb.newlog) {3291error("cannot fdopen%s(%s)",3292get_lock_file_path(&reflog_lock),strerror(errno));3293goto failure;3294}3295}32963297(*prepare_fn)(refname, sha1, cb.policy_cb);3298refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3299(*cleanup_fn)(cb.policy_cb);33003301if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3302/*3303 * It doesn't make sense to adjust a reference pointed3304 * to by a symbolic ref based on expiring entries in3305 * the symbolic reference's reflog. Nor can we update3306 * a reference if there are no remaining reflog3307 * entries.3308 */3309int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3310!(type & REF_ISSYMREF) &&3311!is_null_oid(&cb.last_kept_oid);33123313if(close_lock_file(&reflog_lock)) {3314 status |=error("couldn't write%s:%s", log_file,3315strerror(errno));3316}else if(update &&3317(write_in_full(get_lock_file_fd(lock->lk),3318oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3319write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3320close_ref(lock) <0)) {3321 status |=error("couldn't write%s",3322get_lock_file_path(lock->lk));3323rollback_lock_file(&reflog_lock);3324}else if(commit_lock_file(&reflog_lock)) {3325 status |=error("unable to write reflog '%s' (%s)",3326 log_file,strerror(errno));3327}else if(update &&commit_ref(lock)) {3328 status |=error("couldn't set%s", lock->ref_name);3329}3330}3331free(log_file);3332unlock_ref(lock);3333return status;33343335 failure:3336rollback_lock_file(&reflog_lock);3337free(log_file);3338unlock_ref(lock);3339return-1;3340}33413342static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3343{3344struct files_ref_store *refs =3345files_downcast(ref_store, REF_STORE_WRITE,"init_db");3346struct strbuf sb = STRBUF_INIT;33473348/*3349 * Create .git/refs/{heads,tags}3350 */3351files_ref_path(refs, &sb,"refs/heads");3352safe_create_dir(sb.buf,1);33533354strbuf_reset(&sb);3355files_ref_path(refs, &sb,"refs/tags");3356safe_create_dir(sb.buf,1);33573358strbuf_release(&sb);3359return0;3360}33613362struct ref_storage_be refs_be_files = {3363 NULL,3364"files",3365 files_ref_store_create,3366 files_init_db,3367 files_transaction_commit,3368 files_initial_transaction_commit,33693370 files_pack_refs,3371 files_peel_ref,3372 files_create_symref,3373 files_delete_refs,3374 files_rename_ref,33753376 files_ref_iterator_begin,3377 files_read_raw_ref,33783379 files_reflog_iterator_begin,3380 files_for_each_reflog_ent,3381 files_for_each_reflog_ent_reverse,3382 files_reflog_exists,3383 files_create_reflog,3384 files_delete_reflog,3385 files_reflog_expire3386};