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;1355struct dirent *de;1356int dirnamelen =strlen(dirname);1357struct strbuf refname;1358struct strbuf path = STRBUF_INIT;1359size_t path_baselen;13601361if(*refs->name)1362strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1363else1364strbuf_git_path(&path,"%s", dirname);1365 path_baselen = path.len;13661367 d =opendir(path.buf);1368if(!d) {1369strbuf_release(&path);1370return;1371}13721373strbuf_init(&refname, dirnamelen +257);1374strbuf_add(&refname, dirname, dirnamelen);13751376while((de =readdir(d)) != NULL) {1377unsigned char sha1[20];1378struct stat st;1379int flag;13801381if(de->d_name[0] =='.')1382continue;1383if(ends_with(de->d_name,".lock"))1384continue;1385strbuf_addstr(&refname, de->d_name);1386strbuf_addstr(&path, de->d_name);1387if(stat(path.buf, &st) <0) {1388;/* silently ignore */1389}else if(S_ISDIR(st.st_mode)) {1390strbuf_addch(&refname,'/');1391add_entry_to_dir(dir,1392create_dir_entry(refs, refname.buf,1393 refname.len,1));1394}else{1395int read_ok;13961397if(*refs->name) {1398hashclr(sha1);1399 flag =0;1400 read_ok = !resolve_gitlink_ref(refs->name,1401 refname.buf, sha1);1402}else{1403 read_ok = !read_ref_full(refname.buf,1404 RESOLVE_REF_READING,1405 sha1, &flag);1406}14071408if(!read_ok) {1409hashclr(sha1);1410 flag |= REF_ISBROKEN;1411}else if(is_null_sha1(sha1)) {1412/*1413 * It is so astronomically unlikely1414 * that NULL_SHA1 is the SHA-1 of an1415 * actual object that we consider its1416 * appearance in a loose reference1417 * file to be repo corruption1418 * (probably due to a software bug).1419 */1420 flag |= REF_ISBROKEN;1421}14221423if(check_refname_format(refname.buf,1424 REFNAME_ALLOW_ONELEVEL)) {1425if(!refname_is_safe(refname.buf))1426die("loose refname is dangerous:%s", refname.buf);1427hashclr(sha1);1428 flag |= REF_BAD_NAME | REF_ISBROKEN;1429}1430add_entry_to_dir(dir,1431create_ref_entry(refname.buf, sha1, flag,0));1432}1433strbuf_setlen(&refname, dirnamelen);1434strbuf_setlen(&path, path_baselen);1435}1436strbuf_release(&refname);1437strbuf_release(&path);1438closedir(d);1439}14401441static struct ref_dir *get_loose_refs(struct ref_cache *refs)1442{1443if(!refs->loose) {1444/*1445 * Mark the top-level directory complete because we1446 * are about to read the only subdirectory that can1447 * hold references:1448 */1449 refs->loose =create_dir_entry(refs,"",0,0);1450/*1451 * Create an incomplete entry for "refs/":1452 */1453add_entry_to_dir(get_ref_dir(refs->loose),1454create_dir_entry(refs,"refs/",5,1));1455}1456returnget_ref_dir(refs->loose);1457}14581459/* We allow "recursive" symbolic refs. Only within reason, though */1460#define MAXDEPTH 51461#define MAXREFLEN (1024)14621463/*1464 * Called by resolve_gitlink_ref_recursive() after it failed to read1465 * from the loose refs in ref_cache refs. Find <refname> in the1466 * packed-refs file for the submodule.1467 */1468static intresolve_gitlink_packed_ref(struct ref_cache *refs,1469const char*refname,unsigned char*sha1)1470{1471struct ref_entry *ref;1472struct ref_dir *dir =get_packed_refs(refs);14731474 ref =find_ref(dir, refname);1475if(ref == NULL)1476return-1;14771478hashcpy(sha1, ref->u.value.oid.hash);1479return0;1480}14811482static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1483const char*refname,unsigned char*sha1,1484int recursion)1485{1486int fd, len;1487char buffer[128], *p;1488char*path;14891490if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1491return-1;1492 path = *refs->name1493?git_pathdup_submodule(refs->name,"%s", refname)1494:git_pathdup("%s", refname);1495 fd =open(path, O_RDONLY);1496free(path);1497if(fd <0)1498returnresolve_gitlink_packed_ref(refs, refname, sha1);14991500 len =read(fd, buffer,sizeof(buffer)-1);1501close(fd);1502if(len <0)1503return-1;1504while(len &&isspace(buffer[len-1]))1505 len--;1506 buffer[len] =0;15071508/* Was it a detached head or an old-fashioned symlink? */1509if(!get_sha1_hex(buffer, sha1))1510return0;15111512/* Symref? */1513if(strncmp(buffer,"ref:",4))1514return-1;1515 p = buffer +4;1516while(isspace(*p))1517 p++;15181519returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1520}15211522intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1523{1524int len =strlen(path), retval;1525char*submodule;1526struct ref_cache *refs;15271528while(len && path[len-1] =='/')1529 len--;1530if(!len)1531return-1;1532 submodule =xstrndup(path, len);1533 refs =get_ref_cache(submodule);1534free(submodule);15351536 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1537return retval;1538}15391540/*1541 * Return the ref_entry for the given refname from the packed1542 * references. If it does not exist, return NULL.1543 */1544static struct ref_entry *get_packed_ref(const char*refname)1545{1546returnfind_ref(get_packed_refs(&ref_cache), refname);1547}15481549/*1550 * A loose ref file doesn't exist; check for a packed ref. The1551 * options are forwarded from resolve_safe_unsafe().1552 */1553static intresolve_missing_loose_ref(const char*refname,1554int resolve_flags,1555unsigned char*sha1,1556int*flags)1557{1558struct ref_entry *entry;15591560/*1561 * The loose reference file does not exist; check for a packed1562 * reference.1563 */1564 entry =get_packed_ref(refname);1565if(entry) {1566hashcpy(sha1, entry->u.value.oid.hash);1567if(flags)1568*flags |= REF_ISPACKED;1569return0;1570}1571/* The reference is not a packed reference, either. */1572if(resolve_flags & RESOLVE_REF_READING) {1573 errno = ENOENT;1574return-1;1575}else{1576hashclr(sha1);1577return0;1578}1579}15801581/* This function needs to return a meaningful errno on failure */1582static const char*resolve_ref_unsafe_1(const char*refname,1583int resolve_flags,1584unsigned char*sha1,1585int*flags,1586struct strbuf *sb_path)1587{1588int depth = MAXDEPTH;1589 ssize_t len;1590char buffer[256];1591static char refname_buffer[256];1592int bad_name =0;15931594if(flags)1595*flags =0;15961597if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1598if(flags)1599*flags |= REF_BAD_NAME;16001601if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1602!refname_is_safe(refname)) {1603 errno = EINVAL;1604return NULL;1605}1606/*1607 * dwim_ref() uses REF_ISBROKEN to distinguish between1608 * missing refs and refs that were present but invalid,1609 * to complain about the latter to stderr.1610 *1611 * We don't know whether the ref exists, so don't set1612 * REF_ISBROKEN yet.1613 */1614 bad_name =1;1615}1616for(;;) {1617const char*path;1618struct stat st;1619char*buf;1620int fd;16211622if(--depth <0) {1623 errno = ELOOP;1624return NULL;1625}16261627strbuf_reset(sb_path);1628strbuf_git_path(sb_path,"%s", refname);1629 path = sb_path->buf;16301631/*1632 * We might have to loop back here to avoid a race1633 * condition: first we lstat() the file, then we try1634 * to read it as a link or as a file. But if somebody1635 * changes the type of the file (file <-> directory1636 * <-> symlink) between the lstat() and reading, then1637 * we don't want to report that as an error but rather1638 * try again starting with the lstat().1639 */1640 stat_ref:1641if(lstat(path, &st) <0) {1642if(errno != ENOENT)1643return NULL;1644if(resolve_missing_loose_ref(refname, resolve_flags,1645 sha1, flags))1646return NULL;1647if(bad_name) {1648hashclr(sha1);1649if(flags)1650*flags |= REF_ISBROKEN;1651}1652return refname;1653}16541655/* Follow "normalized" - ie "refs/.." symlinks by hand */1656if(S_ISLNK(st.st_mode)) {1657 len =readlink(path, buffer,sizeof(buffer)-1);1658if(len <0) {1659if(errno == ENOENT || errno == EINVAL)1660/* inconsistent with lstat; retry */1661goto stat_ref;1662else1663return NULL;1664}1665 buffer[len] =0;1666if(starts_with(buffer,"refs/") &&1667!check_refname_format(buffer,0)) {1668strcpy(refname_buffer, buffer);1669 refname = refname_buffer;1670if(flags)1671*flags |= REF_ISSYMREF;1672if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1673hashclr(sha1);1674return refname;1675}1676continue;1677}1678}16791680/* Is it a directory? */1681if(S_ISDIR(st.st_mode)) {1682 errno = EISDIR;1683return NULL;1684}16851686/*1687 * Anything else, just open it and try to use it as1688 * a ref1689 */1690 fd =open(path, O_RDONLY);1691if(fd <0) {1692if(errno == ENOENT)1693/* inconsistent with lstat; retry */1694goto stat_ref;1695else1696return NULL;1697}1698 len =read_in_full(fd, buffer,sizeof(buffer)-1);1699if(len <0) {1700int save_errno = errno;1701close(fd);1702 errno = save_errno;1703return NULL;1704}1705close(fd);1706while(len &&isspace(buffer[len-1]))1707 len--;1708 buffer[len] ='\0';17091710/*1711 * Is it a symbolic ref?1712 */1713if(!starts_with(buffer,"ref:")) {1714/*1715 * Please note that FETCH_HEAD has a second1716 * line containing other data.1717 */1718if(get_sha1_hex(buffer, sha1) ||1719(buffer[40] !='\0'&& !isspace(buffer[40]))) {1720if(flags)1721*flags |= REF_ISBROKEN;1722 errno = EINVAL;1723return NULL;1724}1725if(bad_name) {1726hashclr(sha1);1727if(flags)1728*flags |= REF_ISBROKEN;1729}1730return refname;1731}1732if(flags)1733*flags |= REF_ISSYMREF;1734 buf = buffer +4;1735while(isspace(*buf))1736 buf++;1737 refname =strcpy(refname_buffer, buf);1738if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1739hashclr(sha1);1740return refname;1741}1742if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1743if(flags)1744*flags |= REF_ISBROKEN;17451746if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1747!refname_is_safe(buf)) {1748 errno = EINVAL;1749return NULL;1750}1751 bad_name =1;1752}1753}1754}17551756const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1757unsigned char*sha1,int*flags)1758{1759struct strbuf sb_path = STRBUF_INIT;1760const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1761 sha1, flags, &sb_path);1762strbuf_release(&sb_path);1763return ret;1764}17651766char*resolve_refdup(const char*refname,int resolve_flags,1767unsigned char*sha1,int*flags)1768{1769returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1770 sha1, flags));1771}17721773/* The argument to filter_refs */1774struct ref_filter {1775const char*pattern;1776 each_ref_fn *fn;1777void*cb_data;1778};17791780intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1781{1782if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1783return0;1784return-1;1785}17861787intread_ref(const char*refname,unsigned char*sha1)1788{1789returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1790}17911792intref_exists(const char*refname)1793{1794unsigned char sha1[20];1795return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1796}17971798static intfilter_refs(const char*refname,const struct object_id *oid,1799int flags,void*data)1800{1801struct ref_filter *filter = (struct ref_filter *)data;18021803if(wildmatch(filter->pattern, refname,0, NULL))1804return0;1805return filter->fn(refname, oid, flags, filter->cb_data);1806}18071808enum peel_status {1809/* object was peeled successfully: */1810 PEEL_PEELED =0,18111812/*1813 * object cannot be peeled because the named object (or an1814 * object referred to by a tag in the peel chain), does not1815 * exist.1816 */1817 PEEL_INVALID = -1,18181819/* object cannot be peeled because it is not a tag: */1820 PEEL_NON_TAG = -2,18211822/* ref_entry contains no peeled value because it is a symref: */1823 PEEL_IS_SYMREF = -3,18241825/*1826 * ref_entry cannot be peeled because it is broken (i.e., the1827 * symbolic reference cannot even be resolved to an object1828 * name):1829 */1830 PEEL_BROKEN = -41831};18321833/*1834 * Peel the named object; i.e., if the object is a tag, resolve the1835 * tag recursively until a non-tag is found. If successful, store the1836 * result to sha1 and return PEEL_PEELED. If the object is not a tag1837 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1838 * and leave sha1 unchanged.1839 */1840static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1841{1842struct object *o =lookup_unknown_object(name);18431844if(o->type == OBJ_NONE) {1845int type =sha1_object_info(name, NULL);1846if(type <0|| !object_as_type(o, type,0))1847return PEEL_INVALID;1848}18491850if(o->type != OBJ_TAG)1851return PEEL_NON_TAG;18521853 o =deref_tag_noverify(o);1854if(!o)1855return PEEL_INVALID;18561857hashcpy(sha1, o->sha1);1858return PEEL_PEELED;1859}18601861/*1862 * Peel the entry (if possible) and return its new peel_status. If1863 * repeel is true, re-peel the entry even if there is an old peeled1864 * value that is already stored in it.1865 *1866 * It is OK to call this function with a packed reference entry that1867 * might be stale and might even refer to an object that has since1868 * been garbage-collected. In such a case, if the entry has1869 * REF_KNOWS_PEELED then leave the status unchanged and return1870 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1871 */1872static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1873{1874enum peel_status status;18751876if(entry->flag & REF_KNOWS_PEELED) {1877if(repeel) {1878 entry->flag &= ~REF_KNOWS_PEELED;1879oidclr(&entry->u.value.peeled);1880}else{1881returnis_null_oid(&entry->u.value.peeled) ?1882 PEEL_NON_TAG : PEEL_PEELED;1883}1884}1885if(entry->flag & REF_ISBROKEN)1886return PEEL_BROKEN;1887if(entry->flag & REF_ISSYMREF)1888return PEEL_IS_SYMREF;18891890 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1891if(status == PEEL_PEELED || status == PEEL_NON_TAG)1892 entry->flag |= REF_KNOWS_PEELED;1893return status;1894}18951896intpeel_ref(const char*refname,unsigned char*sha1)1897{1898int flag;1899unsigned char base[20];19001901if(current_ref && (current_ref->name == refname1902|| !strcmp(current_ref->name, refname))) {1903if(peel_entry(current_ref,0))1904return-1;1905hashcpy(sha1, current_ref->u.value.peeled.hash);1906return0;1907}19081909if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1910return-1;19111912/*1913 * If the reference is packed, read its ref_entry from the1914 * cache in the hope that we already know its peeled value.1915 * We only try this optimization on packed references because1916 * (a) forcing the filling of the loose reference cache could1917 * be expensive and (b) loose references anyway usually do not1918 * have REF_KNOWS_PEELED.1919 */1920if(flag & REF_ISPACKED) {1921struct ref_entry *r =get_packed_ref(refname);1922if(r) {1923if(peel_entry(r,0))1924return-1;1925hashcpy(sha1, r->u.value.peeled.hash);1926return0;1927}1928}19291930returnpeel_object(base, sha1);1931}19321933struct warn_if_dangling_data {1934FILE*fp;1935const char*refname;1936const struct string_list *refnames;1937const char*msg_fmt;1938};19391940static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1941int flags,void*cb_data)1942{1943struct warn_if_dangling_data *d = cb_data;1944const char*resolves_to;1945struct object_id junk;19461947if(!(flags & REF_ISSYMREF))1948return0;19491950 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1951if(!resolves_to1952|| (d->refname1953?strcmp(resolves_to, d->refname)1954: !string_list_has_string(d->refnames, resolves_to))) {1955return0;1956}19571958fprintf(d->fp, d->msg_fmt, refname);1959fputc('\n', d->fp);1960return0;1961}19621963voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1964{1965struct warn_if_dangling_data data;19661967 data.fp = fp;1968 data.refname = refname;1969 data.refnames = NULL;1970 data.msg_fmt = msg_fmt;1971for_each_rawref(warn_if_dangling_symref, &data);1972}19731974voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1975{1976struct warn_if_dangling_data data;19771978 data.fp = fp;1979 data.refname = NULL;1980 data.refnames = refnames;1981 data.msg_fmt = msg_fmt;1982for_each_rawref(warn_if_dangling_symref, &data);1983}19841985/*1986 * Call fn for each reference in the specified ref_cache, omitting1987 * references not in the containing_dir of base. fn is called for all1988 * references, including broken ones. If fn ever returns a non-zero1989 * value, stop the iteration and return that value; otherwise, return1990 * 0.1991 */1992static intdo_for_each_entry(struct ref_cache *refs,const char*base,1993 each_ref_entry_fn fn,void*cb_data)1994{1995struct packed_ref_cache *packed_ref_cache;1996struct ref_dir *loose_dir;1997struct ref_dir *packed_dir;1998int retval =0;19992000/*2001 * We must make sure that all loose refs are read before accessing the2002 * packed-refs file; this avoids a race condition in which loose refs2003 * are migrated to the packed-refs file by a simultaneous process, but2004 * our in-memory view is from before the migration. get_packed_ref_cache()2005 * takes care of making sure our view is up to date with what is on2006 * disk.2007 */2008 loose_dir =get_loose_refs(refs);2009if(base && *base) {2010 loose_dir =find_containing_dir(loose_dir, base,0);2011}2012if(loose_dir)2013prime_ref_dir(loose_dir);20142015 packed_ref_cache =get_packed_ref_cache(refs);2016acquire_packed_ref_cache(packed_ref_cache);2017 packed_dir =get_packed_ref_dir(packed_ref_cache);2018if(base && *base) {2019 packed_dir =find_containing_dir(packed_dir, base,0);2020}20212022if(packed_dir && loose_dir) {2023sort_ref_dir(packed_dir);2024sort_ref_dir(loose_dir);2025 retval =do_for_each_entry_in_dirs(2026 packed_dir, loose_dir, fn, cb_data);2027}else if(packed_dir) {2028sort_ref_dir(packed_dir);2029 retval =do_for_each_entry_in_dir(2030 packed_dir,0, fn, cb_data);2031}else if(loose_dir) {2032sort_ref_dir(loose_dir);2033 retval =do_for_each_entry_in_dir(2034 loose_dir,0, fn, cb_data);2035}20362037release_packed_ref_cache(packed_ref_cache);2038return retval;2039}20402041/*2042 * Call fn for each reference in the specified ref_cache for which the2043 * refname begins with base. If trim is non-zero, then trim that many2044 * characters off the beginning of each refname before passing the2045 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2046 * broken references in the iteration. If fn ever returns a non-zero2047 * value, stop the iteration and return that value; otherwise, return2048 * 0.2049 */2050static intdo_for_each_ref(struct ref_cache *refs,const char*base,2051 each_ref_fn fn,int trim,int flags,void*cb_data)2052{2053struct ref_entry_cb data;2054 data.base = base;2055 data.trim = trim;2056 data.flags = flags;2057 data.fn = fn;2058 data.cb_data = cb_data;20592060if(ref_paranoia <0)2061 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2062if(ref_paranoia)2063 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20642065returndo_for_each_entry(refs, base, do_one_ref, &data);2066}20672068static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2069{2070struct object_id oid;2071int flag;20722073if(submodule) {2074if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2075returnfn("HEAD", &oid,0, cb_data);20762077return0;2078}20792080if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2081returnfn("HEAD", &oid, flag, cb_data);20822083return0;2084}20852086inthead_ref(each_ref_fn fn,void*cb_data)2087{2088returndo_head_ref(NULL, fn, cb_data);2089}20902091inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2092{2093returndo_head_ref(submodule, fn, cb_data);2094}20952096intfor_each_ref(each_ref_fn fn,void*cb_data)2097{2098returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2099}21002101intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2102{2103returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2104}21052106intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2107{2108returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2109}21102111intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2112 each_ref_fn fn,void*cb_data)2113{2114returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2115}21162117intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2118{2119returnfor_each_ref_in("refs/tags/", fn, cb_data);2120}21212122intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2123{2124returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2125}21262127intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2128{2129returnfor_each_ref_in("refs/heads/", fn, cb_data);2130}21312132intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2133{2134returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2135}21362137intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2138{2139returnfor_each_ref_in("refs/remotes/", fn, cb_data);2140}21412142intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2143{2144returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2145}21462147intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2148{2149returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2150strlen(git_replace_ref_base),0, cb_data);2151}21522153inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2154{2155struct strbuf buf = STRBUF_INIT;2156int ret =0;2157struct object_id oid;2158int flag;21592160strbuf_addf(&buf,"%sHEAD",get_git_namespace());2161if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2162 ret =fn(buf.buf, &oid, flag, cb_data);2163strbuf_release(&buf);21642165return ret;2166}21672168intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2169{2170struct strbuf buf = STRBUF_INIT;2171int ret;2172strbuf_addf(&buf,"%srefs/",get_git_namespace());2173 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2174strbuf_release(&buf);2175return ret;2176}21772178intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2179const char*prefix,void*cb_data)2180{2181struct strbuf real_pattern = STRBUF_INIT;2182struct ref_filter filter;2183int ret;21842185if(!prefix && !starts_with(pattern,"refs/"))2186strbuf_addstr(&real_pattern,"refs/");2187else if(prefix)2188strbuf_addstr(&real_pattern, prefix);2189strbuf_addstr(&real_pattern, pattern);21902191if(!has_glob_specials(pattern)) {2192/* Append implied '/' '*' if not present. */2193if(real_pattern.buf[real_pattern.len -1] !='/')2194strbuf_addch(&real_pattern,'/');2195/* No need to check for '*', there is none. */2196strbuf_addch(&real_pattern,'*');2197}21982199 filter.pattern = real_pattern.buf;2200 filter.fn = fn;2201 filter.cb_data = cb_data;2202 ret =for_each_ref(filter_refs, &filter);22032204strbuf_release(&real_pattern);2205return ret;2206}22072208intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2209{2210returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2211}22122213intfor_each_rawref(each_ref_fn fn,void*cb_data)2214{2215returndo_for_each_ref(&ref_cache,"", fn,0,2216 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2217}22182219const char*prettify_refname(const char*name)2220{2221return name + (2222starts_with(name,"refs/heads/") ?11:2223starts_with(name,"refs/tags/") ?10:2224starts_with(name,"refs/remotes/") ?13:22250);2226}22272228static const char*ref_rev_parse_rules[] = {2229"%.*s",2230"refs/%.*s",2231"refs/tags/%.*s",2232"refs/heads/%.*s",2233"refs/remotes/%.*s",2234"refs/remotes/%.*s/HEAD",2235 NULL2236};22372238intrefname_match(const char*abbrev_name,const char*full_name)2239{2240const char**p;2241const int abbrev_name_len =strlen(abbrev_name);22422243for(p = ref_rev_parse_rules; *p; p++) {2244if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2245return1;2246}2247}22482249return0;2250}22512252static voidunlock_ref(struct ref_lock *lock)2253{2254/* Do not free lock->lk -- atexit() still looks at them */2255if(lock->lk)2256rollback_lock_file(lock->lk);2257free(lock->ref_name);2258free(lock->orig_ref_name);2259free(lock);2260}22612262/*2263 * Verify that the reference locked by lock has the value old_sha1.2264 * Fail if the reference doesn't exist and mustexist is set. Return 02265 * on success. On error, write an error message to err, set errno, and2266 * return a negative value.2267 */2268static intverify_lock(struct ref_lock *lock,2269const unsigned char*old_sha1,int mustexist,2270struct strbuf *err)2271{2272assert(err);22732274if(read_ref_full(lock->ref_name,2275 mustexist ? RESOLVE_REF_READING :0,2276 lock->old_oid.hash, NULL)) {2277int save_errno = errno;2278strbuf_addf(err,"can't verify ref%s", lock->ref_name);2279 errno = save_errno;2280return-1;2281}2282if(hashcmp(lock->old_oid.hash, old_sha1)) {2283strbuf_addf(err,"ref%sis at%sbut expected%s",2284 lock->ref_name,2285sha1_to_hex(lock->old_oid.hash),2286sha1_to_hex(old_sha1));2287 errno = EBUSY;2288return-1;2289}2290return0;2291}22922293static intremove_empty_directories(const char*file)2294{2295/* we want to create a file but there is a directory there;2296 * if that is an empty directory (or a directory that contains2297 * only empty directories), remove them.2298 */2299struct strbuf path;2300int result, save_errno;23012302strbuf_init(&path,20);2303strbuf_addstr(&path, file);23042305 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2306 save_errno = errno;23072308strbuf_release(&path);2309 errno = save_errno;23102311return result;2312}23132314/*2315 * *string and *len will only be substituted, and *string returned (for2316 * later free()ing) if the string passed in is a magic short-hand form2317 * to name a branch.2318 */2319static char*substitute_branch_name(const char**string,int*len)2320{2321struct strbuf buf = STRBUF_INIT;2322int ret =interpret_branch_name(*string, *len, &buf);23232324if(ret == *len) {2325size_t size;2326*string =strbuf_detach(&buf, &size);2327*len = size;2328return(char*)*string;2329}23302331return NULL;2332}23332334intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2335{2336char*last_branch =substitute_branch_name(&str, &len);2337const char**p, *r;2338int refs_found =0;23392340*ref = NULL;2341for(p = ref_rev_parse_rules; *p; p++) {2342char fullref[PATH_MAX];2343unsigned char sha1_from_ref[20];2344unsigned char*this_result;2345int flag;23462347 this_result = refs_found ? sha1_from_ref : sha1;2348mksnpath(fullref,sizeof(fullref), *p, len, str);2349 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2350 this_result, &flag);2351if(r) {2352if(!refs_found++)2353*ref =xstrdup(r);2354if(!warn_ambiguous_refs)2355break;2356}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2357warning("ignoring dangling symref%s.", fullref);2358}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2359warning("ignoring broken ref%s.", fullref);2360}2361}2362free(last_branch);2363return refs_found;2364}23652366intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2367{2368char*last_branch =substitute_branch_name(&str, &len);2369const char**p;2370int logs_found =0;23712372*log = NULL;2373for(p = ref_rev_parse_rules; *p; p++) {2374unsigned char hash[20];2375char path[PATH_MAX];2376const char*ref, *it;23772378mksnpath(path,sizeof(path), *p, len, str);2379 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2380 hash, NULL);2381if(!ref)2382continue;2383if(reflog_exists(path))2384 it = path;2385else if(strcmp(ref, path) &&reflog_exists(ref))2386 it = ref;2387else2388continue;2389if(!logs_found++) {2390*log =xstrdup(it);2391hashcpy(sha1, hash);2392}2393if(!warn_ambiguous_refs)2394break;2395}2396free(last_branch);2397return logs_found;2398}23992400/*2401 * Locks a ref returning the lock on success and NULL on failure.2402 * On failure errno is set to something meaningful.2403 */2404static struct ref_lock *lock_ref_sha1_basic(const char*refname,2405const unsigned char*old_sha1,2406const struct string_list *extras,2407const struct string_list *skip,2408unsigned int flags,int*type_p,2409struct strbuf *err)2410{2411const char*ref_file;2412const char*orig_refname = refname;2413struct ref_lock *lock;2414int last_errno =0;2415int type, lflags;2416int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2417int resolve_flags =0;2418int attempts_remaining =3;24192420assert(err);24212422 lock =xcalloc(1,sizeof(struct ref_lock));24232424if(mustexist)2425 resolve_flags |= RESOLVE_REF_READING;2426if(flags & REF_DELETING) {2427 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2428if(flags & REF_NODEREF)2429 resolve_flags |= RESOLVE_REF_NO_RECURSE;2430}24312432 refname =resolve_ref_unsafe(refname, resolve_flags,2433 lock->old_oid.hash, &type);2434if(!refname && errno == EISDIR) {2435/* we are trying to lock foo but we used to2436 * have foo/bar which now does not exist;2437 * it is normal for the empty directory 'foo'2438 * to remain.2439 */2440 ref_file =git_path("%s", orig_refname);2441if(remove_empty_directories(ref_file)) {2442 last_errno = errno;24432444if(!verify_refname_available(orig_refname, extras, skip,2445get_loose_refs(&ref_cache), err))2446strbuf_addf(err,"there are still refs under '%s'",2447 orig_refname);24482449goto error_return;2450}2451 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2452 lock->old_oid.hash, &type);2453}2454if(type_p)2455*type_p = type;2456if(!refname) {2457 last_errno = errno;2458if(last_errno != ENOTDIR ||2459!verify_refname_available(orig_refname, extras, skip,2460get_loose_refs(&ref_cache), err))2461strbuf_addf(err,"unable to resolve reference%s:%s",2462 orig_refname,strerror(last_errno));24632464goto error_return;2465}2466/*2467 * If the ref did not exist and we are creating it, make sure2468 * there is no existing packed ref whose name begins with our2469 * refname, nor a packed ref whose name is a proper prefix of2470 * our refname.2471 */2472if(is_null_oid(&lock->old_oid) &&2473verify_refname_available(refname, extras, skip,2474get_packed_refs(&ref_cache), err)) {2475 last_errno = ENOTDIR;2476goto error_return;2477}24782479 lock->lk =xcalloc(1,sizeof(struct lock_file));24802481 lflags =0;2482if(flags & REF_NODEREF) {2483 refname = orig_refname;2484 lflags |= LOCK_NO_DEREF;2485}2486 lock->ref_name =xstrdup(refname);2487 lock->orig_ref_name =xstrdup(orig_refname);2488 ref_file =git_path("%s", refname);24892490 retry:2491switch(safe_create_leading_directories_const(ref_file)) {2492case SCLD_OK:2493break;/* success */2494case SCLD_VANISHED:2495if(--attempts_remaining >0)2496goto retry;2497/* fall through */2498default:2499 last_errno = errno;2500strbuf_addf(err,"unable to create directory for%s", ref_file);2501goto error_return;2502}25032504if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2505 last_errno = errno;2506if(errno == ENOENT && --attempts_remaining >0)2507/*2508 * Maybe somebody just deleted one of the2509 * directories leading to ref_file. Try2510 * again:2511 */2512goto retry;2513else{2514unable_to_lock_message(ref_file, errno, err);2515goto error_return;2516}2517}2518if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2519 last_errno = errno;2520goto error_return;2521}2522return lock;25232524 error_return:2525unlock_ref(lock);2526 errno = last_errno;2527return NULL;2528}25292530/*2531 * Write an entry to the packed-refs file for the specified refname.2532 * If peeled is non-NULL, write it as the entry's peeled value.2533 */2534static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2535unsigned char*peeled)2536{2537fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2538if(peeled)2539fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2540}25412542/*2543 * An each_ref_entry_fn that writes the entry to a packed-refs file.2544 */2545static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2546{2547enum peel_status peel_status =peel_entry(entry,0);25482549if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2550error("internal error:%sis not a valid packed reference!",2551 entry->name);2552write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2553 peel_status == PEEL_PEELED ?2554 entry->u.value.peeled.hash : NULL);2555return0;2556}25572558/*2559 * Lock the packed-refs file for writing. Flags is passed to2560 * hold_lock_file_for_update(). Return 0 on success. On errors, set2561 * errno appropriately and return a nonzero value.2562 */2563static intlock_packed_refs(int flags)2564{2565static int timeout_configured =0;2566static int timeout_value =1000;25672568struct packed_ref_cache *packed_ref_cache;25692570if(!timeout_configured) {2571git_config_get_int("core.packedrefstimeout", &timeout_value);2572 timeout_configured =1;2573}25742575if(hold_lock_file_for_update_timeout(2576&packlock,git_path("packed-refs"),2577 flags, timeout_value) <0)2578return-1;2579/*2580 * Get the current packed-refs while holding the lock. If the2581 * packed-refs file has been modified since we last read it,2582 * this will automatically invalidate the cache and re-read2583 * the packed-refs file.2584 */2585 packed_ref_cache =get_packed_ref_cache(&ref_cache);2586 packed_ref_cache->lock = &packlock;2587/* Increment the reference count to prevent it from being freed: */2588acquire_packed_ref_cache(packed_ref_cache);2589return0;2590}25912592/*2593 * Write the current version of the packed refs cache from memory to2594 * disk. The packed-refs file must already be locked for writing (see2595 * lock_packed_refs()). Return zero on success. On errors, set errno2596 * and return a nonzero value2597 */2598static intcommit_packed_refs(void)2599{2600struct packed_ref_cache *packed_ref_cache =2601get_packed_ref_cache(&ref_cache);2602int error =0;2603int save_errno =0;2604FILE*out;26052606if(!packed_ref_cache->lock)2607die("internal error: packed-refs not locked");26082609 out =fdopen_lock_file(packed_ref_cache->lock,"w");2610if(!out)2611die_errno("unable to fdopen packed-refs descriptor");26122613fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2614do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26150, write_packed_entry_fn, out);26162617if(commit_lock_file(packed_ref_cache->lock)) {2618 save_errno = errno;2619 error = -1;2620}2621 packed_ref_cache->lock = NULL;2622release_packed_ref_cache(packed_ref_cache);2623 errno = save_errno;2624return error;2625}26262627/*2628 * Rollback the lockfile for the packed-refs file, and discard the2629 * in-memory packed reference cache. (The packed-refs file will be2630 * read anew if it is needed again after this function is called.)2631 */2632static voidrollback_packed_refs(void)2633{2634struct packed_ref_cache *packed_ref_cache =2635get_packed_ref_cache(&ref_cache);26362637if(!packed_ref_cache->lock)2638die("internal error: packed-refs not locked");2639rollback_lock_file(packed_ref_cache->lock);2640 packed_ref_cache->lock = NULL;2641release_packed_ref_cache(packed_ref_cache);2642clear_packed_ref_cache(&ref_cache);2643}26442645struct ref_to_prune {2646struct ref_to_prune *next;2647unsigned char sha1[20];2648char name[FLEX_ARRAY];2649};26502651struct pack_refs_cb_data {2652unsigned int flags;2653struct ref_dir *packed_refs;2654struct ref_to_prune *ref_to_prune;2655};26562657/*2658 * An each_ref_entry_fn that is run over loose references only. If2659 * the loose reference can be packed, add an entry in the packed ref2660 * cache. If the reference should be pruned, also add it to2661 * ref_to_prune in the pack_refs_cb_data.2662 */2663static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2664{2665struct pack_refs_cb_data *cb = cb_data;2666enum peel_status peel_status;2667struct ref_entry *packed_entry;2668int is_tag_ref =starts_with(entry->name,"refs/tags/");26692670/* ALWAYS pack tags */2671if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2672return0;26732674/* Do not pack symbolic or broken refs: */2675if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2676return0;26772678/* Add a packed ref cache entry equivalent to the loose entry. */2679 peel_status =peel_entry(entry,1);2680if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2681die("internal error peeling reference%s(%s)",2682 entry->name,oid_to_hex(&entry->u.value.oid));2683 packed_entry =find_ref(cb->packed_refs, entry->name);2684if(packed_entry) {2685/* Overwrite existing packed entry with info from loose entry */2686 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2687oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2688}else{2689 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2690 REF_ISPACKED | REF_KNOWS_PEELED,0);2691add_ref(cb->packed_refs, packed_entry);2692}2693oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26942695/* Schedule the loose reference for pruning if requested. */2696if((cb->flags & PACK_REFS_PRUNE)) {2697int namelen =strlen(entry->name) +1;2698struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2699hashcpy(n->sha1, entry->u.value.oid.hash);2700strcpy(n->name, entry->name);2701 n->next = cb->ref_to_prune;2702 cb->ref_to_prune = n;2703}2704return0;2705}27062707/*2708 * Remove empty parents, but spare refs/ and immediate subdirs.2709 * Note: munges *name.2710 */2711static voidtry_remove_empty_parents(char*name)2712{2713char*p, *q;2714int i;2715 p = name;2716for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2717while(*p && *p !='/')2718 p++;2719/* tolerate duplicate slashes; see check_refname_format() */2720while(*p =='/')2721 p++;2722}2723for(q = p; *q; q++)2724;2725while(1) {2726while(q > p && *q !='/')2727 q--;2728while(q > p && *(q-1) =='/')2729 q--;2730if(q == p)2731break;2732*q ='\0';2733if(rmdir(git_path("%s", name)))2734break;2735}2736}27372738/* make sure nobody touched the ref, and unlink */2739static voidprune_ref(struct ref_to_prune *r)2740{2741struct ref_transaction *transaction;2742struct strbuf err = STRBUF_INIT;27432744if(check_refname_format(r->name,0))2745return;27462747 transaction =ref_transaction_begin(&err);2748if(!transaction ||2749ref_transaction_delete(transaction, r->name, r->sha1,2750 REF_ISPRUNING, NULL, &err) ||2751ref_transaction_commit(transaction, &err)) {2752ref_transaction_free(transaction);2753error("%s", err.buf);2754strbuf_release(&err);2755return;2756}2757ref_transaction_free(transaction);2758strbuf_release(&err);2759try_remove_empty_parents(r->name);2760}27612762static voidprune_refs(struct ref_to_prune *r)2763{2764while(r) {2765prune_ref(r);2766 r = r->next;2767}2768}27692770intpack_refs(unsigned int flags)2771{2772struct pack_refs_cb_data cbdata;27732774memset(&cbdata,0,sizeof(cbdata));2775 cbdata.flags = flags;27762777lock_packed_refs(LOCK_DIE_ON_ERROR);2778 cbdata.packed_refs =get_packed_refs(&ref_cache);27792780do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2781 pack_if_possible_fn, &cbdata);27822783if(commit_packed_refs())2784die_errno("unable to overwrite old ref-pack file");27852786prune_refs(cbdata.ref_to_prune);2787return0;2788}27892790/*2791 * Rewrite the packed-refs file, omitting any refs listed in2792 * 'refnames'. On error, leave packed-refs unchanged, write an error2793 * message to 'err', and return a nonzero value.2794 *2795 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2796 */2797static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2798{2799struct ref_dir *packed;2800struct string_list_item *refname;2801int ret, needs_repacking =0, removed =0;28022803assert(err);28042805/* Look for a packed ref */2806for_each_string_list_item(refname, refnames) {2807if(get_packed_ref(refname->string)) {2808 needs_repacking =1;2809break;2810}2811}28122813/* Avoid locking if we have nothing to do */2814if(!needs_repacking)2815return0;/* no refname exists in packed refs */28162817if(lock_packed_refs(0)) {2818unable_to_lock_message(git_path("packed-refs"), errno, err);2819return-1;2820}2821 packed =get_packed_refs(&ref_cache);28222823/* Remove refnames from the cache */2824for_each_string_list_item(refname, refnames)2825if(remove_entry(packed, refname->string) != -1)2826 removed =1;2827if(!removed) {2828/*2829 * All packed entries disappeared while we were2830 * acquiring the lock.2831 */2832rollback_packed_refs();2833return0;2834}28352836/* Write what remains */2837 ret =commit_packed_refs();2838if(ret)2839strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2840strerror(errno));2841return ret;2842}28432844static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2845{2846assert(err);28472848if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2849/*2850 * loose. The loose file name is the same as the2851 * lockfile name, minus ".lock":2852 */2853char*loose_filename =get_locked_file_path(lock->lk);2854int res =unlink_or_msg(loose_filename, err);2855free(loose_filename);2856if(res)2857return1;2858}2859return0;2860}28612862intdelete_ref(const char*refname,const unsigned char*old_sha1,2863unsigned int flags)2864{2865struct ref_transaction *transaction;2866struct strbuf err = STRBUF_INIT;28672868 transaction =ref_transaction_begin(&err);2869if(!transaction ||2870ref_transaction_delete(transaction, refname, old_sha1,2871 flags, NULL, &err) ||2872ref_transaction_commit(transaction, &err)) {2873error("%s", err.buf);2874ref_transaction_free(transaction);2875strbuf_release(&err);2876return1;2877}2878ref_transaction_free(transaction);2879strbuf_release(&err);2880return0;2881}28822883intdelete_refs(struct string_list *refnames)2884{2885struct strbuf err = STRBUF_INIT;2886int i, result =0;28872888if(!refnames->nr)2889return0;28902891 result =repack_without_refs(refnames, &err);2892if(result) {2893/*2894 * If we failed to rewrite the packed-refs file, then2895 * it is unsafe to try to remove loose refs, because2896 * doing so might expose an obsolete packed value for2897 * a reference that might even point at an object that2898 * has been garbage collected.2899 */2900if(refnames->nr ==1)2901error(_("could not delete reference%s:%s"),2902 refnames->items[0].string, err.buf);2903else2904error(_("could not delete references:%s"), err.buf);29052906goto out;2907}29082909for(i =0; i < refnames->nr; i++) {2910const char*refname = refnames->items[i].string;29112912if(delete_ref(refname, NULL,0))2913 result |=error(_("could not remove reference%s"), refname);2914}29152916out:2917strbuf_release(&err);2918return result;2919}29202921/*2922 * People using contrib's git-new-workdir have .git/logs/refs ->2923 * /some/other/path/.git/logs/refs, and that may live on another device.2924 *2925 * IOW, to avoid cross device rename errors, the temporary renamed log must2926 * live into logs/refs.2927 */2928#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"29292930static intrename_tmp_log(const char*newrefname)2931{2932int attempts_remaining =4;29332934 retry:2935switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2936case SCLD_OK:2937break;/* success */2938case SCLD_VANISHED:2939if(--attempts_remaining >0)2940goto retry;2941/* fall through */2942default:2943error("unable to create directory for%s", newrefname);2944return-1;2945}29462947if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2948if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2949/*2950 * rename(a, b) when b is an existing2951 * directory ought to result in ISDIR, but2952 * Solaris 5.8 gives ENOTDIR. Sheesh.2953 */2954if(remove_empty_directories(git_path("logs/%s", newrefname))) {2955error("Directory not empty: logs/%s", newrefname);2956return-1;2957}2958goto retry;2959}else if(errno == ENOENT && --attempts_remaining >0) {2960/*2961 * Maybe another process just deleted one of2962 * the directories in the path to newrefname.2963 * Try again from the beginning.2964 */2965goto retry;2966}else{2967error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2968 newrefname,strerror(errno));2969return-1;2970}2971}2972return0;2973}29742975static intrename_ref_available(const char*oldname,const char*newname)2976{2977struct string_list skip = STRING_LIST_INIT_NODUP;2978struct strbuf err = STRBUF_INIT;2979int ret;29802981string_list_insert(&skip, oldname);2982 ret = !verify_refname_available(newname, NULL, &skip,2983get_packed_refs(&ref_cache), &err)2984&& !verify_refname_available(newname, NULL, &skip,2985get_loose_refs(&ref_cache), &err);2986if(!ret)2987error("%s", err.buf);29882989string_list_clear(&skip,0);2990strbuf_release(&err);2991return ret;2992}29932994static intwrite_ref_to_lockfile(struct ref_lock *lock,2995const unsigned char*sha1,struct strbuf *err);2996static intcommit_ref_update(struct ref_lock *lock,2997const unsigned char*sha1,const char*logmsg,2998int flags,struct strbuf *err);29993000intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3001{3002unsigned char sha1[20], orig_sha1[20];3003int flag =0, logmoved =0;3004struct ref_lock *lock;3005struct stat loginfo;3006int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3007const char*symref = NULL;3008struct strbuf err = STRBUF_INIT;30093010if(log &&S_ISLNK(loginfo.st_mode))3011returnerror("reflog for%sis a symlink", oldrefname);30123013 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3014 orig_sha1, &flag);3015if(flag & REF_ISSYMREF)3016returnerror("refname%sis a symbolic ref, renaming it is not supported",3017 oldrefname);3018if(!symref)3019returnerror("refname%snot found", oldrefname);30203021if(!rename_ref_available(oldrefname, newrefname))3022return1;30233024if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3025returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3026 oldrefname,strerror(errno));30273028if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3029error("unable to delete old%s", oldrefname);3030goto rollback;3031}30323033if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3034delete_ref(newrefname, sha1, REF_NODEREF)) {3035if(errno==EISDIR) {3036if(remove_empty_directories(git_path("%s", newrefname))) {3037error("Directory not empty:%s", newrefname);3038goto rollback;3039}3040}else{3041error("unable to delete existing%s", newrefname);3042goto rollback;3043}3044}30453046if(log &&rename_tmp_log(newrefname))3047goto rollback;30483049 logmoved = log;30503051 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3052if(!lock) {3053error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3054strbuf_release(&err);3055goto rollback;3056}3057hashcpy(lock->old_oid.hash, orig_sha1);30583059if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3060commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3061error("unable to write current sha1 into%s:%s", newrefname, err.buf);3062strbuf_release(&err);3063goto rollback;3064}30653066return0;30673068 rollback:3069 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3070if(!lock) {3071error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3072strbuf_release(&err);3073goto rollbacklog;3074}30753076 flag = log_all_ref_updates;3077 log_all_ref_updates =0;3078if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3079commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3080error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3081strbuf_release(&err);3082}3083 log_all_ref_updates = flag;30843085 rollbacklog:3086if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3087error("unable to restore logfile%sfrom%s:%s",3088 oldrefname, newrefname,strerror(errno));3089if(!logmoved && log &&3090rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3091error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3092 oldrefname,strerror(errno));30933094return1;3095}30963097static intclose_ref(struct ref_lock *lock)3098{3099if(close_lock_file(lock->lk))3100return-1;3101return0;3102}31033104static intcommit_ref(struct ref_lock *lock)3105{3106if(commit_lock_file(lock->lk))3107return-1;3108return0;3109}31103111/*3112 * copy the reflog message msg to buf, which has been allocated sufficiently3113 * large, while cleaning up the whitespaces. Especially, convert LF to space,3114 * because reflog file is one line per entry.3115 */3116static intcopy_msg(char*buf,const char*msg)3117{3118char*cp = buf;3119char c;3120int wasspace =1;31213122*cp++ ='\t';3123while((c = *msg++)) {3124if(wasspace &&isspace(c))3125continue;3126 wasspace =isspace(c);3127if(wasspace)3128 c =' ';3129*cp++ = c;3130}3131while(buf < cp &&isspace(cp[-1]))3132 cp--;3133*cp++ ='\n';3134return cp - buf;3135}31363137static intshould_autocreate_reflog(const char*refname)3138{3139if(!log_all_ref_updates)3140return0;3141returnstarts_with(refname,"refs/heads/") ||3142starts_with(refname,"refs/remotes/") ||3143starts_with(refname,"refs/notes/") ||3144!strcmp(refname,"HEAD");3145}31463147/*3148 * Create a reflog for a ref. If force_create = 0, the reflog will3149 * only be created for certain refs (those for which3150 * should_autocreate_reflog returns non-zero. Otherwise, create it3151 * regardless of the ref name. Fill in *err and return -1 on failure.3152 */3153static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3154{3155int logfd, oflags = O_APPEND | O_WRONLY;31563157strbuf_git_path(logfile,"logs/%s", refname);3158if(force_create ||should_autocreate_reflog(refname)) {3159if(safe_create_leading_directories(logfile->buf) <0) {3160strbuf_addf(err,"unable to create directory for%s: "3161"%s", logfile->buf,strerror(errno));3162return-1;3163}3164 oflags |= O_CREAT;3165}31663167 logfd =open(logfile->buf, oflags,0666);3168if(logfd <0) {3169if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3170return0;31713172if(errno == EISDIR) {3173if(remove_empty_directories(logfile->buf)) {3174strbuf_addf(err,"There are still logs under "3175"'%s'", logfile->buf);3176return-1;3177}3178 logfd =open(logfile->buf, oflags,0666);3179}31803181if(logfd <0) {3182strbuf_addf(err,"unable to append to%s:%s",3183 logfile->buf,strerror(errno));3184return-1;3185}3186}31873188adjust_shared_perm(logfile->buf);3189close(logfd);3190return0;3191}319231933194intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3195{3196int ret;3197struct strbuf sb = STRBUF_INIT;31983199 ret =log_ref_setup(refname, &sb, err, force_create);3200strbuf_release(&sb);3201return ret;3202}32033204static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3205const unsigned char*new_sha1,3206const char*committer,const char*msg)3207{3208int msglen, written;3209unsigned maxlen, len;3210char*logrec;32113212 msglen = msg ?strlen(msg) :0;3213 maxlen =strlen(committer) + msglen +100;3214 logrec =xmalloc(maxlen);3215 len =sprintf(logrec,"%s %s %s\n",3216sha1_to_hex(old_sha1),3217sha1_to_hex(new_sha1),3218 committer);3219if(msglen)3220 len +=copy_msg(logrec + len -1, msg) -1;32213222 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3223free(logrec);3224if(written != len)3225return-1;32263227return0;3228}32293230static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3231const unsigned char*new_sha1,const char*msg,3232struct strbuf *logfile,int flags,3233struct strbuf *err)3234{3235int logfd, result, oflags = O_APPEND | O_WRONLY;32363237if(log_all_ref_updates <0)3238 log_all_ref_updates = !is_bare_repository();32393240 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);32413242if(result)3243return result;32443245 logfd =open(logfile->buf, oflags);3246if(logfd <0)3247return0;3248 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3249git_committer_info(0), msg);3250if(result) {3251strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3252strerror(errno));3253close(logfd);3254return-1;3255}3256if(close(logfd)) {3257strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3258strerror(errno));3259return-1;3260}3261return0;3262}32633264static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3265const unsigned char*new_sha1,const char*msg,3266int flags,struct strbuf *err)3267{3268struct strbuf sb = STRBUF_INIT;3269int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3270 err);3271strbuf_release(&sb);3272return ret;3273}32743275intis_branch(const char*refname)3276{3277return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3278}32793280/*3281 * Write sha1 into the open lockfile, then close the lockfile. On3282 * errors, rollback the lockfile, fill in *err and3283 * return -1.3284 */3285static intwrite_ref_to_lockfile(struct ref_lock *lock,3286const unsigned char*sha1,struct strbuf *err)3287{3288static char term ='\n';3289struct object *o;32903291 o =parse_object(sha1);3292if(!o) {3293strbuf_addf(err,3294"Trying to write ref%swith nonexistent object%s",3295 lock->ref_name,sha1_to_hex(sha1));3296unlock_ref(lock);3297return-1;3298}3299if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3300strbuf_addf(err,3301"Trying to write non-commit object%sto branch%s",3302sha1_to_hex(sha1), lock->ref_name);3303unlock_ref(lock);3304return-1;3305}3306if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3307write_in_full(lock->lk->fd, &term,1) !=1||3308close_ref(lock) <0) {3309strbuf_addf(err,3310"Couldn't write%s", lock->lk->filename.buf);3311unlock_ref(lock);3312return-1;3313}3314return0;3315}33163317/*3318 * Commit a change to a loose reference that has already been written3319 * to the loose reference lockfile. Also update the reflogs if3320 * necessary, using the specified lockmsg (which can be NULL).3321 */3322static intcommit_ref_update(struct ref_lock *lock,3323const unsigned char*sha1,const char*logmsg,3324int flags,struct strbuf *err)3325{3326clear_loose_ref_cache(&ref_cache);3327if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3328(strcmp(lock->ref_name, lock->orig_ref_name) &&3329log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3330char*old_msg =strbuf_detach(err, NULL);3331strbuf_addf(err,"Cannot update the ref '%s':%s",3332 lock->ref_name, old_msg);3333free(old_msg);3334unlock_ref(lock);3335return-1;3336}3337if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3338/*3339 * Special hack: If a branch is updated directly and HEAD3340 * points to it (may happen on the remote side of a push3341 * for example) then logically the HEAD reflog should be3342 * updated too.3343 * A generic solution implies reverse symref information,3344 * but finding all symrefs pointing to the given branch3345 * would be rather costly for this rare event (the direct3346 * update of a branch) to be worth it. So let's cheat and3347 * check with HEAD only which should cover 99% of all usage3348 * scenarios (even 100% of the default ones).3349 */3350unsigned char head_sha1[20];3351int head_flag;3352const char*head_ref;3353 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3354 head_sha1, &head_flag);3355if(head_ref && (head_flag & REF_ISSYMREF) &&3356!strcmp(head_ref, lock->ref_name)) {3357struct strbuf log_err = STRBUF_INIT;3358if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3359 logmsg,0, &log_err)) {3360error("%s", log_err.buf);3361strbuf_release(&log_err);3362}3363}3364}3365if(commit_ref(lock)) {3366error("Couldn't set%s", lock->ref_name);3367unlock_ref(lock);3368return-1;3369}33703371unlock_ref(lock);3372return0;3373}33743375intcreate_symref(const char*ref_target,const char*refs_heads_master,3376const char*logmsg)3377{3378char*lockpath = NULL;3379char ref[1000];3380int fd, len, written;3381char*git_HEAD =git_pathdup("%s", ref_target);3382unsigned char old_sha1[20], new_sha1[20];3383struct strbuf err = STRBUF_INIT;33843385if(logmsg &&read_ref(ref_target, old_sha1))3386hashclr(old_sha1);33873388if(safe_create_leading_directories(git_HEAD) <0)3389returnerror("unable to create directory for%s", git_HEAD);33903391#ifndef NO_SYMLINK_HEAD3392if(prefer_symlink_refs) {3393unlink(git_HEAD);3394if(!symlink(refs_heads_master, git_HEAD))3395goto done;3396fprintf(stderr,"no symlink - falling back to symbolic ref\n");3397}3398#endif33993400 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3401if(sizeof(ref) <= len) {3402error("refname too long:%s", refs_heads_master);3403goto error_free_return;3404}3405 lockpath =mkpathdup("%s.lock", git_HEAD);3406 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3407if(fd <0) {3408error("Unable to open%sfor writing", lockpath);3409goto error_free_return;3410}3411 written =write_in_full(fd, ref, len);3412if(close(fd) !=0|| written != len) {3413error("Unable to write to%s", lockpath);3414goto error_unlink_return;3415}3416if(rename(lockpath, git_HEAD) <0) {3417error("Unable to create%s", git_HEAD);3418goto error_unlink_return;3419}3420if(adjust_shared_perm(git_HEAD)) {3421error("Unable to fix permissions on%s", lockpath);3422 error_unlink_return:3423unlink_or_warn(lockpath);3424 error_free_return:3425free(lockpath);3426free(git_HEAD);3427return-1;3428}3429free(lockpath);34303431#ifndef NO_SYMLINK_HEAD3432 done:3433#endif3434if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3435log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3436error("%s", err.buf);3437strbuf_release(&err);3438}34393440free(git_HEAD);3441return0;3442}34433444struct read_ref_at_cb {3445const char*refname;3446unsigned long at_time;3447int cnt;3448int reccnt;3449unsigned char*sha1;3450int found_it;34513452unsigned char osha1[20];3453unsigned char nsha1[20];3454int tz;3455unsigned long date;3456char**msg;3457unsigned long*cutoff_time;3458int*cutoff_tz;3459int*cutoff_cnt;3460};34613462static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3463const char*email,unsigned long timestamp,int tz,3464const char*message,void*cb_data)3465{3466struct read_ref_at_cb *cb = cb_data;34673468 cb->reccnt++;3469 cb->tz = tz;3470 cb->date = timestamp;34713472if(timestamp <= cb->at_time || cb->cnt ==0) {3473if(cb->msg)3474*cb->msg =xstrdup(message);3475if(cb->cutoff_time)3476*cb->cutoff_time = timestamp;3477if(cb->cutoff_tz)3478*cb->cutoff_tz = tz;3479if(cb->cutoff_cnt)3480*cb->cutoff_cnt = cb->reccnt -1;3481/*3482 * we have not yet updated cb->[n|o]sha1 so they still3483 * hold the values for the previous record.3484 */3485if(!is_null_sha1(cb->osha1)) {3486hashcpy(cb->sha1, nsha1);3487if(hashcmp(cb->osha1, nsha1))3488warning("Log for ref%shas gap after%s.",3489 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3490}3491else if(cb->date == cb->at_time)3492hashcpy(cb->sha1, nsha1);3493else if(hashcmp(nsha1, cb->sha1))3494warning("Log for ref%sunexpectedly ended on%s.",3495 cb->refname,show_date(cb->date, cb->tz,3496DATE_MODE(RFC2822)));3497hashcpy(cb->osha1, osha1);3498hashcpy(cb->nsha1, nsha1);3499 cb->found_it =1;3500return1;3501}3502hashcpy(cb->osha1, osha1);3503hashcpy(cb->nsha1, nsha1);3504if(cb->cnt >0)3505 cb->cnt--;3506return0;3507}35083509static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3510const char*email,unsigned long timestamp,3511int tz,const char*message,void*cb_data)3512{3513struct read_ref_at_cb *cb = cb_data;35143515if(cb->msg)3516*cb->msg =xstrdup(message);3517if(cb->cutoff_time)3518*cb->cutoff_time = timestamp;3519if(cb->cutoff_tz)3520*cb->cutoff_tz = tz;3521if(cb->cutoff_cnt)3522*cb->cutoff_cnt = cb->reccnt;3523hashcpy(cb->sha1, osha1);3524if(is_null_sha1(cb->sha1))3525hashcpy(cb->sha1, nsha1);3526/* We just want the first entry */3527return1;3528}35293530intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3531unsigned char*sha1,char**msg,3532unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3533{3534struct read_ref_at_cb cb;35353536memset(&cb,0,sizeof(cb));3537 cb.refname = refname;3538 cb.at_time = at_time;3539 cb.cnt = cnt;3540 cb.msg = msg;3541 cb.cutoff_time = cutoff_time;3542 cb.cutoff_tz = cutoff_tz;3543 cb.cutoff_cnt = cutoff_cnt;3544 cb.sha1 = sha1;35453546for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);35473548if(!cb.reccnt) {3549if(flags & GET_SHA1_QUIETLY)3550exit(128);3551else3552die("Log for%sis empty.", refname);3553}3554if(cb.found_it)3555return0;35563557for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);35583559return1;3560}35613562intreflog_exists(const char*refname)3563{3564struct stat st;35653566return!lstat(git_path("logs/%s", refname), &st) &&3567S_ISREG(st.st_mode);3568}35693570intdelete_reflog(const char*refname)3571{3572returnremove_path(git_path("logs/%s", refname));3573}35743575static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3576{3577unsigned char osha1[20], nsha1[20];3578char*email_end, *message;3579unsigned long timestamp;3580int tz;35813582/* old SP new SP name <email> SP time TAB msg LF */3583if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3584get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3585get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3586!(email_end =strchr(sb->buf +82,'>')) ||3587 email_end[1] !=' '||3588!(timestamp =strtoul(email_end +2, &message,10)) ||3589!message || message[0] !=' '||3590(message[1] !='+'&& message[1] !='-') ||3591!isdigit(message[2]) || !isdigit(message[3]) ||3592!isdigit(message[4]) || !isdigit(message[5]))3593return0;/* corrupt? */3594 email_end[1] ='\0';3595 tz =strtol(message +1, NULL,10);3596if(message[6] !='\t')3597 message +=6;3598else3599 message +=7;3600returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3601}36023603static char*find_beginning_of_line(char*bob,char*scan)3604{3605while(bob < scan && *(--scan) !='\n')3606;/* keep scanning backwards */3607/*3608 * Return either beginning of the buffer, or LF at the end of3609 * the previous line.3610 */3611return scan;3612}36133614intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3615{3616struct strbuf sb = STRBUF_INIT;3617FILE*logfp;3618long pos;3619int ret =0, at_tail =1;36203621 logfp =fopen(git_path("logs/%s", refname),"r");3622if(!logfp)3623return-1;36243625/* Jump to the end */3626if(fseek(logfp,0, SEEK_END) <0)3627returnerror("cannot seek back reflog for%s:%s",3628 refname,strerror(errno));3629 pos =ftell(logfp);3630while(!ret &&0< pos) {3631int cnt;3632size_t nread;3633char buf[BUFSIZ];3634char*endp, *scanp;36353636/* Fill next block from the end */3637 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3638if(fseek(logfp, pos - cnt, SEEK_SET))3639returnerror("cannot seek back reflog for%s:%s",3640 refname,strerror(errno));3641 nread =fread(buf, cnt,1, logfp);3642if(nread !=1)3643returnerror("cannot read%dbytes from reflog for%s:%s",3644 cnt, refname,strerror(errno));3645 pos -= cnt;36463647 scanp = endp = buf + cnt;3648if(at_tail && scanp[-1] =='\n')3649/* Looking at the final LF at the end of the file */3650 scanp--;3651 at_tail =0;36523653while(buf < scanp) {3654/*3655 * terminating LF of the previous line, or the beginning3656 * of the buffer.3657 */3658char*bp;36593660 bp =find_beginning_of_line(buf, scanp);36613662if(*bp =='\n') {3663/*3664 * The newline is the end of the previous line,3665 * so we know we have complete line starting3666 * at (bp + 1). Prefix it onto any prior data3667 * we collected for the line and process it.3668 */3669strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3670 scanp = bp;3671 endp = bp +1;3672 ret =show_one_reflog_ent(&sb, fn, cb_data);3673strbuf_reset(&sb);3674if(ret)3675break;3676}else if(!pos) {3677/*3678 * We are at the start of the buffer, and the3679 * start of the file; there is no previous3680 * line, and we have everything for this one.3681 * Process it, and we can end the loop.3682 */3683strbuf_splice(&sb,0,0, buf, endp - buf);3684 ret =show_one_reflog_ent(&sb, fn, cb_data);3685strbuf_reset(&sb);3686break;3687}36883689if(bp == buf) {3690/*3691 * We are at the start of the buffer, and there3692 * is more file to read backwards. Which means3693 * we are in the middle of a line. Note that we3694 * may get here even if *bp was a newline; that3695 * just means we are at the exact end of the3696 * previous line, rather than some spot in the3697 * middle.3698 *3699 * Save away what we have to be combined with3700 * the data from the next read.3701 */3702strbuf_splice(&sb,0,0, buf, endp - buf);3703break;3704}3705}37063707}3708if(!ret && sb.len)3709die("BUG: reverse reflog parser had leftover data");37103711fclose(logfp);3712strbuf_release(&sb);3713return ret;3714}37153716intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3717{3718FILE*logfp;3719struct strbuf sb = STRBUF_INIT;3720int ret =0;37213722 logfp =fopen(git_path("logs/%s", refname),"r");3723if(!logfp)3724return-1;37253726while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3727 ret =show_one_reflog_ent(&sb, fn, cb_data);3728fclose(logfp);3729strbuf_release(&sb);3730return ret;3731}3732/*3733 * Call fn for each reflog in the namespace indicated by name. name3734 * must be empty or end with '/'. Name will be used as a scratch3735 * space, but its contents will be restored before return.3736 */3737static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3738{3739DIR*d =opendir(git_path("logs/%s", name->buf));3740int retval =0;3741struct dirent *de;3742int oldlen = name->len;37433744if(!d)3745return name->len ? errno :0;37463747while((de =readdir(d)) != NULL) {3748struct stat st;37493750if(de->d_name[0] =='.')3751continue;3752if(ends_with(de->d_name,".lock"))3753continue;3754strbuf_addstr(name, de->d_name);3755if(stat(git_path("logs/%s", name->buf), &st) <0) {3756;/* silently ignore */3757}else{3758if(S_ISDIR(st.st_mode)) {3759strbuf_addch(name,'/');3760 retval =do_for_each_reflog(name, fn, cb_data);3761}else{3762struct object_id oid;37633764if(read_ref_full(name->buf,0, oid.hash, NULL))3765 retval =error("bad ref for%s", name->buf);3766else3767 retval =fn(name->buf, &oid,0, cb_data);3768}3769if(retval)3770break;3771}3772strbuf_setlen(name, oldlen);3773}3774closedir(d);3775return retval;3776}37773778intfor_each_reflog(each_ref_fn fn,void*cb_data)3779{3780int retval;3781struct strbuf name;3782strbuf_init(&name, PATH_MAX);3783 retval =do_for_each_reflog(&name, fn, cb_data);3784strbuf_release(&name);3785return retval;3786}37873788/**3789 * Information needed for a single ref update. Set new_sha1 to the new3790 * value or to null_sha1 to delete the ref. To check the old value3791 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3792 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3793 * not exist before update.3794 */3795struct ref_update {3796/*3797 * If (flags & REF_HAVE_NEW), set the reference to this value:3798 */3799unsigned char new_sha1[20];3800/*3801 * If (flags & REF_HAVE_OLD), check that the reference3802 * previously had this value:3803 */3804unsigned char old_sha1[20];3805/*3806 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3807 * REF_DELETING, and REF_ISPRUNING:3808 */3809unsigned int flags;3810struct ref_lock *lock;3811int type;3812char*msg;3813const char refname[FLEX_ARRAY];3814};38153816/*3817 * Transaction states.3818 * OPEN: The transaction is in a valid state and can accept new updates.3819 * An OPEN transaction can be committed.3820 * CLOSED: A closed transaction is no longer active and no other operations3821 * than free can be used on it in this state.3822 * A transaction can either become closed by successfully committing3823 * an active transaction or if there is a failure while building3824 * the transaction thus rendering it failed/inactive.3825 */3826enum ref_transaction_state {3827 REF_TRANSACTION_OPEN =0,3828 REF_TRANSACTION_CLOSED =13829};38303831/*3832 * Data structure for holding a reference transaction, which can3833 * consist of checks and updates to multiple references, carried out3834 * as atomically as possible. This structure is opaque to callers.3835 */3836struct ref_transaction {3837struct ref_update **updates;3838size_t alloc;3839size_t nr;3840enum ref_transaction_state state;3841};38423843struct ref_transaction *ref_transaction_begin(struct strbuf *err)3844{3845assert(err);38463847returnxcalloc(1,sizeof(struct ref_transaction));3848}38493850voidref_transaction_free(struct ref_transaction *transaction)3851{3852int i;38533854if(!transaction)3855return;38563857for(i =0; i < transaction->nr; i++) {3858free(transaction->updates[i]->msg);3859free(transaction->updates[i]);3860}3861free(transaction->updates);3862free(transaction);3863}38643865static struct ref_update *add_update(struct ref_transaction *transaction,3866const char*refname)3867{3868size_t len =strlen(refname);3869struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);38703871strcpy((char*)update->refname, refname);3872ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3873 transaction->updates[transaction->nr++] = update;3874return update;3875}38763877intref_transaction_update(struct ref_transaction *transaction,3878const char*refname,3879const unsigned char*new_sha1,3880const unsigned char*old_sha1,3881unsigned int flags,const char*msg,3882struct strbuf *err)3883{3884struct ref_update *update;38853886assert(err);38873888if(transaction->state != REF_TRANSACTION_OPEN)3889die("BUG: update called for transaction that is not open");38903891if(new_sha1 && !is_null_sha1(new_sha1) &&3892check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3893strbuf_addf(err,"refusing to update ref with bad name%s",3894 refname);3895return-1;3896}38973898 update =add_update(transaction, refname);3899if(new_sha1) {3900hashcpy(update->new_sha1, new_sha1);3901 flags |= REF_HAVE_NEW;3902}3903if(old_sha1) {3904hashcpy(update->old_sha1, old_sha1);3905 flags |= REF_HAVE_OLD;3906}3907 update->flags = flags;3908if(msg)3909 update->msg =xstrdup(msg);3910return0;3911}39123913intref_transaction_create(struct ref_transaction *transaction,3914const char*refname,3915const unsigned char*new_sha1,3916unsigned int flags,const char*msg,3917struct strbuf *err)3918{3919if(!new_sha1 ||is_null_sha1(new_sha1))3920die("BUG: create called without valid new_sha1");3921returnref_transaction_update(transaction, refname, new_sha1,3922 null_sha1, flags, msg, err);3923}39243925intref_transaction_delete(struct ref_transaction *transaction,3926const char*refname,3927const unsigned char*old_sha1,3928unsigned int flags,const char*msg,3929struct strbuf *err)3930{3931if(old_sha1 &&is_null_sha1(old_sha1))3932die("BUG: delete called with old_sha1 set to zeros");3933returnref_transaction_update(transaction, refname,3934 null_sha1, old_sha1,3935 flags, msg, err);3936}39373938intref_transaction_verify(struct ref_transaction *transaction,3939const char*refname,3940const unsigned char*old_sha1,3941unsigned int flags,3942struct strbuf *err)3943{3944if(!old_sha1)3945die("BUG: verify called with old_sha1 set to NULL");3946returnref_transaction_update(transaction, refname,3947 NULL, old_sha1,3948 flags, NULL, err);3949}39503951intupdate_ref(const char*msg,const char*refname,3952const unsigned char*new_sha1,const unsigned char*old_sha1,3953unsigned int flags,enum action_on_err onerr)3954{3955struct ref_transaction *t;3956struct strbuf err = STRBUF_INIT;39573958 t =ref_transaction_begin(&err);3959if(!t ||3960ref_transaction_update(t, refname, new_sha1, old_sha1,3961 flags, msg, &err) ||3962ref_transaction_commit(t, &err)) {3963const char*str ="update_ref failed for ref '%s':%s";39643965ref_transaction_free(t);3966switch(onerr) {3967case UPDATE_REFS_MSG_ON_ERR:3968error(str, refname, err.buf);3969break;3970case UPDATE_REFS_DIE_ON_ERR:3971die(str, refname, err.buf);3972break;3973case UPDATE_REFS_QUIET_ON_ERR:3974break;3975}3976strbuf_release(&err);3977return1;3978}3979strbuf_release(&err);3980ref_transaction_free(t);3981return0;3982}39833984static intref_update_reject_duplicates(struct string_list *refnames,3985struct strbuf *err)3986{3987int i, n = refnames->nr;39883989assert(err);39903991for(i =1; i < n; i++)3992if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3993strbuf_addf(err,3994"Multiple updates for ref '%s' not allowed.",3995 refnames->items[i].string);3996return1;3997}3998return0;3999}40004001intref_transaction_commit(struct ref_transaction *transaction,4002struct strbuf *err)4003{4004int ret =0, i;4005int n = transaction->nr;4006struct ref_update **updates = transaction->updates;4007struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4008struct string_list_item *ref_to_delete;4009struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40104011assert(err);40124013if(transaction->state != REF_TRANSACTION_OPEN)4014die("BUG: commit called for transaction that is not open");40154016if(!n) {4017 transaction->state = REF_TRANSACTION_CLOSED;4018return0;4019}40204021/* Fail if a refname appears more than once in the transaction: */4022for(i =0; i < n; i++)4023string_list_append(&affected_refnames, updates[i]->refname);4024string_list_sort(&affected_refnames);4025if(ref_update_reject_duplicates(&affected_refnames, err)) {4026 ret = TRANSACTION_GENERIC_ERROR;4027goto cleanup;4028}40294030/*4031 * Acquire all locks, verify old values if provided, check4032 * that new values are valid, and write new values to the4033 * lockfiles, ready to be activated. Only keep one lockfile4034 * open at a time to avoid running out of file descriptors.4035 */4036for(i =0; i < n; i++) {4037struct ref_update *update = updates[i];40384039if((update->flags & REF_HAVE_NEW) &&4040is_null_sha1(update->new_sha1))4041 update->flags |= REF_DELETING;4042 update->lock =lock_ref_sha1_basic(4043 update->refname,4044((update->flags & REF_HAVE_OLD) ?4045 update->old_sha1 : NULL),4046&affected_refnames, NULL,4047 update->flags,4048&update->type,4049 err);4050if(!update->lock) {4051char*reason;40524053 ret = (errno == ENOTDIR)4054? TRANSACTION_NAME_CONFLICT4055: TRANSACTION_GENERIC_ERROR;4056 reason =strbuf_detach(err, NULL);4057strbuf_addf(err,"cannot lock ref '%s':%s",4058 update->refname, reason);4059free(reason);4060goto cleanup;4061}4062if((update->flags & REF_HAVE_NEW) &&4063!(update->flags & REF_DELETING)) {4064int overwriting_symref = ((update->type & REF_ISSYMREF) &&4065(update->flags & REF_NODEREF));40664067if(!overwriting_symref &&4068!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4069/*4070 * The reference already has the desired4071 * value, so we don't need to write it.4072 */4073}else if(write_ref_to_lockfile(update->lock,4074 update->new_sha1,4075 err)) {4076char*write_err =strbuf_detach(err, NULL);40774078/*4079 * The lock was freed upon failure of4080 * write_ref_to_lockfile():4081 */4082 update->lock = NULL;4083strbuf_addf(err,4084"cannot update the ref '%s':%s",4085 update->refname, write_err);4086free(write_err);4087 ret = TRANSACTION_GENERIC_ERROR;4088goto cleanup;4089}else{4090 update->flags |= REF_NEEDS_COMMIT;4091}4092}4093if(!(update->flags & REF_NEEDS_COMMIT)) {4094/*4095 * We didn't have to write anything to the lockfile.4096 * Close it to free up the file descriptor:4097 */4098if(close_ref(update->lock)) {4099strbuf_addf(err,"Couldn't close%s.lock",4100 update->refname);4101goto cleanup;4102}4103}4104}41054106/* Perform updates first so live commits remain referenced */4107for(i =0; i < n; i++) {4108struct ref_update *update = updates[i];41094110if(update->flags & REF_NEEDS_COMMIT) {4111if(commit_ref_update(update->lock,4112 update->new_sha1, update->msg,4113 update->flags, err)) {4114/* freed by commit_ref_update(): */4115 update->lock = NULL;4116 ret = TRANSACTION_GENERIC_ERROR;4117goto cleanup;4118}else{4119/* freed by commit_ref_update(): */4120 update->lock = NULL;4121}4122}4123}41244125/* Perform deletes now that updates are safely completed */4126for(i =0; i < n; i++) {4127struct ref_update *update = updates[i];41284129if(update->flags & REF_DELETING) {4130if(delete_ref_loose(update->lock, update->type, err)) {4131 ret = TRANSACTION_GENERIC_ERROR;4132goto cleanup;4133}41344135if(!(update->flags & REF_ISPRUNING))4136string_list_append(&refs_to_delete,4137 update->lock->ref_name);4138}4139}41404141if(repack_without_refs(&refs_to_delete, err)) {4142 ret = TRANSACTION_GENERIC_ERROR;4143goto cleanup;4144}4145for_each_string_list_item(ref_to_delete, &refs_to_delete)4146unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4147clear_loose_ref_cache(&ref_cache);41484149cleanup:4150 transaction->state = REF_TRANSACTION_CLOSED;41514152for(i =0; i < n; i++)4153if(updates[i]->lock)4154unlock_ref(updates[i]->lock);4155string_list_clear(&refs_to_delete,0);4156string_list_clear(&affected_refnames,0);4157return ret;4158}41594160static intref_present(const char*refname,4161const struct object_id *oid,int flags,void*cb_data)4162{4163struct string_list *affected_refnames = cb_data;41644165returnstring_list_has_string(affected_refnames, refname);4166}41674168intinitial_ref_transaction_commit(struct ref_transaction *transaction,4169struct strbuf *err)4170{4171struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4172struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4173int ret =0, i;4174int n = transaction->nr;4175struct ref_update **updates = transaction->updates;4176struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41774178assert(err);41794180if(transaction->state != REF_TRANSACTION_OPEN)4181die("BUG: commit called for transaction that is not open");41824183/* Fail if a refname appears more than once in the transaction: */4184for(i =0; i < n; i++)4185string_list_append(&affected_refnames, updates[i]->refname);4186string_list_sort(&affected_refnames);4187if(ref_update_reject_duplicates(&affected_refnames, err)) {4188 ret = TRANSACTION_GENERIC_ERROR;4189goto cleanup;4190}41914192/*4193 * It's really undefined to call this function in an active4194 * repository or when there are existing references: we are4195 * only locking and changing packed-refs, so (1) any4196 * simultaneous processes might try to change a reference at4197 * the same time we do, and (2) any existing loose versions of4198 * the references that we are setting would have precedence4199 * over our values. But some remote helpers create the remote4200 * "HEAD" and "master" branches before calling this function,4201 * so here we really only check that none of the references4202 * that we are creating already exists.4203 */4204if(for_each_rawref(ref_present, &affected_refnames))4205die("BUG: initial ref transaction called with existing refs");42064207for(i =0; i < n; i++) {4208struct ref_update *update = updates[i];42094210if((update->flags & REF_HAVE_OLD) &&4211!is_null_sha1(update->old_sha1))4212die("BUG: initial ref transaction with old_sha1 set");4213if(verify_refname_available(update->refname,4214&affected_refnames, NULL,4215 loose_refs, err) ||4216verify_refname_available(update->refname,4217&affected_refnames, NULL,4218 packed_refs, err)) {4219 ret = TRANSACTION_NAME_CONFLICT;4220goto cleanup;4221}4222}42234224if(lock_packed_refs(0)) {4225strbuf_addf(err,"unable to lock packed-refs file:%s",4226strerror(errno));4227 ret = TRANSACTION_GENERIC_ERROR;4228goto cleanup;4229}42304231for(i =0; i < n; i++) {4232struct ref_update *update = updates[i];42334234if((update->flags & REF_HAVE_NEW) &&4235!is_null_sha1(update->new_sha1))4236add_packed_ref(update->refname, update->new_sha1);4237}42384239if(commit_packed_refs()) {4240strbuf_addf(err,"unable to commit packed-refs file:%s",4241strerror(errno));4242 ret = TRANSACTION_GENERIC_ERROR;4243goto cleanup;4244}42454246cleanup:4247 transaction->state = REF_TRANSACTION_CLOSED;4248string_list_clear(&affected_refnames,0);4249return ret;4250}42514252char*shorten_unambiguous_ref(const char*refname,int strict)4253{4254int i;4255static char**scanf_fmts;4256static int nr_rules;4257char*short_name;42584259if(!nr_rules) {4260/*4261 * Pre-generate scanf formats from ref_rev_parse_rules[].4262 * Generate a format suitable for scanf from a4263 * ref_rev_parse_rules rule by interpolating "%s" at the4264 * location of the "%.*s".4265 */4266size_t total_len =0;4267size_t offset =0;42684269/* the rule list is NULL terminated, count them first */4270for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4271/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4272 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;42734274 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);42754276 offset =0;4277for(i =0; i < nr_rules; i++) {4278assert(offset < total_len);4279 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4280 offset +=snprintf(scanf_fmts[i], total_len - offset,4281 ref_rev_parse_rules[i],2,"%s") +1;4282}4283}42844285/* bail out if there are no rules */4286if(!nr_rules)4287returnxstrdup(refname);42884289/* buffer for scanf result, at most refname must fit */4290 short_name =xstrdup(refname);42914292/* skip first rule, it will always match */4293for(i = nr_rules -1; i >0; --i) {4294int j;4295int rules_to_fail = i;4296int short_name_len;42974298if(1!=sscanf(refname, scanf_fmts[i], short_name))4299continue;43004301 short_name_len =strlen(short_name);43024303/*4304 * in strict mode, all (except the matched one) rules4305 * must fail to resolve to a valid non-ambiguous ref4306 */4307if(strict)4308 rules_to_fail = nr_rules;43094310/*4311 * check if the short name resolves to a valid ref,4312 * but use only rules prior to the matched one4313 */4314for(j =0; j < rules_to_fail; j++) {4315const char*rule = ref_rev_parse_rules[j];4316char refname[PATH_MAX];43174318/* skip matched rule */4319if(i == j)4320continue;43214322/*4323 * the short name is ambiguous, if it resolves4324 * (with this previous rule) to a valid ref4325 * read_ref() returns 0 on success4326 */4327mksnpath(refname,sizeof(refname),4328 rule, short_name_len, short_name);4329if(ref_exists(refname))4330break;4331}43324333/*4334 * short name is non-ambiguous if all previous rules4335 * haven't resolved to a valid ref4336 */4337if(j == rules_to_fail)4338return short_name;4339}43404341free(short_name);4342returnxstrdup(refname);4343}43444345static struct string_list *hide_refs;43464347intparse_hide_refs_config(const char*var,const char*value,const char*section)4348{4349if(!strcmp("transfer.hiderefs", var) ||4350/* NEEDSWORK: use parse_config_key() once both are merged */4351(starts_with(var, section) && var[strlen(section)] =='.'&&4352!strcmp(var +strlen(section),".hiderefs"))) {4353char*ref;4354int len;43554356if(!value)4357returnconfig_error_nonbool(var);4358 ref =xstrdup(value);4359 len =strlen(ref);4360while(len && ref[len -1] =='/')4361 ref[--len] ='\0';4362if(!hide_refs) {4363 hide_refs =xcalloc(1,sizeof(*hide_refs));4364 hide_refs->strdup_strings =1;4365}4366string_list_append(hide_refs, ref);4367}4368return0;4369}43704371intref_is_hidden(const char*refname)4372{4373struct string_list_item *item;43744375if(!hide_refs)4376return0;4377for_each_string_list_item(item, hide_refs) {4378int len;4379if(!starts_with(refname, item->string))4380continue;4381 len =strlen(item->string);4382if(!refname[len] || refname[len] =='/')4383return1;4384}4385return0;4386}43874388struct expire_reflog_cb {4389unsigned int flags;4390 reflog_expiry_should_prune_fn *should_prune_fn;4391void*policy_cb;4392FILE*newlog;4393unsigned char last_kept_sha1[20];4394};43954396static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4397const char*email,unsigned long timestamp,int tz,4398const char*message,void*cb_data)4399{4400struct expire_reflog_cb *cb = cb_data;4401struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;44024403if(cb->flags & EXPIRE_REFLOGS_REWRITE)4404 osha1 = cb->last_kept_sha1;44054406if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4407 message, policy_cb)) {4408if(!cb->newlog)4409printf("would prune%s", message);4410else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4411printf("prune%s", message);4412}else{4413if(cb->newlog) {4414fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4415sha1_to_hex(osha1),sha1_to_hex(nsha1),4416 email, timestamp, tz, message);4417hashcpy(cb->last_kept_sha1, nsha1);4418}4419if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4420printf("keep%s", message);4421}4422return0;4423}44244425intreflog_expire(const char*refname,const unsigned char*sha1,4426unsigned int flags,4427 reflog_expiry_prepare_fn prepare_fn,4428 reflog_expiry_should_prune_fn should_prune_fn,4429 reflog_expiry_cleanup_fn cleanup_fn,4430void*policy_cb_data)4431{4432static struct lock_file reflog_lock;4433struct expire_reflog_cb cb;4434struct ref_lock *lock;4435char*log_file;4436int status =0;4437int type;4438struct strbuf err = STRBUF_INIT;44394440memset(&cb,0,sizeof(cb));4441 cb.flags = flags;4442 cb.policy_cb = policy_cb_data;4443 cb.should_prune_fn = should_prune_fn;44444445/*4446 * The reflog file is locked by holding the lock on the4447 * reference itself, plus we might need to update the4448 * reference if --updateref was specified:4449 */4450 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4451if(!lock) {4452error("cannot lock ref '%s':%s", refname, err.buf);4453strbuf_release(&err);4454return-1;4455}4456if(!reflog_exists(refname)) {4457unlock_ref(lock);4458return0;4459}44604461 log_file =git_pathdup("logs/%s", refname);4462if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4463/*4464 * Even though holding $GIT_DIR/logs/$reflog.lock has4465 * no locking implications, we use the lock_file4466 * machinery here anyway because it does a lot of the4467 * work we need, including cleaning up if the program4468 * exits unexpectedly.4469 */4470if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4471struct strbuf err = STRBUF_INIT;4472unable_to_lock_message(log_file, errno, &err);4473error("%s", err.buf);4474strbuf_release(&err);4475goto failure;4476}4477 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4478if(!cb.newlog) {4479error("cannot fdopen%s(%s)",4480 reflog_lock.filename.buf,strerror(errno));4481goto failure;4482}4483}44844485(*prepare_fn)(refname, sha1, cb.policy_cb);4486for_each_reflog_ent(refname, expire_reflog_ent, &cb);4487(*cleanup_fn)(cb.policy_cb);44884489if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4490/*4491 * It doesn't make sense to adjust a reference pointed4492 * to by a symbolic ref based on expiring entries in4493 * the symbolic reference's reflog. Nor can we update4494 * a reference if there are no remaining reflog4495 * entries.4496 */4497int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4498!(type & REF_ISSYMREF) &&4499!is_null_sha1(cb.last_kept_sha1);45004501if(close_lock_file(&reflog_lock)) {4502 status |=error("couldn't write%s:%s", log_file,4503strerror(errno));4504}else if(update &&4505(write_in_full(lock->lk->fd,4506sha1_to_hex(cb.last_kept_sha1),40) !=40||4507write_str_in_full(lock->lk->fd,"\n") !=1||4508close_ref(lock) <0)) {4509 status |=error("couldn't write%s",4510 lock->lk->filename.buf);4511rollback_lock_file(&reflog_lock);4512}else if(commit_lock_file(&reflog_lock)) {4513 status |=error("unable to commit reflog '%s' (%s)",4514 log_file,strerror(errno));4515}else if(update &&commit_ref(lock)) {4516 status |=error("couldn't set%s", lock->ref_name);4517}4518}4519free(log_file);4520unlock_ref(lock);4521return status;45224523 failure:4524rollback_lock_file(&reflog_lock);4525free(log_file);4526unlock_ref(lock);4527return-1;4528}