1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9struct ref_lock { 10char*ref_name; 11char*orig_ref_name; 12struct lock_file *lk; 13struct object_id old_oid; 14}; 15 16/* 17 * How to handle various characters in refnames: 18 * 0: An acceptable character for refs 19 * 1: End-of-component 20 * 2: ., look for a preceding . to reject .. in refs 21 * 3: {, look for a preceding @ to reject @{ in refs 22 * 4: A bad character: ASCII control characters, and 23 * ":", "?", "[", "\", "^", "~", SP, or TAB 24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,5,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag in ref_update::flags when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Used as a flag in ref_update::flags when the reference should be 51 * updated to new_sha1. 52 */ 53#define REF_HAVE_NEW 0x08 54 55/* 56 * Used as a flag in ref_update::flags when old_sha1 should be 57 * checked. 58 */ 59#define REF_HAVE_OLD 0x10 60 61/* 62 * Used as a flag in ref_update::flags when the lockfile needs to be 63 * committed. 64 */ 65#define REF_NEEDS_COMMIT 0x20 66 67/* 68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a 69 * value to ref_update::flags 70 */ 71 72/* 73 * Try to read one refname component from the front of refname. 74 * Return the length of the component found, or -1 if the component is 75 * not legal. It is legal if it is something reasonable to have under 76 * ".git/refs/"; We do not like it if: 77 * 78 * - any path component of it begins with ".", or 79 * - it has double dots "..", or 80 * - it has ASCII control characters, or 81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 83 * - it ends with a "/", or 84 * - it ends with ".lock", or 85 * - it contains a "@{" portion 86 */ 87static intcheck_refname_component(const char*refname,int*flags) 88{ 89const char*cp; 90char last ='\0'; 91 92for(cp = refname; ; cp++) { 93int ch = *cp &255; 94unsigned char disp = refname_disposition[ch]; 95switch(disp) { 96case1: 97goto out; 98case2: 99if(last =='.') 100return-1;/* Refname contains "..". */ 101break; 102case3: 103if(last =='@') 104return-1;/* Refname contains "@{". */ 105break; 106case4: 107return-1; 108case5: 109if(!(*flags & REFNAME_REFSPEC_PATTERN)) 110return-1;/* refspec can't be a pattern */ 111 112/* 113 * Unset the pattern flag so that we only accept 114 * a single asterisk for one side of refspec. 115 */ 116*flags &= ~ REFNAME_REFSPEC_PATTERN; 117break; 118} 119 last = ch; 120} 121out: 122if(cp == refname) 123return0;/* Component has zero length. */ 124if(refname[0] =='.') 125return-1;/* Component starts with '.'. */ 126if(cp - refname >= LOCK_SUFFIX_LEN && 127!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 128return-1;/* Refname ends with ".lock". */ 129return cp - refname; 130} 131 132intcheck_refname_format(const char*refname,int flags) 133{ 134int component_len, component_count =0; 135 136if(!strcmp(refname,"@")) 137/* Refname is a single character '@'. */ 138return-1; 139 140while(1) { 141/* We are at the start of a path component. */ 142 component_len =check_refname_component(refname, &flags); 143if(component_len <=0) 144return-1; 145 146 component_count++; 147if(refname[component_len] =='\0') 148break; 149/* Skip to next component. */ 150 refname += component_len +1; 151} 152 153if(refname[component_len -1] =='.') 154return-1;/* Refname ends with '.'. */ 155if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 156return-1;/* Refname has only one component. */ 157return0; 158} 159 160struct ref_entry; 161 162/* 163 * Information used (along with the information in ref_entry) to 164 * describe a single cached reference. This data structure only 165 * occurs embedded in a union in struct ref_entry, and only when 166 * (ref_entry->flag & REF_DIR) is zero. 167 */ 168struct ref_value { 169/* 170 * The name of the object to which this reference resolves 171 * (which may be a tag object). If REF_ISBROKEN, this is 172 * null. If REF_ISSYMREF, then this is the name of the object 173 * referred to by the last reference in the symlink chain. 174 */ 175struct object_id oid; 176 177/* 178 * If REF_KNOWS_PEELED, then this field holds the peeled value 179 * of this reference, or null if the reference is known not to 180 * be peelable. See the documentation for peel_ref() for an 181 * exact definition of "peelable". 182 */ 183struct object_id peeled; 184}; 185 186struct ref_cache; 187 188/* 189 * Information used (along with the information in ref_entry) to 190 * describe a level in the hierarchy of references. This data 191 * structure only occurs embedded in a union in struct ref_entry, and 192 * only when (ref_entry.flag & REF_DIR) is set. In that case, 193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 194 * in the directory have already been read: 195 * 196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 197 * or packed references, already read. 198 * 199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 200 * references that hasn't been read yet (nor has any of its 201 * subdirectories). 202 * 203 * Entries within a directory are stored within a growable array of 204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 205 * sorted are sorted by their component name in strcmp() order and the 206 * remaining entries are unsorted. 207 * 208 * Loose references are read lazily, one directory at a time. When a 209 * directory of loose references is read, then all of the references 210 * in that directory are stored, and REF_INCOMPLETE stubs are created 211 * for any subdirectories, but the subdirectories themselves are not 212 * read. The reading is triggered by get_ref_dir(). 213 */ 214struct ref_dir { 215int nr, alloc; 216 217/* 218 * Entries with index 0 <= i < sorted are sorted by name. New 219 * entries are appended to the list unsorted, and are sorted 220 * only when required; thus we avoid the need to sort the list 221 * after the addition of every reference. 222 */ 223int sorted; 224 225/* A pointer to the ref_cache that contains this ref_dir. */ 226struct ref_cache *ref_cache; 227 228struct ref_entry **entries; 229}; 230 231/* 232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 234 * public values; see refs.h. 235 */ 236 237/* 238 * The field ref_entry->u.value.peeled of this value entry contains 239 * the correct peeled value for the reference, which might be 240 * null_sha1 if the reference is not a tag or if it is broken. 241 */ 242#define REF_KNOWS_PEELED 0x10 243 244/* ref_entry represents a directory of references */ 245#define REF_DIR 0x20 246 247/* 248 * Entry has not yet been read from disk (used only for REF_DIR 249 * entries representing loose references) 250 */ 251#define REF_INCOMPLETE 0x40 252 253/* 254 * A ref_entry represents either a reference or a "subdirectory" of 255 * references. 256 * 257 * Each directory in the reference namespace is represented by a 258 * ref_entry with (flags & REF_DIR) set and containing a subdir member 259 * that holds the entries in that directory that have been read so 260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 262 * used for loose reference directories. 263 * 264 * References are represented by a ref_entry with (flags & REF_DIR) 265 * unset and a value member that describes the reference's value. The 266 * flag member is at the ref_entry level, but it is also needed to 267 * interpret the contents of the value field (in other words, a 268 * ref_value object is not very much use without the enclosing 269 * ref_entry). 270 * 271 * Reference names cannot end with slash and directories' names are 272 * always stored with a trailing slash (except for the top-level 273 * directory, which is always denoted by ""). This has two nice 274 * consequences: (1) when the entries in each subdir are sorted 275 * lexicographically by name (as they usually are), the references in 276 * a whole tree can be generated in lexicographic order by traversing 277 * the tree in left-to-right, depth-first order; (2) the names of 278 * references and subdirectories cannot conflict, and therefore the 279 * presence of an empty subdirectory does not block the creation of a 280 * similarly-named reference. (The fact that reference names with the 281 * same leading components can conflict *with each other* is a 282 * separate issue that is regulated by verify_refname_available().) 283 * 284 * Please note that the name field contains the fully-qualified 285 * reference (or subdirectory) name. Space could be saved by only 286 * storing the relative names. But that would require the full names 287 * to be generated on the fly when iterating in do_for_each_ref(), and 288 * would break callback functions, who have always been able to assume 289 * that the name strings that they are passed will not be freed during 290 * the iteration. 291 */ 292struct ref_entry { 293unsigned char flag;/* ISSYMREF? ISPACKED? */ 294union{ 295struct ref_value value;/* if not (flags&REF_DIR) */ 296struct ref_dir subdir;/* if (flags&REF_DIR) */ 297} u; 298/* 299 * The full name of the reference (e.g., "refs/heads/master") 300 * or the full name of the directory with a trailing slash 301 * (e.g., "refs/heads/"): 302 */ 303char name[FLEX_ARRAY]; 304}; 305 306static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 307 308static struct ref_dir *get_ref_dir(struct ref_entry *entry) 309{ 310struct ref_dir *dir; 311assert(entry->flag & REF_DIR); 312 dir = &entry->u.subdir; 313if(entry->flag & REF_INCOMPLETE) { 314read_loose_refs(entry->name, dir); 315 entry->flag &= ~REF_INCOMPLETE; 316} 317return dir; 318} 319 320/* 321 * Check if a refname is safe. 322 * For refs that start with "refs/" we consider it safe as long they do 323 * not try to resolve to outside of refs/. 324 * 325 * For all other refs we only consider them safe iff they only contain 326 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 327 * "config"). 328 */ 329static intrefname_is_safe(const char*refname) 330{ 331if(starts_with(refname,"refs/")) { 332char*buf; 333int result; 334 335 buf =xmalloc(strlen(refname) +1); 336/* 337 * Does the refname try to escape refs/? 338 * For example: refs/foo/../bar is safe but refs/foo/../../bar 339 * is not. 340 */ 341 result = !normalize_path_copy(buf, refname +strlen("refs/")); 342free(buf); 343return result; 344} 345while(*refname) { 346if(!isupper(*refname) && *refname !='_') 347return0; 348 refname++; 349} 350return1; 351} 352 353static struct ref_entry *create_ref_entry(const char*refname, 354const unsigned char*sha1,int flag, 355int check_name) 356{ 357int len; 358struct ref_entry *ref; 359 360if(check_name && 361check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 362die("Reference has invalid format: '%s'", refname); 363 len =strlen(refname) +1; 364 ref =xmalloc(sizeof(struct ref_entry) + len); 365hashcpy(ref->u.value.oid.hash, sha1); 366oidclr(&ref->u.value.peeled); 367memcpy(ref->name, refname, len); 368 ref->flag = flag; 369return ref; 370} 371 372static voidclear_ref_dir(struct ref_dir *dir); 373 374static voidfree_ref_entry(struct ref_entry *entry) 375{ 376if(entry->flag & REF_DIR) { 377/* 378 * Do not use get_ref_dir() here, as that might 379 * trigger the reading of loose refs. 380 */ 381clear_ref_dir(&entry->u.subdir); 382} 383free(entry); 384} 385 386/* 387 * Add a ref_entry to the end of dir (unsorted). Entry is always 388 * stored directly in dir; no recursion into subdirectories is 389 * done. 390 */ 391static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 392{ 393ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 394 dir->entries[dir->nr++] = entry; 395/* optimize for the case that entries are added in order */ 396if(dir->nr ==1|| 397(dir->nr == dir->sorted +1&& 398strcmp(dir->entries[dir->nr -2]->name, 399 dir->entries[dir->nr -1]->name) <0)) 400 dir->sorted = dir->nr; 401} 402 403/* 404 * Clear and free all entries in dir, recursively. 405 */ 406static voidclear_ref_dir(struct ref_dir *dir) 407{ 408int i; 409for(i =0; i < dir->nr; i++) 410free_ref_entry(dir->entries[i]); 411free(dir->entries); 412 dir->sorted = dir->nr = dir->alloc =0; 413 dir->entries = NULL; 414} 415 416/* 417 * Create a struct ref_entry object for the specified dirname. 418 * dirname is the name of the directory with a trailing slash (e.g., 419 * "refs/heads/") or "" for the top-level directory. 420 */ 421static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 422const char*dirname,size_t len, 423int incomplete) 424{ 425struct ref_entry *direntry; 426 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 427memcpy(direntry->name, dirname, len); 428 direntry->name[len] ='\0'; 429 direntry->u.subdir.ref_cache = ref_cache; 430 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 431return direntry; 432} 433 434static intref_entry_cmp(const void*a,const void*b) 435{ 436struct ref_entry *one = *(struct ref_entry **)a; 437struct ref_entry *two = *(struct ref_entry **)b; 438returnstrcmp(one->name, two->name); 439} 440 441static voidsort_ref_dir(struct ref_dir *dir); 442 443struct string_slice { 444size_t len; 445const char*str; 446}; 447 448static intref_entry_cmp_sslice(const void*key_,const void*ent_) 449{ 450const struct string_slice *key = key_; 451const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 452int cmp =strncmp(key->str, ent->name, key->len); 453if(cmp) 454return cmp; 455return'\0'- (unsigned char)ent->name[key->len]; 456} 457 458/* 459 * Return the index of the entry with the given refname from the 460 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 461 * no such entry is found. dir must already be complete. 462 */ 463static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 464{ 465struct ref_entry **r; 466struct string_slice key; 467 468if(refname == NULL || !dir->nr) 469return-1; 470 471sort_ref_dir(dir); 472 key.len = len; 473 key.str = refname; 474 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 475 ref_entry_cmp_sslice); 476 477if(r == NULL) 478return-1; 479 480return r - dir->entries; 481} 482 483/* 484 * Search for a directory entry directly within dir (without 485 * recursing). Sort dir if necessary. subdirname must be a directory 486 * name (i.e., end in '/'). If mkdir is set, then create the 487 * directory if it is missing; otherwise, return NULL if the desired 488 * directory cannot be found. dir must already be complete. 489 */ 490static struct ref_dir *search_for_subdir(struct ref_dir *dir, 491const char*subdirname,size_t len, 492int mkdir) 493{ 494int entry_index =search_ref_dir(dir, subdirname, len); 495struct ref_entry *entry; 496if(entry_index == -1) { 497if(!mkdir) 498return NULL; 499/* 500 * Since dir is complete, the absence of a subdir 501 * means that the subdir really doesn't exist; 502 * therefore, create an empty record for it but mark 503 * the record complete. 504 */ 505 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 506add_entry_to_dir(dir, entry); 507}else{ 508 entry = dir->entries[entry_index]; 509} 510returnget_ref_dir(entry); 511} 512 513/* 514 * If refname is a reference name, find the ref_dir within the dir 515 * tree that should hold refname. If refname is a directory name 516 * (i.e., ends in '/'), then return that ref_dir itself. dir must 517 * represent the top-level directory and must already be complete. 518 * Sort ref_dirs and recurse into subdirectories as necessary. If 519 * mkdir is set, then create any missing directories; otherwise, 520 * return NULL if the desired directory cannot be found. 521 */ 522static struct ref_dir *find_containing_dir(struct ref_dir *dir, 523const char*refname,int mkdir) 524{ 525const char*slash; 526for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 527size_t dirnamelen = slash - refname +1; 528struct ref_dir *subdir; 529 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 530if(!subdir) { 531 dir = NULL; 532break; 533} 534 dir = subdir; 535} 536 537return dir; 538} 539 540/* 541 * Find the value entry with the given name in dir, sorting ref_dirs 542 * and recursing into subdirectories as necessary. If the name is not 543 * found or it corresponds to a directory entry, return NULL. 544 */ 545static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 546{ 547int entry_index; 548struct ref_entry *entry; 549 dir =find_containing_dir(dir, refname,0); 550if(!dir) 551return NULL; 552 entry_index =search_ref_dir(dir, refname,strlen(refname)); 553if(entry_index == -1) 554return NULL; 555 entry = dir->entries[entry_index]; 556return(entry->flag & REF_DIR) ? NULL : entry; 557} 558 559/* 560 * Remove the entry with the given name from dir, recursing into 561 * subdirectories as necessary. If refname is the name of a directory 562 * (i.e., ends with '/'), then remove the directory and its contents. 563 * If the removal was successful, return the number of entries 564 * remaining in the directory entry that contained the deleted entry. 565 * If the name was not found, return -1. Please note that this 566 * function only deletes the entry from the cache; it does not delete 567 * it from the filesystem or ensure that other cache entries (which 568 * might be symbolic references to the removed entry) are updated. 569 * Nor does it remove any containing dir entries that might be made 570 * empty by the removal. dir must represent the top-level directory 571 * and must already be complete. 572 */ 573static intremove_entry(struct ref_dir *dir,const char*refname) 574{ 575int refname_len =strlen(refname); 576int entry_index; 577struct ref_entry *entry; 578int is_dir = refname[refname_len -1] =='/'; 579if(is_dir) { 580/* 581 * refname represents a reference directory. Remove 582 * the trailing slash; otherwise we will get the 583 * directory *representing* refname rather than the 584 * one *containing* it. 585 */ 586char*dirname =xmemdupz(refname, refname_len -1); 587 dir =find_containing_dir(dir, dirname,0); 588free(dirname); 589}else{ 590 dir =find_containing_dir(dir, refname,0); 591} 592if(!dir) 593return-1; 594 entry_index =search_ref_dir(dir, refname, refname_len); 595if(entry_index == -1) 596return-1; 597 entry = dir->entries[entry_index]; 598 599memmove(&dir->entries[entry_index], 600&dir->entries[entry_index +1], 601(dir->nr - entry_index -1) *sizeof(*dir->entries) 602); 603 dir->nr--; 604if(dir->sorted > entry_index) 605 dir->sorted--; 606free_ref_entry(entry); 607return dir->nr; 608} 609 610/* 611 * Add a ref_entry to the ref_dir (unsorted), recursing into 612 * subdirectories as necessary. dir must represent the top-level 613 * directory. Return 0 on success. 614 */ 615static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 616{ 617 dir =find_containing_dir(dir, ref->name,1); 618if(!dir) 619return-1; 620add_entry_to_dir(dir, ref); 621return0; 622} 623 624/* 625 * Emit a warning and return true iff ref1 and ref2 have the same name 626 * and the same sha1. Die if they have the same name but different 627 * sha1s. 628 */ 629static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 630{ 631if(strcmp(ref1->name, ref2->name)) 632return0; 633 634/* Duplicate name; make sure that they don't conflict: */ 635 636if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 637/* This is impossible by construction */ 638die("Reference directory conflict:%s", ref1->name); 639 640if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 641die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 642 643warning("Duplicated ref:%s", ref1->name); 644return1; 645} 646 647/* 648 * Sort the entries in dir non-recursively (if they are not already 649 * sorted) and remove any duplicate entries. 650 */ 651static voidsort_ref_dir(struct ref_dir *dir) 652{ 653int i, j; 654struct ref_entry *last = NULL; 655 656/* 657 * This check also prevents passing a zero-length array to qsort(), 658 * which is a problem on some platforms. 659 */ 660if(dir->sorted == dir->nr) 661return; 662 663qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 664 665/* Remove any duplicates: */ 666for(i =0, j =0; j < dir->nr; j++) { 667struct ref_entry *entry = dir->entries[j]; 668if(last &&is_dup_ref(last, entry)) 669free_ref_entry(entry); 670else 671 last = dir->entries[i++] = entry; 672} 673 dir->sorted = dir->nr = i; 674} 675 676/* Include broken references in a do_for_each_ref*() iteration: */ 677#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 678 679/* 680 * Return true iff the reference described by entry can be resolved to 681 * an object in the database. Emit a warning if the referred-to 682 * object does not exist. 683 */ 684static intref_resolves_to_object(struct ref_entry *entry) 685{ 686if(entry->flag & REF_ISBROKEN) 687return0; 688if(!has_sha1_file(entry->u.value.oid.hash)) { 689error("%sdoes not point to a valid object!", entry->name); 690return0; 691} 692return1; 693} 694 695/* 696 * current_ref is a performance hack: when iterating over references 697 * using the for_each_ref*() functions, current_ref is set to the 698 * current reference's entry before calling the callback function. If 699 * the callback function calls peel_ref(), then peel_ref() first 700 * checks whether the reference to be peeled is the current reference 701 * (it usually is) and if so, returns that reference's peeled version 702 * if it is available. This avoids a refname lookup in a common case. 703 */ 704static struct ref_entry *current_ref; 705 706typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 707 708struct ref_entry_cb { 709const char*base; 710int trim; 711int flags; 712 each_ref_fn *fn; 713void*cb_data; 714}; 715 716/* 717 * Handle one reference in a do_for_each_ref*()-style iteration, 718 * calling an each_ref_fn for each entry. 719 */ 720static intdo_one_ref(struct ref_entry *entry,void*cb_data) 721{ 722struct ref_entry_cb *data = cb_data; 723struct ref_entry *old_current_ref; 724int retval; 725 726if(!starts_with(entry->name, data->base)) 727return0; 728 729if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 730!ref_resolves_to_object(entry)) 731return0; 732 733/* Store the old value, in case this is a recursive call: */ 734 old_current_ref = current_ref; 735 current_ref = entry; 736 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 737 entry->flag, data->cb_data); 738 current_ref = old_current_ref; 739return retval; 740} 741 742/* 743 * Call fn for each reference in dir that has index in the range 744 * offset <= index < dir->nr. Recurse into subdirectories that are in 745 * that index range, sorting them before iterating. This function 746 * does not sort dir itself; it should be sorted beforehand. fn is 747 * called for all references, including broken ones. 748 */ 749static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 750 each_ref_entry_fn fn,void*cb_data) 751{ 752int i; 753assert(dir->sorted == dir->nr); 754for(i = offset; i < dir->nr; i++) { 755struct ref_entry *entry = dir->entries[i]; 756int retval; 757if(entry->flag & REF_DIR) { 758struct ref_dir *subdir =get_ref_dir(entry); 759sort_ref_dir(subdir); 760 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 761}else{ 762 retval =fn(entry, cb_data); 763} 764if(retval) 765return retval; 766} 767return0; 768} 769 770/* 771 * Call fn for each reference in the union of dir1 and dir2, in order 772 * by refname. Recurse into subdirectories. If a value entry appears 773 * in both dir1 and dir2, then only process the version that is in 774 * dir2. The input dirs must already be sorted, but subdirs will be 775 * sorted as needed. fn is called for all references, including 776 * broken ones. 777 */ 778static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 779struct ref_dir *dir2, 780 each_ref_entry_fn fn,void*cb_data) 781{ 782int retval; 783int i1 =0, i2 =0; 784 785assert(dir1->sorted == dir1->nr); 786assert(dir2->sorted == dir2->nr); 787while(1) { 788struct ref_entry *e1, *e2; 789int cmp; 790if(i1 == dir1->nr) { 791returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 792} 793if(i2 == dir2->nr) { 794returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 795} 796 e1 = dir1->entries[i1]; 797 e2 = dir2->entries[i2]; 798 cmp =strcmp(e1->name, e2->name); 799if(cmp ==0) { 800if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 801/* Both are directories; descend them in parallel. */ 802struct ref_dir *subdir1 =get_ref_dir(e1); 803struct ref_dir *subdir2 =get_ref_dir(e2); 804sort_ref_dir(subdir1); 805sort_ref_dir(subdir2); 806 retval =do_for_each_entry_in_dirs( 807 subdir1, subdir2, fn, cb_data); 808 i1++; 809 i2++; 810}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 811/* Both are references; ignore the one from dir1. */ 812 retval =fn(e2, cb_data); 813 i1++; 814 i2++; 815}else{ 816die("conflict between reference and directory:%s", 817 e1->name); 818} 819}else{ 820struct ref_entry *e; 821if(cmp <0) { 822 e = e1; 823 i1++; 824}else{ 825 e = e2; 826 i2++; 827} 828if(e->flag & REF_DIR) { 829struct ref_dir *subdir =get_ref_dir(e); 830sort_ref_dir(subdir); 831 retval =do_for_each_entry_in_dir( 832 subdir,0, fn, cb_data); 833}else{ 834 retval =fn(e, cb_data); 835} 836} 837if(retval) 838return retval; 839} 840} 841 842/* 843 * Load all of the refs from the dir into our in-memory cache. The hard work 844 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 845 * through all of the sub-directories. We do not even need to care about 846 * sorting, as traversal order does not matter to us. 847 */ 848static voidprime_ref_dir(struct ref_dir *dir) 849{ 850int i; 851for(i =0; i < dir->nr; i++) { 852struct ref_entry *entry = dir->entries[i]; 853if(entry->flag & REF_DIR) 854prime_ref_dir(get_ref_dir(entry)); 855} 856} 857 858struct nonmatching_ref_data { 859const struct string_list *skip; 860const char*conflicting_refname; 861}; 862 863static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 864{ 865struct nonmatching_ref_data *data = vdata; 866 867if(data->skip &&string_list_has_string(data->skip, entry->name)) 868return0; 869 870 data->conflicting_refname = entry->name; 871return1; 872} 873 874/* 875 * Return 0 if a reference named refname could be created without 876 * conflicting with the name of an existing reference in dir. 877 * Otherwise, return a negative value and write an explanation to err. 878 * If extras is non-NULL, it is a list of additional refnames with 879 * which refname is not allowed to conflict. If skip is non-NULL, 880 * ignore potential conflicts with refs in skip (e.g., because they 881 * are scheduled for deletion in the same operation). Behavior is 882 * undefined if the same name is listed in both extras and skip. 883 * 884 * Two reference names conflict if one of them exactly matches the 885 * leading components of the other; e.g., "refs/foo/bar" conflicts 886 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 887 * "refs/foo/bar" or "refs/foo/barbados". 888 * 889 * extras and skip must be sorted. 890 */ 891static intverify_refname_available(const char*refname, 892const struct string_list *extras, 893const struct string_list *skip, 894struct ref_dir *dir, 895struct strbuf *err) 896{ 897const char*slash; 898int pos; 899struct strbuf dirname = STRBUF_INIT; 900int ret = -1; 901 902/* 903 * For the sake of comments in this function, suppose that 904 * refname is "refs/foo/bar". 905 */ 906 907assert(err); 908 909strbuf_grow(&dirname,strlen(refname) +1); 910for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 911/* Expand dirname to the new prefix, not including the trailing slash: */ 912strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 913 914/* 915 * We are still at a leading dir of the refname (e.g., 916 * "refs/foo"; if there is a reference with that name, 917 * it is a conflict, *unless* it is in skip. 918 */ 919if(dir) { 920 pos =search_ref_dir(dir, dirname.buf, dirname.len); 921if(pos >=0&& 922(!skip || !string_list_has_string(skip, dirname.buf))) { 923/* 924 * We found a reference whose name is 925 * a proper prefix of refname; e.g., 926 * "refs/foo", and is not in skip. 927 */ 928strbuf_addf(err,"'%s' exists; cannot create '%s'", 929 dirname.buf, refname); 930goto cleanup; 931} 932} 933 934if(extras &&string_list_has_string(extras, dirname.buf) && 935(!skip || !string_list_has_string(skip, dirname.buf))) { 936strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 937 refname, dirname.buf); 938goto cleanup; 939} 940 941/* 942 * Otherwise, we can try to continue our search with 943 * the next component. So try to look up the 944 * directory, e.g., "refs/foo/". If we come up empty, 945 * we know there is nothing under this whole prefix, 946 * but even in that case we still have to continue the 947 * search for conflicts with extras. 948 */ 949strbuf_addch(&dirname,'/'); 950if(dir) { 951 pos =search_ref_dir(dir, dirname.buf, dirname.len); 952if(pos <0) { 953/* 954 * There was no directory "refs/foo/", 955 * so there is nothing under this 956 * whole prefix. So there is no need 957 * to continue looking for conflicting 958 * references. But we need to continue 959 * looking for conflicting extras. 960 */ 961 dir = NULL; 962}else{ 963 dir =get_ref_dir(dir->entries[pos]); 964} 965} 966} 967 968/* 969 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 970 * There is no point in searching for a reference with that 971 * name, because a refname isn't considered to conflict with 972 * itself. But we still need to check for references whose 973 * names are in the "refs/foo/bar/" namespace, because they 974 * *do* conflict. 975 */ 976strbuf_addstr(&dirname, refname + dirname.len); 977strbuf_addch(&dirname,'/'); 978 979if(dir) { 980 pos =search_ref_dir(dir, dirname.buf, dirname.len); 981 982if(pos >=0) { 983/* 984 * We found a directory named "$refname/" 985 * (e.g., "refs/foo/bar/"). It is a problem 986 * iff it contains any ref that is not in 987 * "skip". 988 */ 989struct nonmatching_ref_data data; 990 991 data.skip = skip; 992 data.conflicting_refname = NULL; 993 dir =get_ref_dir(dir->entries[pos]); 994sort_ref_dir(dir); 995if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 996strbuf_addf(err,"'%s' exists; cannot create '%s'", 997 data.conflicting_refname, refname); 998goto cleanup; 999}1000}1001}10021003if(extras) {1004/*1005 * Check for entries in extras that start with1006 * "$refname/". We do that by looking for the place1007 * where "$refname/" would be inserted in extras. If1008 * there is an entry at that position that starts with1009 * "$refname/" and is not in skip, then we have a1010 * conflict.1011 */1012for(pos =string_list_find_insert_index(extras, dirname.buf,0);1013 pos < extras->nr; pos++) {1014const char*extra_refname = extras->items[pos].string;10151016if(!starts_with(extra_refname, dirname.buf))1017break;10181019if(!skip || !string_list_has_string(skip, extra_refname)) {1020strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1021 refname, extra_refname);1022goto cleanup;1023}1024}1025}10261027/* No conflicts were found */1028 ret =0;10291030cleanup:1031strbuf_release(&dirname);1032return ret;1033}10341035struct packed_ref_cache {1036struct ref_entry *root;10371038/*1039 * Count of references to the data structure in this instance,1040 * including the pointer from ref_cache::packed if any. The1041 * data will not be freed as long as the reference count is1042 * nonzero.1043 */1044unsigned int referrers;10451046/*1047 * Iff the packed-refs file associated with this instance is1048 * currently locked for writing, this points at the associated1049 * lock (which is owned by somebody else). The referrer count1050 * is also incremented when the file is locked and decremented1051 * when it is unlocked.1052 */1053struct lock_file *lock;10541055/* The metadata from when this packed-refs cache was read */1056struct stat_validity validity;1057};10581059/*1060 * Future: need to be in "struct repository"1061 * when doing a full libification.1062 */1063static struct ref_cache {1064struct ref_cache *next;1065struct ref_entry *loose;1066struct packed_ref_cache *packed;1067/*1068 * The submodule name, or "" for the main repo. We allocate1069 * length 1 rather than FLEX_ARRAY so that the main ref_cache1070 * is initialized correctly.1071 */1072char name[1];1073} ref_cache, *submodule_ref_caches;10741075/* Lock used for the main packed-refs file: */1076static struct lock_file packlock;10771078/*1079 * Increment the reference count of *packed_refs.1080 */1081static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1082{1083 packed_refs->referrers++;1084}10851086/*1087 * Decrease the reference count of *packed_refs. If it goes to zero,1088 * free *packed_refs and return true; otherwise return false.1089 */1090static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1091{1092if(!--packed_refs->referrers) {1093free_ref_entry(packed_refs->root);1094stat_validity_clear(&packed_refs->validity);1095free(packed_refs);1096return1;1097}else{1098return0;1099}1100}11011102static voidclear_packed_ref_cache(struct ref_cache *refs)1103{1104if(refs->packed) {1105struct packed_ref_cache *packed_refs = refs->packed;11061107if(packed_refs->lock)1108die("internal error: packed-ref cache cleared while locked");1109 refs->packed = NULL;1110release_packed_ref_cache(packed_refs);1111}1112}11131114static voidclear_loose_ref_cache(struct ref_cache *refs)1115{1116if(refs->loose) {1117free_ref_entry(refs->loose);1118 refs->loose = NULL;1119}1120}11211122static struct ref_cache *create_ref_cache(const char*submodule)1123{1124int len;1125struct ref_cache *refs;1126if(!submodule)1127 submodule ="";1128 len =strlen(submodule) +1;1129 refs =xcalloc(1,sizeof(struct ref_cache) + len);1130memcpy(refs->name, submodule, len);1131return refs;1132}11331134/*1135 * Return a pointer to a ref_cache for the specified submodule. For1136 * the main repository, use submodule==NULL. The returned structure1137 * will be allocated and initialized but not necessarily populated; it1138 * should not be freed.1139 */1140static struct ref_cache *get_ref_cache(const char*submodule)1141{1142struct ref_cache *refs;11431144if(!submodule || !*submodule)1145return&ref_cache;11461147for(refs = submodule_ref_caches; refs; refs = refs->next)1148if(!strcmp(submodule, refs->name))1149return refs;11501151 refs =create_ref_cache(submodule);1152 refs->next = submodule_ref_caches;1153 submodule_ref_caches = refs;1154return refs;1155}11561157/* The length of a peeled reference line in packed-refs, including EOL: */1158#define PEELED_LINE_LENGTH 4211591160/*1161 * The packed-refs header line that we write out. Perhaps other1162 * traits will be added later. The trailing space is required.1163 */1164static const char PACKED_REFS_HEADER[] =1165"# pack-refs with: peeled fully-peeled\n";11661167/*1168 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1169 * Return a pointer to the refname within the line (null-terminated),1170 * or NULL if there was a problem.1171 */1172static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1173{1174const char*ref;11751176/*1177 * 42: the answer to everything.1178 *1179 * In this case, it happens to be the answer to1180 * 40 (length of sha1 hex representation)1181 * +1 (space in between hex and name)1182 * +1 (newline at the end of the line)1183 */1184if(line->len <=42)1185return NULL;11861187if(get_sha1_hex(line->buf, sha1) <0)1188return NULL;1189if(!isspace(line->buf[40]))1190return NULL;11911192 ref = line->buf +41;1193if(isspace(*ref))1194return NULL;11951196if(line->buf[line->len -1] !='\n')1197return NULL;1198 line->buf[--line->len] =0;11991200return ref;1201}12021203/*1204 * Read f, which is a packed-refs file, into dir.1205 *1206 * A comment line of the form "# pack-refs with: " may contain zero or1207 * more traits. We interpret the traits as follows:1208 *1209 * No traits:1210 *1211 * Probably no references are peeled. But if the file contains a1212 * peeled value for a reference, we will use it.1213 *1214 * peeled:1215 *1216 * References under "refs/tags/", if they *can* be peeled, *are*1217 * peeled in this file. References outside of "refs/tags/" are1218 * probably not peeled even if they could have been, but if we find1219 * a peeled value for such a reference we will use it.1220 *1221 * fully-peeled:1222 *1223 * All references in the file that can be peeled are peeled.1224 * Inversely (and this is more important), any references in the1225 * file for which no peeled value is recorded is not peelable. This1226 * trait should typically be written alongside "peeled" for1227 * compatibility with older clients, but we do not require it1228 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1229 */1230static voidread_packed_refs(FILE*f,struct ref_dir *dir)1231{1232struct ref_entry *last = NULL;1233struct strbuf line = STRBUF_INIT;1234enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12351236while(strbuf_getwholeline(&line, f,'\n') != EOF) {1237unsigned char sha1[20];1238const char*refname;1239const char*traits;12401241if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1242if(strstr(traits," fully-peeled "))1243 peeled = PEELED_FULLY;1244else if(strstr(traits," peeled "))1245 peeled = PEELED_TAGS;1246/* perhaps other traits later as well */1247continue;1248}12491250 refname =parse_ref_line(&line, sha1);1251if(refname) {1252int flag = REF_ISPACKED;12531254if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1255if(!refname_is_safe(refname))1256die("packed refname is dangerous:%s", refname);1257hashclr(sha1);1258 flag |= REF_BAD_NAME | REF_ISBROKEN;1259}1260 last =create_ref_entry(refname, sha1, flag,0);1261if(peeled == PEELED_FULLY ||1262(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1263 last->flag |= REF_KNOWS_PEELED;1264add_ref(dir, last);1265continue;1266}1267if(last &&1268 line.buf[0] =='^'&&1269 line.len == PEELED_LINE_LENGTH &&1270 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1271!get_sha1_hex(line.buf +1, sha1)) {1272hashcpy(last->u.value.peeled.hash, sha1);1273/*1274 * Regardless of what the file header said,1275 * we definitely know the value of *this*1276 * reference:1277 */1278 last->flag |= REF_KNOWS_PEELED;1279}1280}12811282strbuf_release(&line);1283}12841285/*1286 * Get the packed_ref_cache for the specified ref_cache, creating it1287 * if necessary.1288 */1289static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1290{1291char*packed_refs_file;12921293if(*refs->name)1294 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1295else1296 packed_refs_file =git_pathdup("packed-refs");12971298if(refs->packed &&1299!stat_validity_check(&refs->packed->validity, packed_refs_file))1300clear_packed_ref_cache(refs);13011302if(!refs->packed) {1303FILE*f;13041305 refs->packed =xcalloc(1,sizeof(*refs->packed));1306acquire_packed_ref_cache(refs->packed);1307 refs->packed->root =create_dir_entry(refs,"",0,0);1308 f =fopen(packed_refs_file,"r");1309if(f) {1310stat_validity_update(&refs->packed->validity,fileno(f));1311read_packed_refs(f,get_ref_dir(refs->packed->root));1312fclose(f);1313}1314}1315free(packed_refs_file);1316return refs->packed;1317}13181319static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1320{1321returnget_ref_dir(packed_ref_cache->root);1322}13231324static struct ref_dir *get_packed_refs(struct ref_cache *refs)1325{1326returnget_packed_ref_dir(get_packed_ref_cache(refs));1327}13281329/*1330 * Add a reference to the in-memory packed reference cache. This may1331 * only be called while the packed-refs file is locked (see1332 * lock_packed_refs()). To actually write the packed-refs file, call1333 * commit_packed_refs().1334 */1335static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1336{1337struct packed_ref_cache *packed_ref_cache =1338get_packed_ref_cache(&ref_cache);13391340if(!packed_ref_cache->lock)1341die("internal error: packed refs not locked");1342add_ref(get_packed_ref_dir(packed_ref_cache),1343create_ref_entry(refname, sha1, REF_ISPACKED,1));1344}13451346/*1347 * Read the loose references from the namespace dirname into dir1348 * (without recursing). dirname must end with '/'. dir must be the1349 * directory entry corresponding to dirname.1350 */1351static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1352{1353struct ref_cache *refs = dir->ref_cache;1354DIR*d;1355const char*path;1356struct dirent *de;1357int dirnamelen =strlen(dirname);1358struct strbuf refname;13591360if(*refs->name)1361 path =git_path_submodule(refs->name,"%s", dirname);1362else1363 path =git_path("%s", dirname);13641365 d =opendir(path);1366if(!d)1367return;13681369strbuf_init(&refname, dirnamelen +257);1370strbuf_add(&refname, dirname, dirnamelen);13711372while((de =readdir(d)) != NULL) {1373unsigned char sha1[20];1374struct stat st;1375int flag;1376const char*refdir;13771378if(de->d_name[0] =='.')1379continue;1380if(ends_with(de->d_name,".lock"))1381continue;1382strbuf_addstr(&refname, de->d_name);1383 refdir = *refs->name1384?git_path_submodule(refs->name,"%s", refname.buf)1385:git_path("%s", refname.buf);1386if(stat(refdir, &st) <0) {1387;/* silently ignore */1388}else if(S_ISDIR(st.st_mode)) {1389strbuf_addch(&refname,'/');1390add_entry_to_dir(dir,1391create_dir_entry(refs, refname.buf,1392 refname.len,1));1393}else{1394int read_ok;13951396if(*refs->name) {1397hashclr(sha1);1398 flag =0;1399 read_ok = !resolve_gitlink_ref(refs->name,1400 refname.buf, sha1);1401}else{1402 read_ok = !read_ref_full(refname.buf,1403 RESOLVE_REF_READING,1404 sha1, &flag);1405}14061407if(!read_ok) {1408hashclr(sha1);1409 flag |= REF_ISBROKEN;1410}else if(is_null_sha1(sha1)) {1411/*1412 * It is so astronomically unlikely1413 * that NULL_SHA1 is the SHA-1 of an1414 * actual object that we consider its1415 * appearance in a loose reference1416 * file to be repo corruption1417 * (probably due to a software bug).1418 */1419 flag |= REF_ISBROKEN;1420}14211422if(check_refname_format(refname.buf,1423 REFNAME_ALLOW_ONELEVEL)) {1424if(!refname_is_safe(refname.buf))1425die("loose refname is dangerous:%s", refname.buf);1426hashclr(sha1);1427 flag |= REF_BAD_NAME | REF_ISBROKEN;1428}1429add_entry_to_dir(dir,1430create_ref_entry(refname.buf, sha1, flag,0));1431}1432strbuf_setlen(&refname, dirnamelen);1433}1434strbuf_release(&refname);1435closedir(d);1436}14371438static struct ref_dir *get_loose_refs(struct ref_cache *refs)1439{1440if(!refs->loose) {1441/*1442 * Mark the top-level directory complete because we1443 * are about to read the only subdirectory that can1444 * hold references:1445 */1446 refs->loose =create_dir_entry(refs,"",0,0);1447/*1448 * Create an incomplete entry for "refs/":1449 */1450add_entry_to_dir(get_ref_dir(refs->loose),1451create_dir_entry(refs,"refs/",5,1));1452}1453returnget_ref_dir(refs->loose);1454}14551456/* We allow "recursive" symbolic refs. Only within reason, though */1457#define MAXDEPTH 51458#define MAXREFLEN (1024)14591460/*1461 * Called by resolve_gitlink_ref_recursive() after it failed to read1462 * from the loose refs in ref_cache refs. Find <refname> in the1463 * packed-refs file for the submodule.1464 */1465static intresolve_gitlink_packed_ref(struct ref_cache *refs,1466const char*refname,unsigned char*sha1)1467{1468struct ref_entry *ref;1469struct ref_dir *dir =get_packed_refs(refs);14701471 ref =find_ref(dir, refname);1472if(ref == NULL)1473return-1;14741475hashcpy(sha1, ref->u.value.oid.hash);1476return0;1477}14781479static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1480const char*refname,unsigned char*sha1,1481int recursion)1482{1483int fd, len;1484char buffer[128], *p;1485char*path;14861487if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1488return-1;1489 path = *refs->name1490?git_pathdup_submodule(refs->name,"%s", refname)1491:git_pathdup("%s", refname);1492 fd =open(path, O_RDONLY);1493free(path);1494if(fd <0)1495returnresolve_gitlink_packed_ref(refs, refname, sha1);14961497 len =read(fd, buffer,sizeof(buffer)-1);1498close(fd);1499if(len <0)1500return-1;1501while(len &&isspace(buffer[len-1]))1502 len--;1503 buffer[len] =0;15041505/* Was it a detached head or an old-fashioned symlink? */1506if(!get_sha1_hex(buffer, sha1))1507return0;15081509/* Symref? */1510if(strncmp(buffer,"ref:",4))1511return-1;1512 p = buffer +4;1513while(isspace(*p))1514 p++;15151516returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1517}15181519intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1520{1521int len =strlen(path), retval;1522char*submodule;1523struct ref_cache *refs;15241525while(len && path[len-1] =='/')1526 len--;1527if(!len)1528return-1;1529 submodule =xstrndup(path, len);1530 refs =get_ref_cache(submodule);1531free(submodule);15321533 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1534return retval;1535}15361537/*1538 * Return the ref_entry for the given refname from the packed1539 * references. If it does not exist, return NULL.1540 */1541static struct ref_entry *get_packed_ref(const char*refname)1542{1543returnfind_ref(get_packed_refs(&ref_cache), refname);1544}15451546/*1547 * A loose ref file doesn't exist; check for a packed ref. The1548 * options are forwarded from resolve_safe_unsafe().1549 */1550static intresolve_missing_loose_ref(const char*refname,1551int resolve_flags,1552unsigned char*sha1,1553int*flags)1554{1555struct ref_entry *entry;15561557/*1558 * The loose reference file does not exist; check for a packed1559 * reference.1560 */1561 entry =get_packed_ref(refname);1562if(entry) {1563hashcpy(sha1, entry->u.value.oid.hash);1564if(flags)1565*flags |= REF_ISPACKED;1566return0;1567}1568/* The reference is not a packed reference, either. */1569if(resolve_flags & RESOLVE_REF_READING) {1570 errno = ENOENT;1571return-1;1572}else{1573hashclr(sha1);1574return0;1575}1576}15771578/* This function needs to return a meaningful errno on failure */1579static const char*resolve_ref_unsafe_1(const char*refname,1580int resolve_flags,1581unsigned char*sha1,1582int*flags,1583struct strbuf *sb_path)1584{1585int depth = MAXDEPTH;1586 ssize_t len;1587char buffer[256];1588static char refname_buffer[256];1589int bad_name =0;15901591if(flags)1592*flags =0;15931594if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1595if(flags)1596*flags |= REF_BAD_NAME;15971598if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1599!refname_is_safe(refname)) {1600 errno = EINVAL;1601return NULL;1602}1603/*1604 * dwim_ref() uses REF_ISBROKEN to distinguish between1605 * missing refs and refs that were present but invalid,1606 * to complain about the latter to stderr.1607 *1608 * We don't know whether the ref exists, so don't set1609 * REF_ISBROKEN yet.1610 */1611 bad_name =1;1612}1613for(;;) {1614const char*path;1615struct stat st;1616char*buf;1617int fd;16181619if(--depth <0) {1620 errno = ELOOP;1621return NULL;1622}16231624strbuf_reset(sb_path);1625strbuf_git_path(sb_path,"%s", refname);1626 path = sb_path->buf;16271628/*1629 * We might have to loop back here to avoid a race1630 * condition: first we lstat() the file, then we try1631 * to read it as a link or as a file. But if somebody1632 * changes the type of the file (file <-> directory1633 * <-> symlink) between the lstat() and reading, then1634 * we don't want to report that as an error but rather1635 * try again starting with the lstat().1636 */1637 stat_ref:1638if(lstat(path, &st) <0) {1639if(errno != ENOENT)1640return NULL;1641if(resolve_missing_loose_ref(refname, resolve_flags,1642 sha1, flags))1643return NULL;1644if(bad_name) {1645hashclr(sha1);1646if(flags)1647*flags |= REF_ISBROKEN;1648}1649return refname;1650}16511652/* Follow "normalized" - ie "refs/.." symlinks by hand */1653if(S_ISLNK(st.st_mode)) {1654 len =readlink(path, buffer,sizeof(buffer)-1);1655if(len <0) {1656if(errno == ENOENT || errno == EINVAL)1657/* inconsistent with lstat; retry */1658goto stat_ref;1659else1660return NULL;1661}1662 buffer[len] =0;1663if(starts_with(buffer,"refs/") &&1664!check_refname_format(buffer,0)) {1665strcpy(refname_buffer, buffer);1666 refname = refname_buffer;1667if(flags)1668*flags |= REF_ISSYMREF;1669if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1670hashclr(sha1);1671return refname;1672}1673continue;1674}1675}16761677/* Is it a directory? */1678if(S_ISDIR(st.st_mode)) {1679 errno = EISDIR;1680return NULL;1681}16821683/*1684 * Anything else, just open it and try to use it as1685 * a ref1686 */1687 fd =open(path, O_RDONLY);1688if(fd <0) {1689if(errno == ENOENT)1690/* inconsistent with lstat; retry */1691goto stat_ref;1692else1693return NULL;1694}1695 len =read_in_full(fd, buffer,sizeof(buffer)-1);1696if(len <0) {1697int save_errno = errno;1698close(fd);1699 errno = save_errno;1700return NULL;1701}1702close(fd);1703while(len &&isspace(buffer[len-1]))1704 len--;1705 buffer[len] ='\0';17061707/*1708 * Is it a symbolic ref?1709 */1710if(!starts_with(buffer,"ref:")) {1711/*1712 * Please note that FETCH_HEAD has a second1713 * line containing other data.1714 */1715if(get_sha1_hex(buffer, sha1) ||1716(buffer[40] !='\0'&& !isspace(buffer[40]))) {1717if(flags)1718*flags |= REF_ISBROKEN;1719 errno = EINVAL;1720return NULL;1721}1722if(bad_name) {1723hashclr(sha1);1724if(flags)1725*flags |= REF_ISBROKEN;1726}1727return refname;1728}1729if(flags)1730*flags |= REF_ISSYMREF;1731 buf = buffer +4;1732while(isspace(*buf))1733 buf++;1734 refname =strcpy(refname_buffer, buf);1735if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1736hashclr(sha1);1737return refname;1738}1739if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1740if(flags)1741*flags |= REF_ISBROKEN;17421743if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1744!refname_is_safe(buf)) {1745 errno = EINVAL;1746return NULL;1747}1748 bad_name =1;1749}1750}1751}17521753const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1754unsigned char*sha1,int*flags)1755{1756struct strbuf sb_path = STRBUF_INIT;1757const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1758 sha1, flags, &sb_path);1759strbuf_release(&sb_path);1760return ret;1761}17621763char*resolve_refdup(const char*refname,int resolve_flags,1764unsigned char*sha1,int*flags)1765{1766returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1767 sha1, flags));1768}17691770/* The argument to filter_refs */1771struct ref_filter {1772const char*pattern;1773 each_ref_fn *fn;1774void*cb_data;1775};17761777intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1778{1779if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1780return0;1781return-1;1782}17831784intread_ref(const char*refname,unsigned char*sha1)1785{1786returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1787}17881789intref_exists(const char*refname)1790{1791unsigned char sha1[20];1792return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1793}17941795static intfilter_refs(const char*refname,const struct object_id *oid,1796int flags,void*data)1797{1798struct ref_filter *filter = (struct ref_filter *)data;17991800if(wildmatch(filter->pattern, refname,0, NULL))1801return0;1802return filter->fn(refname, oid, flags, filter->cb_data);1803}18041805enum peel_status {1806/* object was peeled successfully: */1807 PEEL_PEELED =0,18081809/*1810 * object cannot be peeled because the named object (or an1811 * object referred to by a tag in the peel chain), does not1812 * exist.1813 */1814 PEEL_INVALID = -1,18151816/* object cannot be peeled because it is not a tag: */1817 PEEL_NON_TAG = -2,18181819/* ref_entry contains no peeled value because it is a symref: */1820 PEEL_IS_SYMREF = -3,18211822/*1823 * ref_entry cannot be peeled because it is broken (i.e., the1824 * symbolic reference cannot even be resolved to an object1825 * name):1826 */1827 PEEL_BROKEN = -41828};18291830/*1831 * Peel the named object; i.e., if the object is a tag, resolve the1832 * tag recursively until a non-tag is found. If successful, store the1833 * result to sha1 and return PEEL_PEELED. If the object is not a tag1834 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1835 * and leave sha1 unchanged.1836 */1837static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1838{1839struct object *o =lookup_unknown_object(name);18401841if(o->type == OBJ_NONE) {1842int type =sha1_object_info(name, NULL);1843if(type <0|| !object_as_type(o, type,0))1844return PEEL_INVALID;1845}18461847if(o->type != OBJ_TAG)1848return PEEL_NON_TAG;18491850 o =deref_tag_noverify(o);1851if(!o)1852return PEEL_INVALID;18531854hashcpy(sha1, o->sha1);1855return PEEL_PEELED;1856}18571858/*1859 * Peel the entry (if possible) and return its new peel_status. If1860 * repeel is true, re-peel the entry even if there is an old peeled1861 * value that is already stored in it.1862 *1863 * It is OK to call this function with a packed reference entry that1864 * might be stale and might even refer to an object that has since1865 * been garbage-collected. In such a case, if the entry has1866 * REF_KNOWS_PEELED then leave the status unchanged and return1867 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1868 */1869static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1870{1871enum peel_status status;18721873if(entry->flag & REF_KNOWS_PEELED) {1874if(repeel) {1875 entry->flag &= ~REF_KNOWS_PEELED;1876oidclr(&entry->u.value.peeled);1877}else{1878returnis_null_oid(&entry->u.value.peeled) ?1879 PEEL_NON_TAG : PEEL_PEELED;1880}1881}1882if(entry->flag & REF_ISBROKEN)1883return PEEL_BROKEN;1884if(entry->flag & REF_ISSYMREF)1885return PEEL_IS_SYMREF;18861887 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1888if(status == PEEL_PEELED || status == PEEL_NON_TAG)1889 entry->flag |= REF_KNOWS_PEELED;1890return status;1891}18921893intpeel_ref(const char*refname,unsigned char*sha1)1894{1895int flag;1896unsigned char base[20];18971898if(current_ref && (current_ref->name == refname1899|| !strcmp(current_ref->name, refname))) {1900if(peel_entry(current_ref,0))1901return-1;1902hashcpy(sha1, current_ref->u.value.peeled.hash);1903return0;1904}19051906if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1907return-1;19081909/*1910 * If the reference is packed, read its ref_entry from the1911 * cache in the hope that we already know its peeled value.1912 * We only try this optimization on packed references because1913 * (a) forcing the filling of the loose reference cache could1914 * be expensive and (b) loose references anyway usually do not1915 * have REF_KNOWS_PEELED.1916 */1917if(flag & REF_ISPACKED) {1918struct ref_entry *r =get_packed_ref(refname);1919if(r) {1920if(peel_entry(r,0))1921return-1;1922hashcpy(sha1, r->u.value.peeled.hash);1923return0;1924}1925}19261927returnpeel_object(base, sha1);1928}19291930struct warn_if_dangling_data {1931FILE*fp;1932const char*refname;1933const struct string_list *refnames;1934const char*msg_fmt;1935};19361937static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1938int flags,void*cb_data)1939{1940struct warn_if_dangling_data *d = cb_data;1941const char*resolves_to;1942struct object_id junk;19431944if(!(flags & REF_ISSYMREF))1945return0;19461947 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1948if(!resolves_to1949|| (d->refname1950?strcmp(resolves_to, d->refname)1951: !string_list_has_string(d->refnames, resolves_to))) {1952return0;1953}19541955fprintf(d->fp, d->msg_fmt, refname);1956fputc('\n', d->fp);1957return0;1958}19591960voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1961{1962struct warn_if_dangling_data data;19631964 data.fp = fp;1965 data.refname = refname;1966 data.refnames = NULL;1967 data.msg_fmt = msg_fmt;1968for_each_rawref(warn_if_dangling_symref, &data);1969}19701971voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1972{1973struct warn_if_dangling_data data;19741975 data.fp = fp;1976 data.refname = NULL;1977 data.refnames = refnames;1978 data.msg_fmt = msg_fmt;1979for_each_rawref(warn_if_dangling_symref, &data);1980}19811982/*1983 * Call fn for each reference in the specified ref_cache, omitting1984 * references not in the containing_dir of base. fn is called for all1985 * references, including broken ones. If fn ever returns a non-zero1986 * value, stop the iteration and return that value; otherwise, return1987 * 0.1988 */1989static intdo_for_each_entry(struct ref_cache *refs,const char*base,1990 each_ref_entry_fn fn,void*cb_data)1991{1992struct packed_ref_cache *packed_ref_cache;1993struct ref_dir *loose_dir;1994struct ref_dir *packed_dir;1995int retval =0;19961997/*1998 * We must make sure that all loose refs are read before accessing the1999 * packed-refs file; this avoids a race condition in which loose refs2000 * are migrated to the packed-refs file by a simultaneous process, but2001 * our in-memory view is from before the migration. get_packed_ref_cache()2002 * takes care of making sure our view is up to date with what is on2003 * disk.2004 */2005 loose_dir =get_loose_refs(refs);2006if(base && *base) {2007 loose_dir =find_containing_dir(loose_dir, base,0);2008}2009if(loose_dir)2010prime_ref_dir(loose_dir);20112012 packed_ref_cache =get_packed_ref_cache(refs);2013acquire_packed_ref_cache(packed_ref_cache);2014 packed_dir =get_packed_ref_dir(packed_ref_cache);2015if(base && *base) {2016 packed_dir =find_containing_dir(packed_dir, base,0);2017}20182019if(packed_dir && loose_dir) {2020sort_ref_dir(packed_dir);2021sort_ref_dir(loose_dir);2022 retval =do_for_each_entry_in_dirs(2023 packed_dir, loose_dir, fn, cb_data);2024}else if(packed_dir) {2025sort_ref_dir(packed_dir);2026 retval =do_for_each_entry_in_dir(2027 packed_dir,0, fn, cb_data);2028}else if(loose_dir) {2029sort_ref_dir(loose_dir);2030 retval =do_for_each_entry_in_dir(2031 loose_dir,0, fn, cb_data);2032}20332034release_packed_ref_cache(packed_ref_cache);2035return retval;2036}20372038/*2039 * Call fn for each reference in the specified ref_cache for which the2040 * refname begins with base. If trim is non-zero, then trim that many2041 * characters off the beginning of each refname before passing the2042 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2043 * broken references in the iteration. If fn ever returns a non-zero2044 * value, stop the iteration and return that value; otherwise, return2045 * 0.2046 */2047static intdo_for_each_ref(struct ref_cache *refs,const char*base,2048 each_ref_fn fn,int trim,int flags,void*cb_data)2049{2050struct ref_entry_cb data;2051 data.base = base;2052 data.trim = trim;2053 data.flags = flags;2054 data.fn = fn;2055 data.cb_data = cb_data;20562057if(ref_paranoia <0)2058 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2059if(ref_paranoia)2060 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20612062returndo_for_each_entry(refs, base, do_one_ref, &data);2063}20642065static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2066{2067struct object_id oid;2068int flag;20692070if(submodule) {2071if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2072returnfn("HEAD", &oid,0, cb_data);20732074return0;2075}20762077if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2078returnfn("HEAD", &oid, flag, cb_data);20792080return0;2081}20822083inthead_ref(each_ref_fn fn,void*cb_data)2084{2085returndo_head_ref(NULL, fn, cb_data);2086}20872088inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2089{2090returndo_head_ref(submodule, fn, cb_data);2091}20922093intfor_each_ref(each_ref_fn fn,void*cb_data)2094{2095returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2096}20972098intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2099{2100returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2101}21022103intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2104{2105returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2106}21072108intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2109 each_ref_fn fn,void*cb_data)2110{2111returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2112}21132114intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2115{2116returnfor_each_ref_in("refs/tags/", fn, cb_data);2117}21182119intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2120{2121returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2122}21232124intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2125{2126returnfor_each_ref_in("refs/heads/", fn, cb_data);2127}21282129intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2130{2131returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2132}21332134intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2135{2136returnfor_each_ref_in("refs/remotes/", fn, cb_data);2137}21382139intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2140{2141returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2142}21432144intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2145{2146returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2147strlen(git_replace_ref_base),0, cb_data);2148}21492150inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2151{2152struct strbuf buf = STRBUF_INIT;2153int ret =0;2154struct object_id oid;2155int flag;21562157strbuf_addf(&buf,"%sHEAD",get_git_namespace());2158if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2159 ret =fn(buf.buf, &oid, flag, cb_data);2160strbuf_release(&buf);21612162return ret;2163}21642165intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2166{2167struct strbuf buf = STRBUF_INIT;2168int ret;2169strbuf_addf(&buf,"%srefs/",get_git_namespace());2170 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2171strbuf_release(&buf);2172return ret;2173}21742175intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2176const char*prefix,void*cb_data)2177{2178struct strbuf real_pattern = STRBUF_INIT;2179struct ref_filter filter;2180int ret;21812182if(!prefix && !starts_with(pattern,"refs/"))2183strbuf_addstr(&real_pattern,"refs/");2184else if(prefix)2185strbuf_addstr(&real_pattern, prefix);2186strbuf_addstr(&real_pattern, pattern);21872188if(!has_glob_specials(pattern)) {2189/* Append implied '/' '*' if not present. */2190if(real_pattern.buf[real_pattern.len -1] !='/')2191strbuf_addch(&real_pattern,'/');2192/* No need to check for '*', there is none. */2193strbuf_addch(&real_pattern,'*');2194}21952196 filter.pattern = real_pattern.buf;2197 filter.fn = fn;2198 filter.cb_data = cb_data;2199 ret =for_each_ref(filter_refs, &filter);22002201strbuf_release(&real_pattern);2202return ret;2203}22042205intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2206{2207returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2208}22092210intfor_each_rawref(each_ref_fn fn,void*cb_data)2211{2212returndo_for_each_ref(&ref_cache,"", fn,0,2213 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2214}22152216const char*prettify_refname(const char*name)2217{2218return name + (2219starts_with(name,"refs/heads/") ?11:2220starts_with(name,"refs/tags/") ?10:2221starts_with(name,"refs/remotes/") ?13:22220);2223}22242225static const char*ref_rev_parse_rules[] = {2226"%.*s",2227"refs/%.*s",2228"refs/tags/%.*s",2229"refs/heads/%.*s",2230"refs/remotes/%.*s",2231"refs/remotes/%.*s/HEAD",2232 NULL2233};22342235intrefname_match(const char*abbrev_name,const char*full_name)2236{2237const char**p;2238const int abbrev_name_len =strlen(abbrev_name);22392240for(p = ref_rev_parse_rules; *p; p++) {2241if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2242return1;2243}2244}22452246return0;2247}22482249static voidunlock_ref(struct ref_lock *lock)2250{2251/* Do not free lock->lk -- atexit() still looks at them */2252if(lock->lk)2253rollback_lock_file(lock->lk);2254free(lock->ref_name);2255free(lock->orig_ref_name);2256free(lock);2257}22582259/*2260 * Verify that the reference locked by lock has the value old_sha1.2261 * Fail if the reference doesn't exist and mustexist is set. Return 02262 * on success. On error, write an error message to err, set errno, and2263 * return a negative value.2264 */2265static intverify_lock(struct ref_lock *lock,2266const unsigned char*old_sha1,int mustexist,2267struct strbuf *err)2268{2269assert(err);22702271if(read_ref_full(lock->ref_name,2272 mustexist ? RESOLVE_REF_READING :0,2273 lock->old_oid.hash, NULL)) {2274int save_errno = errno;2275strbuf_addf(err,"can't verify ref%s", lock->ref_name);2276 errno = save_errno;2277return-1;2278}2279if(hashcmp(lock->old_oid.hash, old_sha1)) {2280strbuf_addf(err,"ref%sis at%sbut expected%s",2281 lock->ref_name,2282sha1_to_hex(lock->old_oid.hash),2283sha1_to_hex(old_sha1));2284 errno = EBUSY;2285return-1;2286}2287return0;2288}22892290static intremove_empty_directories(const char*file)2291{2292/* we want to create a file but there is a directory there;2293 * if that is an empty directory (or a directory that contains2294 * only empty directories), remove them.2295 */2296struct strbuf path;2297int result, save_errno;22982299strbuf_init(&path,20);2300strbuf_addstr(&path, file);23012302 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2303 save_errno = errno;23042305strbuf_release(&path);2306 errno = save_errno;23072308return result;2309}23102311/*2312 * *string and *len will only be substituted, and *string returned (for2313 * later free()ing) if the string passed in is a magic short-hand form2314 * to name a branch.2315 */2316static char*substitute_branch_name(const char**string,int*len)2317{2318struct strbuf buf = STRBUF_INIT;2319int ret =interpret_branch_name(*string, *len, &buf);23202321if(ret == *len) {2322size_t size;2323*string =strbuf_detach(&buf, &size);2324*len = size;2325return(char*)*string;2326}23272328return NULL;2329}23302331intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2332{2333char*last_branch =substitute_branch_name(&str, &len);2334const char**p, *r;2335int refs_found =0;23362337*ref = NULL;2338for(p = ref_rev_parse_rules; *p; p++) {2339char fullref[PATH_MAX];2340unsigned char sha1_from_ref[20];2341unsigned char*this_result;2342int flag;23432344 this_result = refs_found ? sha1_from_ref : sha1;2345mksnpath(fullref,sizeof(fullref), *p, len, str);2346 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2347 this_result, &flag);2348if(r) {2349if(!refs_found++)2350*ref =xstrdup(r);2351if(!warn_ambiguous_refs)2352break;2353}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2354warning("ignoring dangling symref%s.", fullref);2355}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2356warning("ignoring broken ref%s.", fullref);2357}2358}2359free(last_branch);2360return refs_found;2361}23622363intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2364{2365char*last_branch =substitute_branch_name(&str, &len);2366const char**p;2367int logs_found =0;23682369*log = NULL;2370for(p = ref_rev_parse_rules; *p; p++) {2371unsigned char hash[20];2372char path[PATH_MAX];2373const char*ref, *it;23742375mksnpath(path,sizeof(path), *p, len, str);2376 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2377 hash, NULL);2378if(!ref)2379continue;2380if(reflog_exists(path))2381 it = path;2382else if(strcmp(ref, path) &&reflog_exists(ref))2383 it = ref;2384else2385continue;2386if(!logs_found++) {2387*log =xstrdup(it);2388hashcpy(sha1, hash);2389}2390if(!warn_ambiguous_refs)2391break;2392}2393free(last_branch);2394return logs_found;2395}23962397/*2398 * Locks a ref returning the lock on success and NULL on failure.2399 * On failure errno is set to something meaningful.2400 */2401static struct ref_lock *lock_ref_sha1_basic(const char*refname,2402const unsigned char*old_sha1,2403const struct string_list *extras,2404const struct string_list *skip,2405unsigned int flags,int*type_p,2406struct strbuf *err)2407{2408const char*ref_file;2409const char*orig_refname = refname;2410struct ref_lock *lock;2411int last_errno =0;2412int type, lflags;2413int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2414int resolve_flags =0;2415int attempts_remaining =3;24162417assert(err);24182419 lock =xcalloc(1,sizeof(struct ref_lock));24202421if(mustexist)2422 resolve_flags |= RESOLVE_REF_READING;2423if(flags & REF_DELETING) {2424 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2425if(flags & REF_NODEREF)2426 resolve_flags |= RESOLVE_REF_NO_RECURSE;2427}24282429 refname =resolve_ref_unsafe(refname, resolve_flags,2430 lock->old_oid.hash, &type);2431if(!refname && errno == EISDIR) {2432/* we are trying to lock foo but we used to2433 * have foo/bar which now does not exist;2434 * it is normal for the empty directory 'foo'2435 * to remain.2436 */2437 ref_file =git_path("%s", orig_refname);2438if(remove_empty_directories(ref_file)) {2439 last_errno = errno;24402441if(!verify_refname_available(orig_refname, extras, skip,2442get_loose_refs(&ref_cache), err))2443strbuf_addf(err,"there are still refs under '%s'",2444 orig_refname);24452446goto error_return;2447}2448 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2449 lock->old_oid.hash, &type);2450}2451if(type_p)2452*type_p = type;2453if(!refname) {2454 last_errno = errno;2455if(last_errno != ENOTDIR ||2456!verify_refname_available(orig_refname, extras, skip,2457get_loose_refs(&ref_cache), err))2458strbuf_addf(err,"unable to resolve reference%s:%s",2459 orig_refname,strerror(last_errno));24602461goto error_return;2462}2463/*2464 * If the ref did not exist and we are creating it, make sure2465 * there is no existing packed ref whose name begins with our2466 * refname, nor a packed ref whose name is a proper prefix of2467 * our refname.2468 */2469if(is_null_oid(&lock->old_oid) &&2470verify_refname_available(refname, extras, skip,2471get_packed_refs(&ref_cache), err)) {2472 last_errno = ENOTDIR;2473goto error_return;2474}24752476 lock->lk =xcalloc(1,sizeof(struct lock_file));24772478 lflags =0;2479if(flags & REF_NODEREF) {2480 refname = orig_refname;2481 lflags |= LOCK_NO_DEREF;2482}2483 lock->ref_name =xstrdup(refname);2484 lock->orig_ref_name =xstrdup(orig_refname);2485 ref_file =git_path("%s", refname);24862487 retry:2488switch(safe_create_leading_directories_const(ref_file)) {2489case SCLD_OK:2490break;/* success */2491case SCLD_VANISHED:2492if(--attempts_remaining >0)2493goto retry;2494/* fall through */2495default:2496 last_errno = errno;2497strbuf_addf(err,"unable to create directory for%s", ref_file);2498goto error_return;2499}25002501if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2502 last_errno = errno;2503if(errno == ENOENT && --attempts_remaining >0)2504/*2505 * Maybe somebody just deleted one of the2506 * directories leading to ref_file. Try2507 * again:2508 */2509goto retry;2510else{2511unable_to_lock_message(ref_file, errno, err);2512goto error_return;2513}2514}2515if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2516 last_errno = errno;2517goto error_return;2518}2519return lock;25202521 error_return:2522unlock_ref(lock);2523 errno = last_errno;2524return NULL;2525}25262527/*2528 * Write an entry to the packed-refs file for the specified refname.2529 * If peeled is non-NULL, write it as the entry's peeled value.2530 */2531static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2532unsigned char*peeled)2533{2534fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2535if(peeled)2536fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2537}25382539/*2540 * An each_ref_entry_fn that writes the entry to a packed-refs file.2541 */2542static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2543{2544enum peel_status peel_status =peel_entry(entry,0);25452546if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2547error("internal error:%sis not a valid packed reference!",2548 entry->name);2549write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2550 peel_status == PEEL_PEELED ?2551 entry->u.value.peeled.hash : NULL);2552return0;2553}25542555/*2556 * Lock the packed-refs file for writing. Flags is passed to2557 * hold_lock_file_for_update(). Return 0 on success. On errors, set2558 * errno appropriately and return a nonzero value.2559 */2560static intlock_packed_refs(int flags)2561{2562static int timeout_configured =0;2563static int timeout_value =1000;25642565struct packed_ref_cache *packed_ref_cache;25662567if(!timeout_configured) {2568git_config_get_int("core.packedrefstimeout", &timeout_value);2569 timeout_configured =1;2570}25712572if(hold_lock_file_for_update_timeout(2573&packlock,git_path("packed-refs"),2574 flags, timeout_value) <0)2575return-1;2576/*2577 * Get the current packed-refs while holding the lock. If the2578 * packed-refs file has been modified since we last read it,2579 * this will automatically invalidate the cache and re-read2580 * the packed-refs file.2581 */2582 packed_ref_cache =get_packed_ref_cache(&ref_cache);2583 packed_ref_cache->lock = &packlock;2584/* Increment the reference count to prevent it from being freed: */2585acquire_packed_ref_cache(packed_ref_cache);2586return0;2587}25882589/*2590 * Write the current version of the packed refs cache from memory to2591 * disk. The packed-refs file must already be locked for writing (see2592 * lock_packed_refs()). Return zero on success. On errors, set errno2593 * and return a nonzero value2594 */2595static intcommit_packed_refs(void)2596{2597struct packed_ref_cache *packed_ref_cache =2598get_packed_ref_cache(&ref_cache);2599int error =0;2600int save_errno =0;2601FILE*out;26022603if(!packed_ref_cache->lock)2604die("internal error: packed-refs not locked");26052606 out =fdopen_lock_file(packed_ref_cache->lock,"w");2607if(!out)2608die_errno("unable to fdopen packed-refs descriptor");26092610fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2611do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26120, write_packed_entry_fn, out);26132614if(commit_lock_file(packed_ref_cache->lock)) {2615 save_errno = errno;2616 error = -1;2617}2618 packed_ref_cache->lock = NULL;2619release_packed_ref_cache(packed_ref_cache);2620 errno = save_errno;2621return error;2622}26232624/*2625 * Rollback the lockfile for the packed-refs file, and discard the2626 * in-memory packed reference cache. (The packed-refs file will be2627 * read anew if it is needed again after this function is called.)2628 */2629static voidrollback_packed_refs(void)2630{2631struct packed_ref_cache *packed_ref_cache =2632get_packed_ref_cache(&ref_cache);26332634if(!packed_ref_cache->lock)2635die("internal error: packed-refs not locked");2636rollback_lock_file(packed_ref_cache->lock);2637 packed_ref_cache->lock = NULL;2638release_packed_ref_cache(packed_ref_cache);2639clear_packed_ref_cache(&ref_cache);2640}26412642struct ref_to_prune {2643struct ref_to_prune *next;2644unsigned char sha1[20];2645char name[FLEX_ARRAY];2646};26472648struct pack_refs_cb_data {2649unsigned int flags;2650struct ref_dir *packed_refs;2651struct ref_to_prune *ref_to_prune;2652};26532654/*2655 * An each_ref_entry_fn that is run over loose references only. If2656 * the loose reference can be packed, add an entry in the packed ref2657 * cache. If the reference should be pruned, also add it to2658 * ref_to_prune in the pack_refs_cb_data.2659 */2660static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2661{2662struct pack_refs_cb_data *cb = cb_data;2663enum peel_status peel_status;2664struct ref_entry *packed_entry;2665int is_tag_ref =starts_with(entry->name,"refs/tags/");26662667/* ALWAYS pack tags */2668if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2669return0;26702671/* Do not pack symbolic or broken refs: */2672if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2673return0;26742675/* Add a packed ref cache entry equivalent to the loose entry. */2676 peel_status =peel_entry(entry,1);2677if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2678die("internal error peeling reference%s(%s)",2679 entry->name,oid_to_hex(&entry->u.value.oid));2680 packed_entry =find_ref(cb->packed_refs, entry->name);2681if(packed_entry) {2682/* Overwrite existing packed entry with info from loose entry */2683 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2684oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2685}else{2686 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2687 REF_ISPACKED | REF_KNOWS_PEELED,0);2688add_ref(cb->packed_refs, packed_entry);2689}2690oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26912692/* Schedule the loose reference for pruning if requested. */2693if((cb->flags & PACK_REFS_PRUNE)) {2694int namelen =strlen(entry->name) +1;2695struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2696hashcpy(n->sha1, entry->u.value.oid.hash);2697strcpy(n->name, entry->name);2698 n->next = cb->ref_to_prune;2699 cb->ref_to_prune = n;2700}2701return0;2702}27032704/*2705 * Remove empty parents, but spare refs/ and immediate subdirs.2706 * Note: munges *name.2707 */2708static voidtry_remove_empty_parents(char*name)2709{2710char*p, *q;2711int i;2712 p = name;2713for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2714while(*p && *p !='/')2715 p++;2716/* tolerate duplicate slashes; see check_refname_format() */2717while(*p =='/')2718 p++;2719}2720for(q = p; *q; q++)2721;2722while(1) {2723while(q > p && *q !='/')2724 q--;2725while(q > p && *(q-1) =='/')2726 q--;2727if(q == p)2728break;2729*q ='\0';2730if(rmdir(git_path("%s", name)))2731break;2732}2733}27342735/* make sure nobody touched the ref, and unlink */2736static voidprune_ref(struct ref_to_prune *r)2737{2738struct ref_transaction *transaction;2739struct strbuf err = STRBUF_INIT;27402741if(check_refname_format(r->name,0))2742return;27432744 transaction =ref_transaction_begin(&err);2745if(!transaction ||2746ref_transaction_delete(transaction, r->name, r->sha1,2747 REF_ISPRUNING, NULL, &err) ||2748ref_transaction_commit(transaction, &err)) {2749ref_transaction_free(transaction);2750error("%s", err.buf);2751strbuf_release(&err);2752return;2753}2754ref_transaction_free(transaction);2755strbuf_release(&err);2756try_remove_empty_parents(r->name);2757}27582759static voidprune_refs(struct ref_to_prune *r)2760{2761while(r) {2762prune_ref(r);2763 r = r->next;2764}2765}27662767intpack_refs(unsigned int flags)2768{2769struct pack_refs_cb_data cbdata;27702771memset(&cbdata,0,sizeof(cbdata));2772 cbdata.flags = flags;27732774lock_packed_refs(LOCK_DIE_ON_ERROR);2775 cbdata.packed_refs =get_packed_refs(&ref_cache);27762777do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2778 pack_if_possible_fn, &cbdata);27792780if(commit_packed_refs())2781die_errno("unable to overwrite old ref-pack file");27822783prune_refs(cbdata.ref_to_prune);2784return0;2785}27862787/*2788 * Rewrite the packed-refs file, omitting any refs listed in2789 * 'refnames'. On error, leave packed-refs unchanged, write an error2790 * message to 'err', and return a nonzero value.2791 *2792 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2793 */2794static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2795{2796struct ref_dir *packed;2797struct string_list_item *refname;2798int ret, needs_repacking =0, removed =0;27992800assert(err);28012802/* Look for a packed ref */2803for_each_string_list_item(refname, refnames) {2804if(get_packed_ref(refname->string)) {2805 needs_repacking =1;2806break;2807}2808}28092810/* Avoid locking if we have nothing to do */2811if(!needs_repacking)2812return0;/* no refname exists in packed refs */28132814if(lock_packed_refs(0)) {2815unable_to_lock_message(git_path("packed-refs"), errno, err);2816return-1;2817}2818 packed =get_packed_refs(&ref_cache);28192820/* Remove refnames from the cache */2821for_each_string_list_item(refname, refnames)2822if(remove_entry(packed, refname->string) != -1)2823 removed =1;2824if(!removed) {2825/*2826 * All packed entries disappeared while we were2827 * acquiring the lock.2828 */2829rollback_packed_refs();2830return0;2831}28322833/* Write what remains */2834 ret =commit_packed_refs();2835if(ret)2836strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2837strerror(errno));2838return ret;2839}28402841static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2842{2843assert(err);28442845if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2846/*2847 * loose. The loose file name is the same as the2848 * lockfile name, minus ".lock":2849 */2850char*loose_filename =get_locked_file_path(lock->lk);2851int res =unlink_or_msg(loose_filename, err);2852free(loose_filename);2853if(res)2854return1;2855}2856return0;2857}28582859intdelete_ref(const char*refname,const unsigned char*old_sha1,2860unsigned int flags)2861{2862struct ref_transaction *transaction;2863struct strbuf err = STRBUF_INIT;28642865 transaction =ref_transaction_begin(&err);2866if(!transaction ||2867ref_transaction_delete(transaction, refname, old_sha1,2868 flags, NULL, &err) ||2869ref_transaction_commit(transaction, &err)) {2870error("%s", err.buf);2871ref_transaction_free(transaction);2872strbuf_release(&err);2873return1;2874}2875ref_transaction_free(transaction);2876strbuf_release(&err);2877return0;2878}28792880intdelete_refs(struct string_list *refnames)2881{2882struct strbuf err = STRBUF_INIT;2883int i, result =0;28842885if(!refnames->nr)2886return0;28872888 result =repack_without_refs(refnames, &err);2889if(result) {2890/*2891 * If we failed to rewrite the packed-refs file, then2892 * it is unsafe to try to remove loose refs, because2893 * doing so might expose an obsolete packed value for2894 * a reference that might even point at an object that2895 * has been garbage collected.2896 */2897if(refnames->nr ==1)2898error(_("could not delete reference%s:%s"),2899 refnames->items[0].string, err.buf);2900else2901error(_("could not delete references:%s"), err.buf);29022903goto out;2904}29052906for(i =0; i < refnames->nr; i++) {2907const char*refname = refnames->items[i].string;29082909if(delete_ref(refname, NULL,0))2910 result |=error(_("could not remove reference%s"), refname);2911}29122913out:2914strbuf_release(&err);2915return result;2916}29172918/*2919 * People using contrib's git-new-workdir have .git/logs/refs ->2920 * /some/other/path/.git/logs/refs, and that may live on another device.2921 *2922 * IOW, to avoid cross device rename errors, the temporary renamed log must2923 * live into logs/refs.2924 */2925#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"29262927static intrename_tmp_log(const char*newrefname)2928{2929int attempts_remaining =4;29302931 retry:2932switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2933case SCLD_OK:2934break;/* success */2935case SCLD_VANISHED:2936if(--attempts_remaining >0)2937goto retry;2938/* fall through */2939default:2940error("unable to create directory for%s", newrefname);2941return-1;2942}29432944if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2945if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2946/*2947 * rename(a, b) when b is an existing2948 * directory ought to result in ISDIR, but2949 * Solaris 5.8 gives ENOTDIR. Sheesh.2950 */2951if(remove_empty_directories(git_path("logs/%s", newrefname))) {2952error("Directory not empty: logs/%s", newrefname);2953return-1;2954}2955goto retry;2956}else if(errno == ENOENT && --attempts_remaining >0) {2957/*2958 * Maybe another process just deleted one of2959 * the directories in the path to newrefname.2960 * Try again from the beginning.2961 */2962goto retry;2963}else{2964error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2965 newrefname,strerror(errno));2966return-1;2967}2968}2969return0;2970}29712972static intrename_ref_available(const char*oldname,const char*newname)2973{2974struct string_list skip = STRING_LIST_INIT_NODUP;2975struct strbuf err = STRBUF_INIT;2976int ret;29772978string_list_insert(&skip, oldname);2979 ret = !verify_refname_available(newname, NULL, &skip,2980get_packed_refs(&ref_cache), &err)2981&& !verify_refname_available(newname, NULL, &skip,2982get_loose_refs(&ref_cache), &err);2983if(!ret)2984error("%s", err.buf);29852986string_list_clear(&skip,0);2987strbuf_release(&err);2988return ret;2989}29902991static intwrite_ref_to_lockfile(struct ref_lock *lock,2992const unsigned char*sha1,struct strbuf *err);2993static intcommit_ref_update(struct ref_lock *lock,2994const unsigned char*sha1,const char*logmsg,2995int flags,struct strbuf *err);29962997intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2998{2999unsigned char sha1[20], orig_sha1[20];3000int flag =0, logmoved =0;3001struct ref_lock *lock;3002struct stat loginfo;3003int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3004const char*symref = NULL;3005struct strbuf err = STRBUF_INIT;30063007if(log &&S_ISLNK(loginfo.st_mode))3008returnerror("reflog for%sis a symlink", oldrefname);30093010 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3011 orig_sha1, &flag);3012if(flag & REF_ISSYMREF)3013returnerror("refname%sis a symbolic ref, renaming it is not supported",3014 oldrefname);3015if(!symref)3016returnerror("refname%snot found", oldrefname);30173018if(!rename_ref_available(oldrefname, newrefname))3019return1;30203021if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3022returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3023 oldrefname,strerror(errno));30243025if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3026error("unable to delete old%s", oldrefname);3027goto rollback;3028}30293030if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3031delete_ref(newrefname, sha1, REF_NODEREF)) {3032if(errno==EISDIR) {3033if(remove_empty_directories(git_path("%s", newrefname))) {3034error("Directory not empty:%s", newrefname);3035goto rollback;3036}3037}else{3038error("unable to delete existing%s", newrefname);3039goto rollback;3040}3041}30423043if(log &&rename_tmp_log(newrefname))3044goto rollback;30453046 logmoved = log;30473048 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3049if(!lock) {3050error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3051strbuf_release(&err);3052goto rollback;3053}3054hashcpy(lock->old_oid.hash, orig_sha1);30553056if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3057commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3058error("unable to write current sha1 into%s:%s", newrefname, err.buf);3059strbuf_release(&err);3060goto rollback;3061}30623063return0;30643065 rollback:3066 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3067if(!lock) {3068error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3069strbuf_release(&err);3070goto rollbacklog;3071}30723073 flag = log_all_ref_updates;3074 log_all_ref_updates =0;3075if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3076commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3077error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3078strbuf_release(&err);3079}3080 log_all_ref_updates = flag;30813082 rollbacklog:3083if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3084error("unable to restore logfile%sfrom%s:%s",3085 oldrefname, newrefname,strerror(errno));3086if(!logmoved && log &&3087rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3088error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3089 oldrefname,strerror(errno));30903091return1;3092}30933094static intclose_ref(struct ref_lock *lock)3095{3096if(close_lock_file(lock->lk))3097return-1;3098return0;3099}31003101static intcommit_ref(struct ref_lock *lock)3102{3103if(commit_lock_file(lock->lk))3104return-1;3105return0;3106}31073108/*3109 * copy the reflog message msg to buf, which has been allocated sufficiently3110 * large, while cleaning up the whitespaces. Especially, convert LF to space,3111 * because reflog file is one line per entry.3112 */3113static intcopy_msg(char*buf,const char*msg)3114{3115char*cp = buf;3116char c;3117int wasspace =1;31183119*cp++ ='\t';3120while((c = *msg++)) {3121if(wasspace &&isspace(c))3122continue;3123 wasspace =isspace(c);3124if(wasspace)3125 c =' ';3126*cp++ = c;3127}3128while(buf < cp &&isspace(cp[-1]))3129 cp--;3130*cp++ ='\n';3131return cp - buf;3132}31333134static intshould_autocreate_reflog(const char*refname)3135{3136if(!log_all_ref_updates)3137return0;3138returnstarts_with(refname,"refs/heads/") ||3139starts_with(refname,"refs/remotes/") ||3140starts_with(refname,"refs/notes/") ||3141!strcmp(refname,"HEAD");3142}31433144/*3145 * Create a reflog for a ref. If force_create = 0, the reflog will3146 * only be created for certain refs (those for which3147 * should_autocreate_reflog returns non-zero. Otherwise, create it3148 * regardless of the ref name. Fill in *err and return -1 on failure.3149 */3150static intlog_ref_setup(const char*refname,struct strbuf *sb_logfile,struct strbuf *err,int force_create)3151{3152int logfd, oflags = O_APPEND | O_WRONLY;3153char*logfile;31543155strbuf_git_path(sb_logfile,"logs/%s", refname);3156 logfile = sb_logfile->buf;3157/* make sure the rest of the function can't change "logfile" */3158 sb_logfile = NULL;3159if(force_create ||should_autocreate_reflog(refname)) {3160if(safe_create_leading_directories(logfile) <0) {3161strbuf_addf(err,"unable to create directory for%s: "3162"%s", logfile,strerror(errno));3163return-1;3164}3165 oflags |= O_CREAT;3166}31673168 logfd =open(logfile, oflags,0666);3169if(logfd <0) {3170if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3171return0;31723173if(errno == EISDIR) {3174if(remove_empty_directories(logfile)) {3175strbuf_addf(err,"There are still logs under "3176"'%s'", logfile);3177return-1;3178}3179 logfd =open(logfile, oflags,0666);3180}31813182if(logfd <0) {3183strbuf_addf(err,"unable to append to%s:%s",3184 logfile,strerror(errno));3185return-1;3186}3187}31883189adjust_shared_perm(logfile);3190close(logfd);3191return0;3192}319331943195intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3196{3197int ret;3198struct strbuf sb = STRBUF_INIT;31993200 ret =log_ref_setup(refname, &sb, err, force_create);3201strbuf_release(&sb);3202return ret;3203}32043205static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3206const unsigned char*new_sha1,3207const char*committer,const char*msg)3208{3209int msglen, written;3210unsigned maxlen, len;3211char*logrec;32123213 msglen = msg ?strlen(msg) :0;3214 maxlen =strlen(committer) + msglen +100;3215 logrec =xmalloc(maxlen);3216 len =sprintf(logrec,"%s %s %s\n",3217sha1_to_hex(old_sha1),3218sha1_to_hex(new_sha1),3219 committer);3220if(msglen)3221 len +=copy_msg(logrec + len -1, msg) -1;32223223 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3224free(logrec);3225if(written != len)3226return-1;32273228return0;3229}32303231static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3232const unsigned char*new_sha1,const char*msg,3233struct strbuf *sb_log_file,int flags,3234struct strbuf *err)3235{3236int logfd, result, oflags = O_APPEND | O_WRONLY;3237char*log_file;32383239if(log_all_ref_updates <0)3240 log_all_ref_updates = !is_bare_repository();32413242 result =log_ref_setup(refname, sb_log_file, err, flags & REF_FORCE_CREATE_REFLOG);32433244if(result)3245return result;3246 log_file = sb_log_file->buf;3247/* make sure the rest of the function can't change "log_file" */3248 sb_log_file = NULL;32493250 logfd =open(log_file, oflags);3251if(logfd <0)3252return0;3253 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3254git_committer_info(0), msg);3255if(result) {3256strbuf_addf(err,"unable to append to%s:%s", log_file,3257strerror(errno));3258close(logfd);3259return-1;3260}3261if(close(logfd)) {3262strbuf_addf(err,"unable to append to%s:%s", log_file,3263strerror(errno));3264return-1;3265}3266return0;3267}32683269static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3270const unsigned char*new_sha1,const char*msg,3271int flags,struct strbuf *err)3272{3273struct strbuf sb = STRBUF_INIT;3274int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3275 err);3276strbuf_release(&sb);3277return ret;3278}32793280intis_branch(const char*refname)3281{3282return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3283}32843285/*3286 * Write sha1 into the open lockfile, then close the lockfile. On3287 * errors, rollback the lockfile, fill in *err and3288 * return -1.3289 */3290static intwrite_ref_to_lockfile(struct ref_lock *lock,3291const unsigned char*sha1,struct strbuf *err)3292{3293static char term ='\n';3294struct object *o;32953296 o =parse_object(sha1);3297if(!o) {3298strbuf_addf(err,3299"Trying to write ref%swith nonexistent object%s",3300 lock->ref_name,sha1_to_hex(sha1));3301unlock_ref(lock);3302return-1;3303}3304if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3305strbuf_addf(err,3306"Trying to write non-commit object%sto branch%s",3307sha1_to_hex(sha1), lock->ref_name);3308unlock_ref(lock);3309return-1;3310}3311if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3312write_in_full(lock->lk->fd, &term,1) !=1||3313close_ref(lock) <0) {3314strbuf_addf(err,3315"Couldn't write%s", lock->lk->filename.buf);3316unlock_ref(lock);3317return-1;3318}3319return0;3320}33213322/*3323 * Commit a change to a loose reference that has already been written3324 * to the loose reference lockfile. Also update the reflogs if3325 * necessary, using the specified lockmsg (which can be NULL).3326 */3327static intcommit_ref_update(struct ref_lock *lock,3328const unsigned char*sha1,const char*logmsg,3329int flags,struct strbuf *err)3330{3331clear_loose_ref_cache(&ref_cache);3332if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3333(strcmp(lock->ref_name, lock->orig_ref_name) &&3334log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3335char*old_msg =strbuf_detach(err, NULL);3336strbuf_addf(err,"Cannot update the ref '%s':%s",3337 lock->ref_name, old_msg);3338free(old_msg);3339unlock_ref(lock);3340return-1;3341}3342if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3343/*3344 * Special hack: If a branch is updated directly and HEAD3345 * points to it (may happen on the remote side of a push3346 * for example) then logically the HEAD reflog should be3347 * updated too.3348 * A generic solution implies reverse symref information,3349 * but finding all symrefs pointing to the given branch3350 * would be rather costly for this rare event (the direct3351 * update of a branch) to be worth it. So let's cheat and3352 * check with HEAD only which should cover 99% of all usage3353 * scenarios (even 100% of the default ones).3354 */3355unsigned char head_sha1[20];3356int head_flag;3357const char*head_ref;3358 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3359 head_sha1, &head_flag);3360if(head_ref && (head_flag & REF_ISSYMREF) &&3361!strcmp(head_ref, lock->ref_name)) {3362struct strbuf log_err = STRBUF_INIT;3363if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3364 logmsg,0, &log_err)) {3365error("%s", log_err.buf);3366strbuf_release(&log_err);3367}3368}3369}3370if(commit_ref(lock)) {3371error("Couldn't set%s", lock->ref_name);3372unlock_ref(lock);3373return-1;3374}33753376unlock_ref(lock);3377return0;3378}33793380intcreate_symref(const char*ref_target,const char*refs_heads_master,3381const char*logmsg)3382{3383char*lockpath = NULL;3384char ref[1000];3385int fd, len, written;3386char*git_HEAD =git_pathdup("%s", ref_target);3387unsigned char old_sha1[20], new_sha1[20];3388struct strbuf err = STRBUF_INIT;33893390if(logmsg &&read_ref(ref_target, old_sha1))3391hashclr(old_sha1);33923393if(safe_create_leading_directories(git_HEAD) <0)3394returnerror("unable to create directory for%s", git_HEAD);33953396#ifndef NO_SYMLINK_HEAD3397if(prefer_symlink_refs) {3398unlink(git_HEAD);3399if(!symlink(refs_heads_master, git_HEAD))3400goto done;3401fprintf(stderr,"no symlink - falling back to symbolic ref\n");3402}3403#endif34043405 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3406if(sizeof(ref) <= len) {3407error("refname too long:%s", refs_heads_master);3408goto error_free_return;3409}3410 lockpath =mkpathdup("%s.lock", git_HEAD);3411 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3412if(fd <0) {3413error("Unable to open%sfor writing", lockpath);3414goto error_free_return;3415}3416 written =write_in_full(fd, ref, len);3417if(close(fd) !=0|| written != len) {3418error("Unable to write to%s", lockpath);3419goto error_unlink_return;3420}3421if(rename(lockpath, git_HEAD) <0) {3422error("Unable to create%s", git_HEAD);3423goto error_unlink_return;3424}3425if(adjust_shared_perm(git_HEAD)) {3426error("Unable to fix permissions on%s", lockpath);3427 error_unlink_return:3428unlink_or_warn(lockpath);3429 error_free_return:3430free(lockpath);3431free(git_HEAD);3432return-1;3433}3434free(lockpath);34353436#ifndef NO_SYMLINK_HEAD3437 done:3438#endif3439if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3440log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3441error("%s", err.buf);3442strbuf_release(&err);3443}34443445free(git_HEAD);3446return0;3447}34483449struct read_ref_at_cb {3450const char*refname;3451unsigned long at_time;3452int cnt;3453int reccnt;3454unsigned char*sha1;3455int found_it;34563457unsigned char osha1[20];3458unsigned char nsha1[20];3459int tz;3460unsigned long date;3461char**msg;3462unsigned long*cutoff_time;3463int*cutoff_tz;3464int*cutoff_cnt;3465};34663467static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3468const char*email,unsigned long timestamp,int tz,3469const char*message,void*cb_data)3470{3471struct read_ref_at_cb *cb = cb_data;34723473 cb->reccnt++;3474 cb->tz = tz;3475 cb->date = timestamp;34763477if(timestamp <= cb->at_time || cb->cnt ==0) {3478if(cb->msg)3479*cb->msg =xstrdup(message);3480if(cb->cutoff_time)3481*cb->cutoff_time = timestamp;3482if(cb->cutoff_tz)3483*cb->cutoff_tz = tz;3484if(cb->cutoff_cnt)3485*cb->cutoff_cnt = cb->reccnt -1;3486/*3487 * we have not yet updated cb->[n|o]sha1 so they still3488 * hold the values for the previous record.3489 */3490if(!is_null_sha1(cb->osha1)) {3491hashcpy(cb->sha1, nsha1);3492if(hashcmp(cb->osha1, nsha1))3493warning("Log for ref%shas gap after%s.",3494 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3495}3496else if(cb->date == cb->at_time)3497hashcpy(cb->sha1, nsha1);3498else if(hashcmp(nsha1, cb->sha1))3499warning("Log for ref%sunexpectedly ended on%s.",3500 cb->refname,show_date(cb->date, cb->tz,3501DATE_MODE(RFC2822)));3502hashcpy(cb->osha1, osha1);3503hashcpy(cb->nsha1, nsha1);3504 cb->found_it =1;3505return1;3506}3507hashcpy(cb->osha1, osha1);3508hashcpy(cb->nsha1, nsha1);3509if(cb->cnt >0)3510 cb->cnt--;3511return0;3512}35133514static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3515const char*email,unsigned long timestamp,3516int tz,const char*message,void*cb_data)3517{3518struct read_ref_at_cb *cb = cb_data;35193520if(cb->msg)3521*cb->msg =xstrdup(message);3522if(cb->cutoff_time)3523*cb->cutoff_time = timestamp;3524if(cb->cutoff_tz)3525*cb->cutoff_tz = tz;3526if(cb->cutoff_cnt)3527*cb->cutoff_cnt = cb->reccnt;3528hashcpy(cb->sha1, osha1);3529if(is_null_sha1(cb->sha1))3530hashcpy(cb->sha1, nsha1);3531/* We just want the first entry */3532return1;3533}35343535intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3536unsigned char*sha1,char**msg,3537unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3538{3539struct read_ref_at_cb cb;35403541memset(&cb,0,sizeof(cb));3542 cb.refname = refname;3543 cb.at_time = at_time;3544 cb.cnt = cnt;3545 cb.msg = msg;3546 cb.cutoff_time = cutoff_time;3547 cb.cutoff_tz = cutoff_tz;3548 cb.cutoff_cnt = cutoff_cnt;3549 cb.sha1 = sha1;35503551for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);35523553if(!cb.reccnt) {3554if(flags & GET_SHA1_QUIETLY)3555exit(128);3556else3557die("Log for%sis empty.", refname);3558}3559if(cb.found_it)3560return0;35613562for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);35633564return1;3565}35663567intreflog_exists(const char*refname)3568{3569struct stat st;35703571return!lstat(git_path("logs/%s", refname), &st) &&3572S_ISREG(st.st_mode);3573}35743575intdelete_reflog(const char*refname)3576{3577returnremove_path(git_path("logs/%s", refname));3578}35793580static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3581{3582unsigned char osha1[20], nsha1[20];3583char*email_end, *message;3584unsigned long timestamp;3585int tz;35863587/* old SP new SP name <email> SP time TAB msg LF */3588if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3589get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3590get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3591!(email_end =strchr(sb->buf +82,'>')) ||3592 email_end[1] !=' '||3593!(timestamp =strtoul(email_end +2, &message,10)) ||3594!message || message[0] !=' '||3595(message[1] !='+'&& message[1] !='-') ||3596!isdigit(message[2]) || !isdigit(message[3]) ||3597!isdigit(message[4]) || !isdigit(message[5]))3598return0;/* corrupt? */3599 email_end[1] ='\0';3600 tz =strtol(message +1, NULL,10);3601if(message[6] !='\t')3602 message +=6;3603else3604 message +=7;3605returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3606}36073608static char*find_beginning_of_line(char*bob,char*scan)3609{3610while(bob < scan && *(--scan) !='\n')3611;/* keep scanning backwards */3612/*3613 * Return either beginning of the buffer, or LF at the end of3614 * the previous line.3615 */3616return scan;3617}36183619intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3620{3621struct strbuf sb = STRBUF_INIT;3622FILE*logfp;3623long pos;3624int ret =0, at_tail =1;36253626 logfp =fopen(git_path("logs/%s", refname),"r");3627if(!logfp)3628return-1;36293630/* Jump to the end */3631if(fseek(logfp,0, SEEK_END) <0)3632returnerror("cannot seek back reflog for%s:%s",3633 refname,strerror(errno));3634 pos =ftell(logfp);3635while(!ret &&0< pos) {3636int cnt;3637size_t nread;3638char buf[BUFSIZ];3639char*endp, *scanp;36403641/* Fill next block from the end */3642 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3643if(fseek(logfp, pos - cnt, SEEK_SET))3644returnerror("cannot seek back reflog for%s:%s",3645 refname,strerror(errno));3646 nread =fread(buf, cnt,1, logfp);3647if(nread !=1)3648returnerror("cannot read%dbytes from reflog for%s:%s",3649 cnt, refname,strerror(errno));3650 pos -= cnt;36513652 scanp = endp = buf + cnt;3653if(at_tail && scanp[-1] =='\n')3654/* Looking at the final LF at the end of the file */3655 scanp--;3656 at_tail =0;36573658while(buf < scanp) {3659/*3660 * terminating LF of the previous line, or the beginning3661 * of the buffer.3662 */3663char*bp;36643665 bp =find_beginning_of_line(buf, scanp);36663667if(*bp =='\n') {3668/*3669 * The newline is the end of the previous line,3670 * so we know we have complete line starting3671 * at (bp + 1). Prefix it onto any prior data3672 * we collected for the line and process it.3673 */3674strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3675 scanp = bp;3676 endp = bp +1;3677 ret =show_one_reflog_ent(&sb, fn, cb_data);3678strbuf_reset(&sb);3679if(ret)3680break;3681}else if(!pos) {3682/*3683 * We are at the start of the buffer, and the3684 * start of the file; there is no previous3685 * line, and we have everything for this one.3686 * Process it, and we can end the loop.3687 */3688strbuf_splice(&sb,0,0, buf, endp - buf);3689 ret =show_one_reflog_ent(&sb, fn, cb_data);3690strbuf_reset(&sb);3691break;3692}36933694if(bp == buf) {3695/*3696 * We are at the start of the buffer, and there3697 * is more file to read backwards. Which means3698 * we are in the middle of a line. Note that we3699 * may get here even if *bp was a newline; that3700 * just means we are at the exact end of the3701 * previous line, rather than some spot in the3702 * middle.3703 *3704 * Save away what we have to be combined with3705 * the data from the next read.3706 */3707strbuf_splice(&sb,0,0, buf, endp - buf);3708break;3709}3710}37113712}3713if(!ret && sb.len)3714die("BUG: reverse reflog parser had leftover data");37153716fclose(logfp);3717strbuf_release(&sb);3718return ret;3719}37203721intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3722{3723FILE*logfp;3724struct strbuf sb = STRBUF_INIT;3725int ret =0;37263727 logfp =fopen(git_path("logs/%s", refname),"r");3728if(!logfp)3729return-1;37303731while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3732 ret =show_one_reflog_ent(&sb, fn, cb_data);3733fclose(logfp);3734strbuf_release(&sb);3735return ret;3736}3737/*3738 * Call fn for each reflog in the namespace indicated by name. name3739 * must be empty or end with '/'. Name will be used as a scratch3740 * space, but its contents will be restored before return.3741 */3742static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3743{3744DIR*d =opendir(git_path("logs/%s", name->buf));3745int retval =0;3746struct dirent *de;3747int oldlen = name->len;37483749if(!d)3750return name->len ? errno :0;37513752while((de =readdir(d)) != NULL) {3753struct stat st;37543755if(de->d_name[0] =='.')3756continue;3757if(ends_with(de->d_name,".lock"))3758continue;3759strbuf_addstr(name, de->d_name);3760if(stat(git_path("logs/%s", name->buf), &st) <0) {3761;/* silently ignore */3762}else{3763if(S_ISDIR(st.st_mode)) {3764strbuf_addch(name,'/');3765 retval =do_for_each_reflog(name, fn, cb_data);3766}else{3767struct object_id oid;37683769if(read_ref_full(name->buf,0, oid.hash, NULL))3770 retval =error("bad ref for%s", name->buf);3771else3772 retval =fn(name->buf, &oid,0, cb_data);3773}3774if(retval)3775break;3776}3777strbuf_setlen(name, oldlen);3778}3779closedir(d);3780return retval;3781}37823783intfor_each_reflog(each_ref_fn fn,void*cb_data)3784{3785int retval;3786struct strbuf name;3787strbuf_init(&name, PATH_MAX);3788 retval =do_for_each_reflog(&name, fn, cb_data);3789strbuf_release(&name);3790return retval;3791}37923793/**3794 * Information needed for a single ref update. Set new_sha1 to the new3795 * value or to null_sha1 to delete the ref. To check the old value3796 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3797 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3798 * not exist before update.3799 */3800struct ref_update {3801/*3802 * If (flags & REF_HAVE_NEW), set the reference to this value:3803 */3804unsigned char new_sha1[20];3805/*3806 * If (flags & REF_HAVE_OLD), check that the reference3807 * previously had this value:3808 */3809unsigned char old_sha1[20];3810/*3811 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3812 * REF_DELETING, and REF_ISPRUNING:3813 */3814unsigned int flags;3815struct ref_lock *lock;3816int type;3817char*msg;3818const char refname[FLEX_ARRAY];3819};38203821/*3822 * Transaction states.3823 * OPEN: The transaction is in a valid state and can accept new updates.3824 * An OPEN transaction can be committed.3825 * CLOSED: A closed transaction is no longer active and no other operations3826 * than free can be used on it in this state.3827 * A transaction can either become closed by successfully committing3828 * an active transaction or if there is a failure while building3829 * the transaction thus rendering it failed/inactive.3830 */3831enum ref_transaction_state {3832 REF_TRANSACTION_OPEN =0,3833 REF_TRANSACTION_CLOSED =13834};38353836/*3837 * Data structure for holding a reference transaction, which can3838 * consist of checks and updates to multiple references, carried out3839 * as atomically as possible. This structure is opaque to callers.3840 */3841struct ref_transaction {3842struct ref_update **updates;3843size_t alloc;3844size_t nr;3845enum ref_transaction_state state;3846};38473848struct ref_transaction *ref_transaction_begin(struct strbuf *err)3849{3850assert(err);38513852returnxcalloc(1,sizeof(struct ref_transaction));3853}38543855voidref_transaction_free(struct ref_transaction *transaction)3856{3857int i;38583859if(!transaction)3860return;38613862for(i =0; i < transaction->nr; i++) {3863free(transaction->updates[i]->msg);3864free(transaction->updates[i]);3865}3866free(transaction->updates);3867free(transaction);3868}38693870static struct ref_update *add_update(struct ref_transaction *transaction,3871const char*refname)3872{3873size_t len =strlen(refname);3874struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);38753876strcpy((char*)update->refname, refname);3877ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3878 transaction->updates[transaction->nr++] = update;3879return update;3880}38813882intref_transaction_update(struct ref_transaction *transaction,3883const char*refname,3884const unsigned char*new_sha1,3885const unsigned char*old_sha1,3886unsigned int flags,const char*msg,3887struct strbuf *err)3888{3889struct ref_update *update;38903891assert(err);38923893if(transaction->state != REF_TRANSACTION_OPEN)3894die("BUG: update called for transaction that is not open");38953896if(new_sha1 && !is_null_sha1(new_sha1) &&3897check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3898strbuf_addf(err,"refusing to update ref with bad name%s",3899 refname);3900return-1;3901}39023903 update =add_update(transaction, refname);3904if(new_sha1) {3905hashcpy(update->new_sha1, new_sha1);3906 flags |= REF_HAVE_NEW;3907}3908if(old_sha1) {3909hashcpy(update->old_sha1, old_sha1);3910 flags |= REF_HAVE_OLD;3911}3912 update->flags = flags;3913if(msg)3914 update->msg =xstrdup(msg);3915return0;3916}39173918intref_transaction_create(struct ref_transaction *transaction,3919const char*refname,3920const unsigned char*new_sha1,3921unsigned int flags,const char*msg,3922struct strbuf *err)3923{3924if(!new_sha1 ||is_null_sha1(new_sha1))3925die("BUG: create called without valid new_sha1");3926returnref_transaction_update(transaction, refname, new_sha1,3927 null_sha1, flags, msg, err);3928}39293930intref_transaction_delete(struct ref_transaction *transaction,3931const char*refname,3932const unsigned char*old_sha1,3933unsigned int flags,const char*msg,3934struct strbuf *err)3935{3936if(old_sha1 &&is_null_sha1(old_sha1))3937die("BUG: delete called with old_sha1 set to zeros");3938returnref_transaction_update(transaction, refname,3939 null_sha1, old_sha1,3940 flags, msg, err);3941}39423943intref_transaction_verify(struct ref_transaction *transaction,3944const char*refname,3945const unsigned char*old_sha1,3946unsigned int flags,3947struct strbuf *err)3948{3949if(!old_sha1)3950die("BUG: verify called with old_sha1 set to NULL");3951returnref_transaction_update(transaction, refname,3952 NULL, old_sha1,3953 flags, NULL, err);3954}39553956intupdate_ref(const char*msg,const char*refname,3957const unsigned char*new_sha1,const unsigned char*old_sha1,3958unsigned int flags,enum action_on_err onerr)3959{3960struct ref_transaction *t;3961struct strbuf err = STRBUF_INIT;39623963 t =ref_transaction_begin(&err);3964if(!t ||3965ref_transaction_update(t, refname, new_sha1, old_sha1,3966 flags, msg, &err) ||3967ref_transaction_commit(t, &err)) {3968const char*str ="update_ref failed for ref '%s':%s";39693970ref_transaction_free(t);3971switch(onerr) {3972case UPDATE_REFS_MSG_ON_ERR:3973error(str, refname, err.buf);3974break;3975case UPDATE_REFS_DIE_ON_ERR:3976die(str, refname, err.buf);3977break;3978case UPDATE_REFS_QUIET_ON_ERR:3979break;3980}3981strbuf_release(&err);3982return1;3983}3984strbuf_release(&err);3985ref_transaction_free(t);3986return0;3987}39883989static intref_update_reject_duplicates(struct string_list *refnames,3990struct strbuf *err)3991{3992int i, n = refnames->nr;39933994assert(err);39953996for(i =1; i < n; i++)3997if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3998strbuf_addf(err,3999"Multiple updates for ref '%s' not allowed.",4000 refnames->items[i].string);4001return1;4002}4003return0;4004}40054006intref_transaction_commit(struct ref_transaction *transaction,4007struct strbuf *err)4008{4009int ret =0, i;4010int n = transaction->nr;4011struct ref_update **updates = transaction->updates;4012struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4013struct string_list_item *ref_to_delete;4014struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40154016assert(err);40174018if(transaction->state != REF_TRANSACTION_OPEN)4019die("BUG: commit called for transaction that is not open");40204021if(!n) {4022 transaction->state = REF_TRANSACTION_CLOSED;4023return0;4024}40254026/* Fail if a refname appears more than once in the transaction: */4027for(i =0; i < n; i++)4028string_list_append(&affected_refnames, updates[i]->refname);4029string_list_sort(&affected_refnames);4030if(ref_update_reject_duplicates(&affected_refnames, err)) {4031 ret = TRANSACTION_GENERIC_ERROR;4032goto cleanup;4033}40344035/*4036 * Acquire all locks, verify old values if provided, check4037 * that new values are valid, and write new values to the4038 * lockfiles, ready to be activated. Only keep one lockfile4039 * open at a time to avoid running out of file descriptors.4040 */4041for(i =0; i < n; i++) {4042struct ref_update *update = updates[i];40434044if((update->flags & REF_HAVE_NEW) &&4045is_null_sha1(update->new_sha1))4046 update->flags |= REF_DELETING;4047 update->lock =lock_ref_sha1_basic(4048 update->refname,4049((update->flags & REF_HAVE_OLD) ?4050 update->old_sha1 : NULL),4051&affected_refnames, NULL,4052 update->flags,4053&update->type,4054 err);4055if(!update->lock) {4056char*reason;40574058 ret = (errno == ENOTDIR)4059? TRANSACTION_NAME_CONFLICT4060: TRANSACTION_GENERIC_ERROR;4061 reason =strbuf_detach(err, NULL);4062strbuf_addf(err,"cannot lock ref '%s':%s",4063 update->refname, reason);4064free(reason);4065goto cleanup;4066}4067if((update->flags & REF_HAVE_NEW) &&4068!(update->flags & REF_DELETING)) {4069int overwriting_symref = ((update->type & REF_ISSYMREF) &&4070(update->flags & REF_NODEREF));40714072if(!overwriting_symref &&4073!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4074/*4075 * The reference already has the desired4076 * value, so we don't need to write it.4077 */4078}else if(write_ref_to_lockfile(update->lock,4079 update->new_sha1,4080 err)) {4081char*write_err =strbuf_detach(err, NULL);40824083/*4084 * The lock was freed upon failure of4085 * write_ref_to_lockfile():4086 */4087 update->lock = NULL;4088strbuf_addf(err,4089"cannot update the ref '%s':%s",4090 update->refname, write_err);4091free(write_err);4092 ret = TRANSACTION_GENERIC_ERROR;4093goto cleanup;4094}else{4095 update->flags |= REF_NEEDS_COMMIT;4096}4097}4098if(!(update->flags & REF_NEEDS_COMMIT)) {4099/*4100 * We didn't have to write anything to the lockfile.4101 * Close it to free up the file descriptor:4102 */4103if(close_ref(update->lock)) {4104strbuf_addf(err,"Couldn't close%s.lock",4105 update->refname);4106goto cleanup;4107}4108}4109}41104111/* Perform updates first so live commits remain referenced */4112for(i =0; i < n; i++) {4113struct ref_update *update = updates[i];41144115if(update->flags & REF_NEEDS_COMMIT) {4116if(commit_ref_update(update->lock,4117 update->new_sha1, update->msg,4118 update->flags, err)) {4119/* freed by commit_ref_update(): */4120 update->lock = NULL;4121 ret = TRANSACTION_GENERIC_ERROR;4122goto cleanup;4123}else{4124/* freed by commit_ref_update(): */4125 update->lock = NULL;4126}4127}4128}41294130/* Perform deletes now that updates are safely completed */4131for(i =0; i < n; i++) {4132struct ref_update *update = updates[i];41334134if(update->flags & REF_DELETING) {4135if(delete_ref_loose(update->lock, update->type, err)) {4136 ret = TRANSACTION_GENERIC_ERROR;4137goto cleanup;4138}41394140if(!(update->flags & REF_ISPRUNING))4141string_list_append(&refs_to_delete,4142 update->lock->ref_name);4143}4144}41454146if(repack_without_refs(&refs_to_delete, err)) {4147 ret = TRANSACTION_GENERIC_ERROR;4148goto cleanup;4149}4150for_each_string_list_item(ref_to_delete, &refs_to_delete)4151unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4152clear_loose_ref_cache(&ref_cache);41534154cleanup:4155 transaction->state = REF_TRANSACTION_CLOSED;41564157for(i =0; i < n; i++)4158if(updates[i]->lock)4159unlock_ref(updates[i]->lock);4160string_list_clear(&refs_to_delete,0);4161string_list_clear(&affected_refnames,0);4162return ret;4163}41644165static intref_present(const char*refname,4166const struct object_id *oid,int flags,void*cb_data)4167{4168struct string_list *affected_refnames = cb_data;41694170returnstring_list_has_string(affected_refnames, refname);4171}41724173intinitial_ref_transaction_commit(struct ref_transaction *transaction,4174struct strbuf *err)4175{4176struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4177struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4178int ret =0, i;4179int n = transaction->nr;4180struct ref_update **updates = transaction->updates;4181struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41824183assert(err);41844185if(transaction->state != REF_TRANSACTION_OPEN)4186die("BUG: commit called for transaction that is not open");41874188/* Fail if a refname appears more than once in the transaction: */4189for(i =0; i < n; i++)4190string_list_append(&affected_refnames, updates[i]->refname);4191string_list_sort(&affected_refnames);4192if(ref_update_reject_duplicates(&affected_refnames, err)) {4193 ret = TRANSACTION_GENERIC_ERROR;4194goto cleanup;4195}41964197/*4198 * It's really undefined to call this function in an active4199 * repository or when there are existing references: we are4200 * only locking and changing packed-refs, so (1) any4201 * simultaneous processes might try to change a reference at4202 * the same time we do, and (2) any existing loose versions of4203 * the references that we are setting would have precedence4204 * over our values. But some remote helpers create the remote4205 * "HEAD" and "master" branches before calling this function,4206 * so here we really only check that none of the references4207 * that we are creating already exists.4208 */4209if(for_each_rawref(ref_present, &affected_refnames))4210die("BUG: initial ref transaction called with existing refs");42114212for(i =0; i < n; i++) {4213struct ref_update *update = updates[i];42144215if((update->flags & REF_HAVE_OLD) &&4216!is_null_sha1(update->old_sha1))4217die("BUG: initial ref transaction with old_sha1 set");4218if(verify_refname_available(update->refname,4219&affected_refnames, NULL,4220 loose_refs, err) ||4221verify_refname_available(update->refname,4222&affected_refnames, NULL,4223 packed_refs, err)) {4224 ret = TRANSACTION_NAME_CONFLICT;4225goto cleanup;4226}4227}42284229if(lock_packed_refs(0)) {4230strbuf_addf(err,"unable to lock packed-refs file:%s",4231strerror(errno));4232 ret = TRANSACTION_GENERIC_ERROR;4233goto cleanup;4234}42354236for(i =0; i < n; i++) {4237struct ref_update *update = updates[i];42384239if((update->flags & REF_HAVE_NEW) &&4240!is_null_sha1(update->new_sha1))4241add_packed_ref(update->refname, update->new_sha1);4242}42434244if(commit_packed_refs()) {4245strbuf_addf(err,"unable to commit packed-refs file:%s",4246strerror(errno));4247 ret = TRANSACTION_GENERIC_ERROR;4248goto cleanup;4249}42504251cleanup:4252 transaction->state = REF_TRANSACTION_CLOSED;4253string_list_clear(&affected_refnames,0);4254return ret;4255}42564257char*shorten_unambiguous_ref(const char*refname,int strict)4258{4259int i;4260static char**scanf_fmts;4261static int nr_rules;4262char*short_name;42634264if(!nr_rules) {4265/*4266 * Pre-generate scanf formats from ref_rev_parse_rules[].4267 * Generate a format suitable for scanf from a4268 * ref_rev_parse_rules rule by interpolating "%s" at the4269 * location of the "%.*s".4270 */4271size_t total_len =0;4272size_t offset =0;42734274/* the rule list is NULL terminated, count them first */4275for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4276/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4277 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;42784279 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);42804281 offset =0;4282for(i =0; i < nr_rules; i++) {4283assert(offset < total_len);4284 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4285 offset +=snprintf(scanf_fmts[i], total_len - offset,4286 ref_rev_parse_rules[i],2,"%s") +1;4287}4288}42894290/* bail out if there are no rules */4291if(!nr_rules)4292returnxstrdup(refname);42934294/* buffer for scanf result, at most refname must fit */4295 short_name =xstrdup(refname);42964297/* skip first rule, it will always match */4298for(i = nr_rules -1; i >0; --i) {4299int j;4300int rules_to_fail = i;4301int short_name_len;43024303if(1!=sscanf(refname, scanf_fmts[i], short_name))4304continue;43054306 short_name_len =strlen(short_name);43074308/*4309 * in strict mode, all (except the matched one) rules4310 * must fail to resolve to a valid non-ambiguous ref4311 */4312if(strict)4313 rules_to_fail = nr_rules;43144315/*4316 * check if the short name resolves to a valid ref,4317 * but use only rules prior to the matched one4318 */4319for(j =0; j < rules_to_fail; j++) {4320const char*rule = ref_rev_parse_rules[j];4321char refname[PATH_MAX];43224323/* skip matched rule */4324if(i == j)4325continue;43264327/*4328 * the short name is ambiguous, if it resolves4329 * (with this previous rule) to a valid ref4330 * read_ref() returns 0 on success4331 */4332mksnpath(refname,sizeof(refname),4333 rule, short_name_len, short_name);4334if(ref_exists(refname))4335break;4336}43374338/*4339 * short name is non-ambiguous if all previous rules4340 * haven't resolved to a valid ref4341 */4342if(j == rules_to_fail)4343return short_name;4344}43454346free(short_name);4347returnxstrdup(refname);4348}43494350static struct string_list *hide_refs;43514352intparse_hide_refs_config(const char*var,const char*value,const char*section)4353{4354if(!strcmp("transfer.hiderefs", var) ||4355/* NEEDSWORK: use parse_config_key() once both are merged */4356(starts_with(var, section) && var[strlen(section)] =='.'&&4357!strcmp(var +strlen(section),".hiderefs"))) {4358char*ref;4359int len;43604361if(!value)4362returnconfig_error_nonbool(var);4363 ref =xstrdup(value);4364 len =strlen(ref);4365while(len && ref[len -1] =='/')4366 ref[--len] ='\0';4367if(!hide_refs) {4368 hide_refs =xcalloc(1,sizeof(*hide_refs));4369 hide_refs->strdup_strings =1;4370}4371string_list_append(hide_refs, ref);4372}4373return0;4374}43754376intref_is_hidden(const char*refname)4377{4378struct string_list_item *item;43794380if(!hide_refs)4381return0;4382for_each_string_list_item(item, hide_refs) {4383int len;4384if(!starts_with(refname, item->string))4385continue;4386 len =strlen(item->string);4387if(!refname[len] || refname[len] =='/')4388return1;4389}4390return0;4391}43924393struct expire_reflog_cb {4394unsigned int flags;4395 reflog_expiry_should_prune_fn *should_prune_fn;4396void*policy_cb;4397FILE*newlog;4398unsigned char last_kept_sha1[20];4399};44004401static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4402const char*email,unsigned long timestamp,int tz,4403const char*message,void*cb_data)4404{4405struct expire_reflog_cb *cb = cb_data;4406struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;44074408if(cb->flags & EXPIRE_REFLOGS_REWRITE)4409 osha1 = cb->last_kept_sha1;44104411if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4412 message, policy_cb)) {4413if(!cb->newlog)4414printf("would prune%s", message);4415else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4416printf("prune%s", message);4417}else{4418if(cb->newlog) {4419fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4420sha1_to_hex(osha1),sha1_to_hex(nsha1),4421 email, timestamp, tz, message);4422hashcpy(cb->last_kept_sha1, nsha1);4423}4424if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4425printf("keep%s", message);4426}4427return0;4428}44294430intreflog_expire(const char*refname,const unsigned char*sha1,4431unsigned int flags,4432 reflog_expiry_prepare_fn prepare_fn,4433 reflog_expiry_should_prune_fn should_prune_fn,4434 reflog_expiry_cleanup_fn cleanup_fn,4435void*policy_cb_data)4436{4437static struct lock_file reflog_lock;4438struct expire_reflog_cb cb;4439struct ref_lock *lock;4440char*log_file;4441int status =0;4442int type;4443struct strbuf err = STRBUF_INIT;44444445memset(&cb,0,sizeof(cb));4446 cb.flags = flags;4447 cb.policy_cb = policy_cb_data;4448 cb.should_prune_fn = should_prune_fn;44494450/*4451 * The reflog file is locked by holding the lock on the4452 * reference itself, plus we might need to update the4453 * reference if --updateref was specified:4454 */4455 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4456if(!lock) {4457error("cannot lock ref '%s':%s", refname, err.buf);4458strbuf_release(&err);4459return-1;4460}4461if(!reflog_exists(refname)) {4462unlock_ref(lock);4463return0;4464}44654466 log_file =git_pathdup("logs/%s", refname);4467if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4468/*4469 * Even though holding $GIT_DIR/logs/$reflog.lock has4470 * no locking implications, we use the lock_file4471 * machinery here anyway because it does a lot of the4472 * work we need, including cleaning up if the program4473 * exits unexpectedly.4474 */4475if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4476struct strbuf err = STRBUF_INIT;4477unable_to_lock_message(log_file, errno, &err);4478error("%s", err.buf);4479strbuf_release(&err);4480goto failure;4481}4482 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4483if(!cb.newlog) {4484error("cannot fdopen%s(%s)",4485 reflog_lock.filename.buf,strerror(errno));4486goto failure;4487}4488}44894490(*prepare_fn)(refname, sha1, cb.policy_cb);4491for_each_reflog_ent(refname, expire_reflog_ent, &cb);4492(*cleanup_fn)(cb.policy_cb);44934494if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4495/*4496 * It doesn't make sense to adjust a reference pointed4497 * to by a symbolic ref based on expiring entries in4498 * the symbolic reference's reflog. Nor can we update4499 * a reference if there are no remaining reflog4500 * entries.4501 */4502int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4503!(type & REF_ISSYMREF) &&4504!is_null_sha1(cb.last_kept_sha1);45054506if(close_lock_file(&reflog_lock)) {4507 status |=error("couldn't write%s:%s", log_file,4508strerror(errno));4509}else if(update &&4510(write_in_full(lock->lk->fd,4511sha1_to_hex(cb.last_kept_sha1),40) !=40||4512write_str_in_full(lock->lk->fd,"\n") !=1||4513close_ref(lock) <0)) {4514 status |=error("couldn't write%s",4515 lock->lk->filename.buf);4516rollback_lock_file(&reflog_lock);4517}else if(commit_lock_file(&reflog_lock)) {4518 status |=error("unable to commit reflog '%s' (%s)",4519 log_file,strerror(errno));4520}else if(update &&commit_ref(lock)) {4521 status |=error("couldn't set%s", lock->ref_name);4522}4523}4524free(log_file);4525unlock_ref(lock);4526return status;45274528 failure:4529rollback_lock_file(&reflog_lock);4530free(log_file);4531unlock_ref(lock);4532return-1;4533}