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; 13unsigned char old_sha1[20]; 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, "~", "^", ":" or SP 23 */ 24static unsigned char refname_disposition[256] = { 251,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 264,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 274,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 280,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 290,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 300,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 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,3,0,0,4,4 33}; 34 35/* 36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 37 * refs (i.e., because the reference is about to be deleted anyway). 38 */ 39#define REF_DELETING 0x02 40 41/* 42 * Used as a flag in ref_update::flags when a loose ref is being 43 * pruned. 44 */ 45#define REF_ISPRUNING 0x04 46 47/* 48 * Used as a flag in ref_update::flags when the reference should be 49 * updated to new_sha1. 50 */ 51#define REF_HAVE_NEW 0x08 52 53/* 54 * Used as a flag in ref_update::flags when old_sha1 should be 55 * checked. 56 */ 57#define REF_HAVE_OLD 0x10 58 59/* 60 * Try to read one refname component from the front of refname. 61 * Return the length of the component found, or -1 if the component is 62 * not legal. It is legal if it is something reasonable to have under 63 * ".git/refs/"; We do not like it if: 64 * 65 * - any path component of it begins with ".", or 66 * - it has double dots "..", or 67 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 68 * - it ends with a "/". 69 * - it ends with ".lock" 70 * - it contains a "\" (backslash) 71 */ 72static intcheck_refname_component(const char*refname,int flags) 73{ 74const char*cp; 75char last ='\0'; 76 77for(cp = refname; ; cp++) { 78int ch = *cp &255; 79unsigned char disp = refname_disposition[ch]; 80switch(disp) { 81case1: 82goto out; 83case2: 84if(last =='.') 85return-1;/* Refname contains "..". */ 86break; 87case3: 88if(last =='@') 89return-1;/* Refname contains "@{". */ 90break; 91case4: 92return-1; 93} 94 last = ch; 95} 96out: 97if(cp == refname) 98return0;/* Component has zero length. */ 99if(refname[0] =='.') 100return-1;/* Component starts with '.'. */ 101if(cp - refname >= LOCK_SUFFIX_LEN && 102!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 103return-1;/* Refname ends with ".lock". */ 104return cp - refname; 105} 106 107intcheck_refname_format(const char*refname,int flags) 108{ 109int component_len, component_count =0; 110 111if(!strcmp(refname,"@")) 112/* Refname is a single character '@'. */ 113return-1; 114 115while(1) { 116/* We are at the start of a path component. */ 117 component_len =check_refname_component(refname, flags); 118if(component_len <=0) { 119if((flags & REFNAME_REFSPEC_PATTERN) && 120 refname[0] =='*'&& 121(refname[1] =='\0'|| refname[1] =='/')) { 122/* Accept one wildcard as a full refname component. */ 123 flags &= ~REFNAME_REFSPEC_PATTERN; 124 component_len =1; 125}else{ 126return-1; 127} 128} 129 component_count++; 130if(refname[component_len] =='\0') 131break; 132/* Skip to next component. */ 133 refname += component_len +1; 134} 135 136if(refname[component_len -1] =='.') 137return-1;/* Refname ends with '.'. */ 138if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 139return-1;/* Refname has only one component. */ 140return0; 141} 142 143struct ref_entry; 144 145/* 146 * Information used (along with the information in ref_entry) to 147 * describe a single cached reference. This data structure only 148 * occurs embedded in a union in struct ref_entry, and only when 149 * (ref_entry->flag & REF_DIR) is zero. 150 */ 151struct ref_value { 152/* 153 * The name of the object to which this reference resolves 154 * (which may be a tag object). If REF_ISBROKEN, this is 155 * null. If REF_ISSYMREF, then this is the name of the object 156 * referred to by the last reference in the symlink chain. 157 */ 158unsigned char sha1[20]; 159 160/* 161 * If REF_KNOWS_PEELED, then this field holds the peeled value 162 * of this reference, or null if the reference is known not to 163 * be peelable. See the documentation for peel_ref() for an 164 * exact definition of "peelable". 165 */ 166unsigned char peeled[20]; 167}; 168 169struct ref_cache; 170 171/* 172 * Information used (along with the information in ref_entry) to 173 * describe a level in the hierarchy of references. This data 174 * structure only occurs embedded in a union in struct ref_entry, and 175 * only when (ref_entry.flag & REF_DIR) is set. In that case, 176 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 177 * in the directory have already been read: 178 * 179 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 180 * or packed references, already read. 181 * 182 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 183 * references that hasn't been read yet (nor has any of its 184 * subdirectories). 185 * 186 * Entries within a directory are stored within a growable array of 187 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 188 * sorted are sorted by their component name in strcmp() order and the 189 * remaining entries are unsorted. 190 * 191 * Loose references are read lazily, one directory at a time. When a 192 * directory of loose references is read, then all of the references 193 * in that directory are stored, and REF_INCOMPLETE stubs are created 194 * for any subdirectories, but the subdirectories themselves are not 195 * read. The reading is triggered by get_ref_dir(). 196 */ 197struct ref_dir { 198int nr, alloc; 199 200/* 201 * Entries with index 0 <= i < sorted are sorted by name. New 202 * entries are appended to the list unsorted, and are sorted 203 * only when required; thus we avoid the need to sort the list 204 * after the addition of every reference. 205 */ 206int sorted; 207 208/* A pointer to the ref_cache that contains this ref_dir. */ 209struct ref_cache *ref_cache; 210 211struct ref_entry **entries; 212}; 213 214/* 215 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 216 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 217 * public values; see refs.h. 218 */ 219 220/* 221 * The field ref_entry->u.value.peeled of this value entry contains 222 * the correct peeled value for the reference, which might be 223 * null_sha1 if the reference is not a tag or if it is broken. 224 */ 225#define REF_KNOWS_PEELED 0x10 226 227/* ref_entry represents a directory of references */ 228#define REF_DIR 0x20 229 230/* 231 * Entry has not yet been read from disk (used only for REF_DIR 232 * entries representing loose references) 233 */ 234#define REF_INCOMPLETE 0x40 235 236/* 237 * A ref_entry represents either a reference or a "subdirectory" of 238 * references. 239 * 240 * Each directory in the reference namespace is represented by a 241 * ref_entry with (flags & REF_DIR) set and containing a subdir member 242 * that holds the entries in that directory that have been read so 243 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 244 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 245 * used for loose reference directories. 246 * 247 * References are represented by a ref_entry with (flags & REF_DIR) 248 * unset and a value member that describes the reference's value. The 249 * flag member is at the ref_entry level, but it is also needed to 250 * interpret the contents of the value field (in other words, a 251 * ref_value object is not very much use without the enclosing 252 * ref_entry). 253 * 254 * Reference names cannot end with slash and directories' names are 255 * always stored with a trailing slash (except for the top-level 256 * directory, which is always denoted by ""). This has two nice 257 * consequences: (1) when the entries in each subdir are sorted 258 * lexicographically by name (as they usually are), the references in 259 * a whole tree can be generated in lexicographic order by traversing 260 * the tree in left-to-right, depth-first order; (2) the names of 261 * references and subdirectories cannot conflict, and therefore the 262 * presence of an empty subdirectory does not block the creation of a 263 * similarly-named reference. (The fact that reference names with the 264 * same leading components can conflict *with each other* is a 265 * separate issue that is regulated by is_refname_available().) 266 * 267 * Please note that the name field contains the fully-qualified 268 * reference (or subdirectory) name. Space could be saved by only 269 * storing the relative names. But that would require the full names 270 * to be generated on the fly when iterating in do_for_each_ref(), and 271 * would break callback functions, who have always been able to assume 272 * that the name strings that they are passed will not be freed during 273 * the iteration. 274 */ 275struct ref_entry { 276unsigned char flag;/* ISSYMREF? ISPACKED? */ 277union{ 278struct ref_value value;/* if not (flags&REF_DIR) */ 279struct ref_dir subdir;/* if (flags&REF_DIR) */ 280} u; 281/* 282 * The full name of the reference (e.g., "refs/heads/master") 283 * or the full name of the directory with a trailing slash 284 * (e.g., "refs/heads/"): 285 */ 286char name[FLEX_ARRAY]; 287}; 288 289static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 290 291static struct ref_dir *get_ref_dir(struct ref_entry *entry) 292{ 293struct ref_dir *dir; 294assert(entry->flag & REF_DIR); 295 dir = &entry->u.subdir; 296if(entry->flag & REF_INCOMPLETE) { 297read_loose_refs(entry->name, dir); 298 entry->flag &= ~REF_INCOMPLETE; 299} 300return dir; 301} 302 303/* 304 * Check if a refname is safe. 305 * For refs that start with "refs/" we consider it safe as long they do 306 * not try to resolve to outside of refs/. 307 * 308 * For all other refs we only consider them safe iff they only contain 309 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 310 * "config"). 311 */ 312static intrefname_is_safe(const char*refname) 313{ 314if(starts_with(refname,"refs/")) { 315char*buf; 316int result; 317 318 buf =xmalloc(strlen(refname) +1); 319/* 320 * Does the refname try to escape refs/? 321 * For example: refs/foo/../bar is safe but refs/foo/../../bar 322 * is not. 323 */ 324 result = !normalize_path_copy(buf, refname +strlen("refs/")); 325free(buf); 326return result; 327} 328while(*refname) { 329if(!isupper(*refname) && *refname !='_') 330return0; 331 refname++; 332} 333return1; 334} 335 336static struct ref_entry *create_ref_entry(const char*refname, 337const unsigned char*sha1,int flag, 338int check_name) 339{ 340int len; 341struct ref_entry *ref; 342 343if(check_name && 344check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 345die("Reference has invalid format: '%s'", refname); 346if(!check_name && !refname_is_safe(refname)) 347die("Reference has invalid name: '%s'", refname); 348 len =strlen(refname) +1; 349 ref =xmalloc(sizeof(struct ref_entry) + len); 350hashcpy(ref->u.value.sha1, sha1); 351hashclr(ref->u.value.peeled); 352memcpy(ref->name, refname, len); 353 ref->flag = flag; 354return ref; 355} 356 357static voidclear_ref_dir(struct ref_dir *dir); 358 359static voidfree_ref_entry(struct ref_entry *entry) 360{ 361if(entry->flag & REF_DIR) { 362/* 363 * Do not use get_ref_dir() here, as that might 364 * trigger the reading of loose refs. 365 */ 366clear_ref_dir(&entry->u.subdir); 367} 368free(entry); 369} 370 371/* 372 * Add a ref_entry to the end of dir (unsorted). Entry is always 373 * stored directly in dir; no recursion into subdirectories is 374 * done. 375 */ 376static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 377{ 378ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 379 dir->entries[dir->nr++] = entry; 380/* optimize for the case that entries are added in order */ 381if(dir->nr ==1|| 382(dir->nr == dir->sorted +1&& 383strcmp(dir->entries[dir->nr -2]->name, 384 dir->entries[dir->nr -1]->name) <0)) 385 dir->sorted = dir->nr; 386} 387 388/* 389 * Clear and free all entries in dir, recursively. 390 */ 391static voidclear_ref_dir(struct ref_dir *dir) 392{ 393int i; 394for(i =0; i < dir->nr; i++) 395free_ref_entry(dir->entries[i]); 396free(dir->entries); 397 dir->sorted = dir->nr = dir->alloc =0; 398 dir->entries = NULL; 399} 400 401/* 402 * Create a struct ref_entry object for the specified dirname. 403 * dirname is the name of the directory with a trailing slash (e.g., 404 * "refs/heads/") or "" for the top-level directory. 405 */ 406static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 407const char*dirname,size_t len, 408int incomplete) 409{ 410struct ref_entry *direntry; 411 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 412memcpy(direntry->name, dirname, len); 413 direntry->name[len] ='\0'; 414 direntry->u.subdir.ref_cache = ref_cache; 415 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 416return direntry; 417} 418 419static intref_entry_cmp(const void*a,const void*b) 420{ 421struct ref_entry *one = *(struct ref_entry **)a; 422struct ref_entry *two = *(struct ref_entry **)b; 423returnstrcmp(one->name, two->name); 424} 425 426static voidsort_ref_dir(struct ref_dir *dir); 427 428struct string_slice { 429size_t len; 430const char*str; 431}; 432 433static intref_entry_cmp_sslice(const void*key_,const void*ent_) 434{ 435const struct string_slice *key = key_; 436const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 437int cmp =strncmp(key->str, ent->name, key->len); 438if(cmp) 439return cmp; 440return'\0'- (unsigned char)ent->name[key->len]; 441} 442 443/* 444 * Return the index of the entry with the given refname from the 445 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 446 * no such entry is found. dir must already be complete. 447 */ 448static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 449{ 450struct ref_entry **r; 451struct string_slice key; 452 453if(refname == NULL || !dir->nr) 454return-1; 455 456sort_ref_dir(dir); 457 key.len = len; 458 key.str = refname; 459 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 460 ref_entry_cmp_sslice); 461 462if(r == NULL) 463return-1; 464 465return r - dir->entries; 466} 467 468/* 469 * Search for a directory entry directly within dir (without 470 * recursing). Sort dir if necessary. subdirname must be a directory 471 * name (i.e., end in '/'). If mkdir is set, then create the 472 * directory if it is missing; otherwise, return NULL if the desired 473 * directory cannot be found. dir must already be complete. 474 */ 475static struct ref_dir *search_for_subdir(struct ref_dir *dir, 476const char*subdirname,size_t len, 477int mkdir) 478{ 479int entry_index =search_ref_dir(dir, subdirname, len); 480struct ref_entry *entry; 481if(entry_index == -1) { 482if(!mkdir) 483return NULL; 484/* 485 * Since dir is complete, the absence of a subdir 486 * means that the subdir really doesn't exist; 487 * therefore, create an empty record for it but mark 488 * the record complete. 489 */ 490 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 491add_entry_to_dir(dir, entry); 492}else{ 493 entry = dir->entries[entry_index]; 494} 495returnget_ref_dir(entry); 496} 497 498/* 499 * If refname is a reference name, find the ref_dir within the dir 500 * tree that should hold refname. If refname is a directory name 501 * (i.e., ends in '/'), then return that ref_dir itself. dir must 502 * represent the top-level directory and must already be complete. 503 * Sort ref_dirs and recurse into subdirectories as necessary. If 504 * mkdir is set, then create any missing directories; otherwise, 505 * return NULL if the desired directory cannot be found. 506 */ 507static struct ref_dir *find_containing_dir(struct ref_dir *dir, 508const char*refname,int mkdir) 509{ 510const char*slash; 511for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 512size_t dirnamelen = slash - refname +1; 513struct ref_dir *subdir; 514 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 515if(!subdir) { 516 dir = NULL; 517break; 518} 519 dir = subdir; 520} 521 522return dir; 523} 524 525/* 526 * Find the value entry with the given name in dir, sorting ref_dirs 527 * and recursing into subdirectories as necessary. If the name is not 528 * found or it corresponds to a directory entry, return NULL. 529 */ 530static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 531{ 532int entry_index; 533struct ref_entry *entry; 534 dir =find_containing_dir(dir, refname,0); 535if(!dir) 536return NULL; 537 entry_index =search_ref_dir(dir, refname,strlen(refname)); 538if(entry_index == -1) 539return NULL; 540 entry = dir->entries[entry_index]; 541return(entry->flag & REF_DIR) ? NULL : entry; 542} 543 544/* 545 * Remove the entry with the given name from dir, recursing into 546 * subdirectories as necessary. If refname is the name of a directory 547 * (i.e., ends with '/'), then remove the directory and its contents. 548 * If the removal was successful, return the number of entries 549 * remaining in the directory entry that contained the deleted entry. 550 * If the name was not found, return -1. Please note that this 551 * function only deletes the entry from the cache; it does not delete 552 * it from the filesystem or ensure that other cache entries (which 553 * might be symbolic references to the removed entry) are updated. 554 * Nor does it remove any containing dir entries that might be made 555 * empty by the removal. dir must represent the top-level directory 556 * and must already be complete. 557 */ 558static intremove_entry(struct ref_dir *dir,const char*refname) 559{ 560int refname_len =strlen(refname); 561int entry_index; 562struct ref_entry *entry; 563int is_dir = refname[refname_len -1] =='/'; 564if(is_dir) { 565/* 566 * refname represents a reference directory. Remove 567 * the trailing slash; otherwise we will get the 568 * directory *representing* refname rather than the 569 * one *containing* it. 570 */ 571char*dirname =xmemdupz(refname, refname_len -1); 572 dir =find_containing_dir(dir, dirname,0); 573free(dirname); 574}else{ 575 dir =find_containing_dir(dir, refname,0); 576} 577if(!dir) 578return-1; 579 entry_index =search_ref_dir(dir, refname, refname_len); 580if(entry_index == -1) 581return-1; 582 entry = dir->entries[entry_index]; 583 584memmove(&dir->entries[entry_index], 585&dir->entries[entry_index +1], 586(dir->nr - entry_index -1) *sizeof(*dir->entries) 587); 588 dir->nr--; 589if(dir->sorted > entry_index) 590 dir->sorted--; 591free_ref_entry(entry); 592return dir->nr; 593} 594 595/* 596 * Add a ref_entry to the ref_dir (unsorted), recursing into 597 * subdirectories as necessary. dir must represent the top-level 598 * directory. Return 0 on success. 599 */ 600static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 601{ 602 dir =find_containing_dir(dir, ref->name,1); 603if(!dir) 604return-1; 605add_entry_to_dir(dir, ref); 606return0; 607} 608 609/* 610 * Emit a warning and return true iff ref1 and ref2 have the same name 611 * and the same sha1. Die if they have the same name but different 612 * sha1s. 613 */ 614static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 615{ 616if(strcmp(ref1->name, ref2->name)) 617return0; 618 619/* Duplicate name; make sure that they don't conflict: */ 620 621if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 622/* This is impossible by construction */ 623die("Reference directory conflict:%s", ref1->name); 624 625if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 626die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 627 628warning("Duplicated ref:%s", ref1->name); 629return1; 630} 631 632/* 633 * Sort the entries in dir non-recursively (if they are not already 634 * sorted) and remove any duplicate entries. 635 */ 636static voidsort_ref_dir(struct ref_dir *dir) 637{ 638int i, j; 639struct ref_entry *last = NULL; 640 641/* 642 * This check also prevents passing a zero-length array to qsort(), 643 * which is a problem on some platforms. 644 */ 645if(dir->sorted == dir->nr) 646return; 647 648qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 649 650/* Remove any duplicates: */ 651for(i =0, j =0; j < dir->nr; j++) { 652struct ref_entry *entry = dir->entries[j]; 653if(last &&is_dup_ref(last, entry)) 654free_ref_entry(entry); 655else 656 last = dir->entries[i++] = entry; 657} 658 dir->sorted = dir->nr = i; 659} 660 661/* Include broken references in a do_for_each_ref*() iteration: */ 662#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 663 664/* 665 * Return true iff the reference described by entry can be resolved to 666 * an object in the database. Emit a warning if the referred-to 667 * object does not exist. 668 */ 669static intref_resolves_to_object(struct ref_entry *entry) 670{ 671if(entry->flag & REF_ISBROKEN) 672return0; 673if(!has_sha1_file(entry->u.value.sha1)) { 674error("%sdoes not point to a valid object!", entry->name); 675return0; 676} 677return1; 678} 679 680/* 681 * current_ref is a performance hack: when iterating over references 682 * using the for_each_ref*() functions, current_ref is set to the 683 * current reference's entry before calling the callback function. If 684 * the callback function calls peel_ref(), then peel_ref() first 685 * checks whether the reference to be peeled is the current reference 686 * (it usually is) and if so, returns that reference's peeled version 687 * if it is available. This avoids a refname lookup in a common case. 688 */ 689static struct ref_entry *current_ref; 690 691typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 692 693struct ref_entry_cb { 694const char*base; 695int trim; 696int flags; 697 each_ref_fn *fn; 698void*cb_data; 699}; 700 701/* 702 * Handle one reference in a do_for_each_ref*()-style iteration, 703 * calling an each_ref_fn for each entry. 704 */ 705static intdo_one_ref(struct ref_entry *entry,void*cb_data) 706{ 707struct ref_entry_cb *data = cb_data; 708struct ref_entry *old_current_ref; 709int retval; 710 711if(!starts_with(entry->name, data->base)) 712return0; 713 714if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 715!ref_resolves_to_object(entry)) 716return0; 717 718/* Store the old value, in case this is a recursive call: */ 719 old_current_ref = current_ref; 720 current_ref = entry; 721 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 722 entry->flag, data->cb_data); 723 current_ref = old_current_ref; 724return retval; 725} 726 727/* 728 * Call fn for each reference in dir that has index in the range 729 * offset <= index < dir->nr. Recurse into subdirectories that are in 730 * that index range, sorting them before iterating. This function 731 * does not sort dir itself; it should be sorted beforehand. fn is 732 * called for all references, including broken ones. 733 */ 734static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 735 each_ref_entry_fn fn,void*cb_data) 736{ 737int i; 738assert(dir->sorted == dir->nr); 739for(i = offset; i < dir->nr; i++) { 740struct ref_entry *entry = dir->entries[i]; 741int retval; 742if(entry->flag & REF_DIR) { 743struct ref_dir *subdir =get_ref_dir(entry); 744sort_ref_dir(subdir); 745 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 746}else{ 747 retval =fn(entry, cb_data); 748} 749if(retval) 750return retval; 751} 752return0; 753} 754 755/* 756 * Call fn for each reference in the union of dir1 and dir2, in order 757 * by refname. Recurse into subdirectories. If a value entry appears 758 * in both dir1 and dir2, then only process the version that is in 759 * dir2. The input dirs must already be sorted, but subdirs will be 760 * sorted as needed. fn is called for all references, including 761 * broken ones. 762 */ 763static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 764struct ref_dir *dir2, 765 each_ref_entry_fn fn,void*cb_data) 766{ 767int retval; 768int i1 =0, i2 =0; 769 770assert(dir1->sorted == dir1->nr); 771assert(dir2->sorted == dir2->nr); 772while(1) { 773struct ref_entry *e1, *e2; 774int cmp; 775if(i1 == dir1->nr) { 776returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 777} 778if(i2 == dir2->nr) { 779returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 780} 781 e1 = dir1->entries[i1]; 782 e2 = dir2->entries[i2]; 783 cmp =strcmp(e1->name, e2->name); 784if(cmp ==0) { 785if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 786/* Both are directories; descend them in parallel. */ 787struct ref_dir *subdir1 =get_ref_dir(e1); 788struct ref_dir *subdir2 =get_ref_dir(e2); 789sort_ref_dir(subdir1); 790sort_ref_dir(subdir2); 791 retval =do_for_each_entry_in_dirs( 792 subdir1, subdir2, fn, cb_data); 793 i1++; 794 i2++; 795}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 796/* Both are references; ignore the one from dir1. */ 797 retval =fn(e2, cb_data); 798 i1++; 799 i2++; 800}else{ 801die("conflict between reference and directory:%s", 802 e1->name); 803} 804}else{ 805struct ref_entry *e; 806if(cmp <0) { 807 e = e1; 808 i1++; 809}else{ 810 e = e2; 811 i2++; 812} 813if(e->flag & REF_DIR) { 814struct ref_dir *subdir =get_ref_dir(e); 815sort_ref_dir(subdir); 816 retval =do_for_each_entry_in_dir( 817 subdir,0, fn, cb_data); 818}else{ 819 retval =fn(e, cb_data); 820} 821} 822if(retval) 823return retval; 824} 825} 826 827/* 828 * Load all of the refs from the dir into our in-memory cache. The hard work 829 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 830 * through all of the sub-directories. We do not even need to care about 831 * sorting, as traversal order does not matter to us. 832 */ 833static voidprime_ref_dir(struct ref_dir *dir) 834{ 835int i; 836for(i =0; i < dir->nr; i++) { 837struct ref_entry *entry = dir->entries[i]; 838if(entry->flag & REF_DIR) 839prime_ref_dir(get_ref_dir(entry)); 840} 841} 842 843static intentry_matches(struct ref_entry *entry,const struct string_list *list) 844{ 845return list &&string_list_has_string(list, entry->name); 846} 847 848struct nonmatching_ref_data { 849const struct string_list *skip; 850struct ref_entry *found; 851}; 852 853static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 854{ 855struct nonmatching_ref_data *data = vdata; 856 857if(entry_matches(entry, data->skip)) 858return0; 859 860 data->found = entry; 861return1; 862} 863 864static voidreport_refname_conflict(struct ref_entry *entry, 865const char*refname) 866{ 867error("'%s' exists; cannot create '%s'", entry->name, refname); 868} 869 870/* 871 * Return true iff a reference named refname could be created without 872 * conflicting with the name of an existing reference in dir. If 873 * skip is non-NULL, ignore potential conflicts with refs in skip 874 * (e.g., because they are scheduled for deletion in the same 875 * operation). 876 * 877 * Two reference names conflict if one of them exactly matches the 878 * leading components of the other; e.g., "foo/bar" conflicts with 879 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 880 * "foo/barbados". 881 * 882 * skip must be sorted. 883 */ 884static intis_refname_available(const char*refname, 885const struct string_list *skip, 886struct ref_dir *dir) 887{ 888const char*slash; 889size_t len; 890int pos; 891char*dirname; 892 893for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 894/* 895 * We are still at a leading dir of the refname; we are 896 * looking for a conflict with a leaf entry. 897 * 898 * If we find one, we still must make sure it is 899 * not in "skip". 900 */ 901 pos =search_ref_dir(dir, refname, slash - refname); 902if(pos >=0) { 903struct ref_entry *entry = dir->entries[pos]; 904if(entry_matches(entry, skip)) 905return1; 906report_refname_conflict(entry, refname); 907return0; 908} 909 910 911/* 912 * Otherwise, we can try to continue our search with 913 * the next component; if we come up empty, we know 914 * there is nothing under this whole prefix. 915 */ 916 pos =search_ref_dir(dir, refname, slash +1- refname); 917if(pos <0) 918return1; 919 920 dir =get_ref_dir(dir->entries[pos]); 921} 922 923/* 924 * We are at the leaf of our refname; we want to 925 * make sure there are no directories which match it. 926 */ 927 len =strlen(refname); 928 dirname =xmallocz(len +1); 929sprintf(dirname,"%s/", refname); 930 pos =search_ref_dir(dir, dirname, len +1); 931free(dirname); 932 933if(pos >=0) { 934/* 935 * We found a directory named "refname". It is a 936 * problem iff it contains any ref that is not 937 * in "skip". 938 */ 939struct ref_entry *entry = dir->entries[pos]; 940struct ref_dir *dir =get_ref_dir(entry); 941struct nonmatching_ref_data data; 942 943 data.skip = skip; 944sort_ref_dir(dir); 945if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 946return1; 947 948report_refname_conflict(data.found, refname); 949return0; 950} 951 952/* 953 * There is no point in searching for another leaf 954 * node which matches it; such an entry would be the 955 * ref we are looking for, not a conflict. 956 */ 957return1; 958} 959 960struct packed_ref_cache { 961struct ref_entry *root; 962 963/* 964 * Count of references to the data structure in this instance, 965 * including the pointer from ref_cache::packed if any. The 966 * data will not be freed as long as the reference count is 967 * nonzero. 968 */ 969unsigned int referrers; 970 971/* 972 * Iff the packed-refs file associated with this instance is 973 * currently locked for writing, this points at the associated 974 * lock (which is owned by somebody else). The referrer count 975 * is also incremented when the file is locked and decremented 976 * when it is unlocked. 977 */ 978struct lock_file *lock; 979 980/* The metadata from when this packed-refs cache was read */ 981struct stat_validity validity; 982}; 983 984/* 985 * Future: need to be in "struct repository" 986 * when doing a full libification. 987 */ 988static struct ref_cache { 989struct ref_cache *next; 990struct ref_entry *loose; 991struct packed_ref_cache *packed; 992/* 993 * The submodule name, or "" for the main repo. We allocate 994 * length 1 rather than FLEX_ARRAY so that the main ref_cache 995 * is initialized correctly. 996 */ 997char name[1]; 998} ref_cache, *submodule_ref_caches; 9991000/* Lock used for the main packed-refs file: */1001static struct lock_file packlock;10021003/*1004 * Increment the reference count of *packed_refs.1005 */1006static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1007{1008 packed_refs->referrers++;1009}10101011/*1012 * Decrease the reference count of *packed_refs. If it goes to zero,1013 * free *packed_refs and return true; otherwise return false.1014 */1015static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1016{1017if(!--packed_refs->referrers) {1018free_ref_entry(packed_refs->root);1019stat_validity_clear(&packed_refs->validity);1020free(packed_refs);1021return1;1022}else{1023return0;1024}1025}10261027static voidclear_packed_ref_cache(struct ref_cache *refs)1028{1029if(refs->packed) {1030struct packed_ref_cache *packed_refs = refs->packed;10311032if(packed_refs->lock)1033die("internal error: packed-ref cache cleared while locked");1034 refs->packed = NULL;1035release_packed_ref_cache(packed_refs);1036}1037}10381039static voidclear_loose_ref_cache(struct ref_cache *refs)1040{1041if(refs->loose) {1042free_ref_entry(refs->loose);1043 refs->loose = NULL;1044}1045}10461047static struct ref_cache *create_ref_cache(const char*submodule)1048{1049int len;1050struct ref_cache *refs;1051if(!submodule)1052 submodule ="";1053 len =strlen(submodule) +1;1054 refs =xcalloc(1,sizeof(struct ref_cache) + len);1055memcpy(refs->name, submodule, len);1056return refs;1057}10581059/*1060 * Return a pointer to a ref_cache for the specified submodule. For1061 * the main repository, use submodule==NULL. The returned structure1062 * will be allocated and initialized but not necessarily populated; it1063 * should not be freed.1064 */1065static struct ref_cache *get_ref_cache(const char*submodule)1066{1067struct ref_cache *refs;10681069if(!submodule || !*submodule)1070return&ref_cache;10711072for(refs = submodule_ref_caches; refs; refs = refs->next)1073if(!strcmp(submodule, refs->name))1074return refs;10751076 refs =create_ref_cache(submodule);1077 refs->next = submodule_ref_caches;1078 submodule_ref_caches = refs;1079return refs;1080}10811082/* The length of a peeled reference line in packed-refs, including EOL: */1083#define PEELED_LINE_LENGTH 4210841085/*1086 * The packed-refs header line that we write out. Perhaps other1087 * traits will be added later. The trailing space is required.1088 */1089static const char PACKED_REFS_HEADER[] =1090"# pack-refs with: peeled fully-peeled\n";10911092/*1093 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1094 * Return a pointer to the refname within the line (null-terminated),1095 * or NULL if there was a problem.1096 */1097static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1098{1099const char*ref;11001101/*1102 * 42: the answer to everything.1103 *1104 * In this case, it happens to be the answer to1105 * 40 (length of sha1 hex representation)1106 * +1 (space in between hex and name)1107 * +1 (newline at the end of the line)1108 */1109if(line->len <=42)1110return NULL;11111112if(get_sha1_hex(line->buf, sha1) <0)1113return NULL;1114if(!isspace(line->buf[40]))1115return NULL;11161117 ref = line->buf +41;1118if(isspace(*ref))1119return NULL;11201121if(line->buf[line->len -1] !='\n')1122return NULL;1123 line->buf[--line->len] =0;11241125return ref;1126}11271128/*1129 * Read f, which is a packed-refs file, into dir.1130 *1131 * A comment line of the form "# pack-refs with: " may contain zero or1132 * more traits. We interpret the traits as follows:1133 *1134 * No traits:1135 *1136 * Probably no references are peeled. But if the file contains a1137 * peeled value for a reference, we will use it.1138 *1139 * peeled:1140 *1141 * References under "refs/tags/", if they *can* be peeled, *are*1142 * peeled in this file. References outside of "refs/tags/" are1143 * probably not peeled even if they could have been, but if we find1144 * a peeled value for such a reference we will use it.1145 *1146 * fully-peeled:1147 *1148 * All references in the file that can be peeled are peeled.1149 * Inversely (and this is more important), any references in the1150 * file for which no peeled value is recorded is not peelable. This1151 * trait should typically be written alongside "peeled" for1152 * compatibility with older clients, but we do not require it1153 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1154 */1155static voidread_packed_refs(FILE*f,struct ref_dir *dir)1156{1157struct ref_entry *last = NULL;1158struct strbuf line = STRBUF_INIT;1159enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11601161while(strbuf_getwholeline(&line, f,'\n') != EOF) {1162unsigned char sha1[20];1163const char*refname;1164const char*traits;11651166if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1167if(strstr(traits," fully-peeled "))1168 peeled = PEELED_FULLY;1169else if(strstr(traits," peeled "))1170 peeled = PEELED_TAGS;1171/* perhaps other traits later as well */1172continue;1173}11741175 refname =parse_ref_line(&line, sha1);1176if(refname) {1177int flag = REF_ISPACKED;11781179if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1180hashclr(sha1);1181 flag |= REF_BAD_NAME | REF_ISBROKEN;1182}1183 last =create_ref_entry(refname, sha1, flag,0);1184if(peeled == PEELED_FULLY ||1185(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1186 last->flag |= REF_KNOWS_PEELED;1187add_ref(dir, last);1188continue;1189}1190if(last &&1191 line.buf[0] =='^'&&1192 line.len == PEELED_LINE_LENGTH &&1193 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1194!get_sha1_hex(line.buf +1, sha1)) {1195hashcpy(last->u.value.peeled, sha1);1196/*1197 * Regardless of what the file header said,1198 * we definitely know the value of *this*1199 * reference:1200 */1201 last->flag |= REF_KNOWS_PEELED;1202}1203}12041205strbuf_release(&line);1206}12071208/*1209 * Get the packed_ref_cache for the specified ref_cache, creating it1210 * if necessary.1211 */1212static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1213{1214const char*packed_refs_file;12151216if(*refs->name)1217 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1218else1219 packed_refs_file =git_path("packed-refs");12201221if(refs->packed &&1222!stat_validity_check(&refs->packed->validity, packed_refs_file))1223clear_packed_ref_cache(refs);12241225if(!refs->packed) {1226FILE*f;12271228 refs->packed =xcalloc(1,sizeof(*refs->packed));1229acquire_packed_ref_cache(refs->packed);1230 refs->packed->root =create_dir_entry(refs,"",0,0);1231 f =fopen(packed_refs_file,"r");1232if(f) {1233stat_validity_update(&refs->packed->validity,fileno(f));1234read_packed_refs(f,get_ref_dir(refs->packed->root));1235fclose(f);1236}1237}1238return refs->packed;1239}12401241static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1242{1243returnget_ref_dir(packed_ref_cache->root);1244}12451246static struct ref_dir *get_packed_refs(struct ref_cache *refs)1247{1248returnget_packed_ref_dir(get_packed_ref_cache(refs));1249}12501251voidadd_packed_ref(const char*refname,const unsigned char*sha1)1252{1253struct packed_ref_cache *packed_ref_cache =1254get_packed_ref_cache(&ref_cache);12551256if(!packed_ref_cache->lock)1257die("internal error: packed refs not locked");1258add_ref(get_packed_ref_dir(packed_ref_cache),1259create_ref_entry(refname, sha1, REF_ISPACKED,1));1260}12611262/*1263 * Read the loose references from the namespace dirname into dir1264 * (without recursing). dirname must end with '/'. dir must be the1265 * directory entry corresponding to dirname.1266 */1267static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1268{1269struct ref_cache *refs = dir->ref_cache;1270DIR*d;1271const char*path;1272struct dirent *de;1273int dirnamelen =strlen(dirname);1274struct strbuf refname;12751276if(*refs->name)1277 path =git_path_submodule(refs->name,"%s", dirname);1278else1279 path =git_path("%s", dirname);12801281 d =opendir(path);1282if(!d)1283return;12841285strbuf_init(&refname, dirnamelen +257);1286strbuf_add(&refname, dirname, dirnamelen);12871288while((de =readdir(d)) != NULL) {1289unsigned char sha1[20];1290struct stat st;1291int flag;1292const char*refdir;12931294if(de->d_name[0] =='.')1295continue;1296if(ends_with(de->d_name,".lock"))1297continue;1298strbuf_addstr(&refname, de->d_name);1299 refdir = *refs->name1300?git_path_submodule(refs->name,"%s", refname.buf)1301:git_path("%s", refname.buf);1302if(stat(refdir, &st) <0) {1303;/* silently ignore */1304}else if(S_ISDIR(st.st_mode)) {1305strbuf_addch(&refname,'/');1306add_entry_to_dir(dir,1307create_dir_entry(refs, refname.buf,1308 refname.len,1));1309}else{1310if(*refs->name) {1311hashclr(sha1);1312 flag =0;1313if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1314hashclr(sha1);1315 flag |= REF_ISBROKEN;1316}1317}else if(read_ref_full(refname.buf,1318 RESOLVE_REF_READING,1319 sha1, &flag)) {1320hashclr(sha1);1321 flag |= REF_ISBROKEN;1322}1323if(check_refname_format(refname.buf,1324 REFNAME_ALLOW_ONELEVEL)) {1325hashclr(sha1);1326 flag |= REF_BAD_NAME | REF_ISBROKEN;1327}1328add_entry_to_dir(dir,1329create_ref_entry(refname.buf, sha1, flag,0));1330}1331strbuf_setlen(&refname, dirnamelen);1332}1333strbuf_release(&refname);1334closedir(d);1335}13361337static struct ref_dir *get_loose_refs(struct ref_cache *refs)1338{1339if(!refs->loose) {1340/*1341 * Mark the top-level directory complete because we1342 * are about to read the only subdirectory that can1343 * hold references:1344 */1345 refs->loose =create_dir_entry(refs,"",0,0);1346/*1347 * Create an incomplete entry for "refs/":1348 */1349add_entry_to_dir(get_ref_dir(refs->loose),1350create_dir_entry(refs,"refs/",5,1));1351}1352returnget_ref_dir(refs->loose);1353}13541355/* We allow "recursive" symbolic refs. Only within reason, though */1356#define MAXDEPTH 51357#define MAXREFLEN (1024)13581359/*1360 * Called by resolve_gitlink_ref_recursive() after it failed to read1361 * from the loose refs in ref_cache refs. Find <refname> in the1362 * packed-refs file for the submodule.1363 */1364static intresolve_gitlink_packed_ref(struct ref_cache *refs,1365const char*refname,unsigned char*sha1)1366{1367struct ref_entry *ref;1368struct ref_dir *dir =get_packed_refs(refs);13691370 ref =find_ref(dir, refname);1371if(ref == NULL)1372return-1;13731374hashcpy(sha1, ref->u.value.sha1);1375return0;1376}13771378static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1379const char*refname,unsigned char*sha1,1380int recursion)1381{1382int fd, len;1383char buffer[128], *p;1384char*path;13851386if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1387return-1;1388 path = *refs->name1389?git_path_submodule(refs->name,"%s", refname)1390:git_path("%s", refname);1391 fd =open(path, O_RDONLY);1392if(fd <0)1393returnresolve_gitlink_packed_ref(refs, refname, sha1);13941395 len =read(fd, buffer,sizeof(buffer)-1);1396close(fd);1397if(len <0)1398return-1;1399while(len &&isspace(buffer[len-1]))1400 len--;1401 buffer[len] =0;14021403/* Was it a detached head or an old-fashioned symlink? */1404if(!get_sha1_hex(buffer, sha1))1405return0;14061407/* Symref? */1408if(strncmp(buffer,"ref:",4))1409return-1;1410 p = buffer +4;1411while(isspace(*p))1412 p++;14131414returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1415}14161417intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1418{1419int len =strlen(path), retval;1420char*submodule;1421struct ref_cache *refs;14221423while(len && path[len-1] =='/')1424 len--;1425if(!len)1426return-1;1427 submodule =xstrndup(path, len);1428 refs =get_ref_cache(submodule);1429free(submodule);14301431 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1432return retval;1433}14341435/*1436 * Return the ref_entry for the given refname from the packed1437 * references. If it does not exist, return NULL.1438 */1439static struct ref_entry *get_packed_ref(const char*refname)1440{1441returnfind_ref(get_packed_refs(&ref_cache), refname);1442}14431444/*1445 * A loose ref file doesn't exist; check for a packed ref. The1446 * options are forwarded from resolve_safe_unsafe().1447 */1448static intresolve_missing_loose_ref(const char*refname,1449int resolve_flags,1450unsigned char*sha1,1451int*flags)1452{1453struct ref_entry *entry;14541455/*1456 * The loose reference file does not exist; check for a packed1457 * reference.1458 */1459 entry =get_packed_ref(refname);1460if(entry) {1461hashcpy(sha1, entry->u.value.sha1);1462if(flags)1463*flags |= REF_ISPACKED;1464return0;1465}1466/* The reference is not a packed reference, either. */1467if(resolve_flags & RESOLVE_REF_READING) {1468 errno = ENOENT;1469return-1;1470}else{1471hashclr(sha1);1472return0;1473}1474}14751476/* This function needs to return a meaningful errno on failure */1477const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1478{1479int depth = MAXDEPTH;1480 ssize_t len;1481char buffer[256];1482static char refname_buffer[256];1483int bad_name =0;14841485if(flags)1486*flags =0;14871488if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1489if(flags)1490*flags |= REF_BAD_NAME;14911492if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1493!refname_is_safe(refname)) {1494 errno = EINVAL;1495return NULL;1496}1497/*1498 * dwim_ref() uses REF_ISBROKEN to distinguish between1499 * missing refs and refs that were present but invalid,1500 * to complain about the latter to stderr.1501 *1502 * We don't know whether the ref exists, so don't set1503 * REF_ISBROKEN yet.1504 */1505 bad_name =1;1506}1507for(;;) {1508char path[PATH_MAX];1509struct stat st;1510char*buf;1511int fd;15121513if(--depth <0) {1514 errno = ELOOP;1515return NULL;1516}15171518git_snpath(path,sizeof(path),"%s", refname);15191520/*1521 * We might have to loop back here to avoid a race1522 * condition: first we lstat() the file, then we try1523 * to read it as a link or as a file. But if somebody1524 * changes the type of the file (file <-> directory1525 * <-> symlink) between the lstat() and reading, then1526 * we don't want to report that as an error but rather1527 * try again starting with the lstat().1528 */1529 stat_ref:1530if(lstat(path, &st) <0) {1531if(errno != ENOENT)1532return NULL;1533if(resolve_missing_loose_ref(refname, resolve_flags,1534 sha1, flags))1535return NULL;1536if(bad_name) {1537hashclr(sha1);1538if(flags)1539*flags |= REF_ISBROKEN;1540}1541return refname;1542}15431544/* Follow "normalized" - ie "refs/.." symlinks by hand */1545if(S_ISLNK(st.st_mode)) {1546 len =readlink(path, buffer,sizeof(buffer)-1);1547if(len <0) {1548if(errno == ENOENT || errno == EINVAL)1549/* inconsistent with lstat; retry */1550goto stat_ref;1551else1552return NULL;1553}1554 buffer[len] =0;1555if(starts_with(buffer,"refs/") &&1556!check_refname_format(buffer,0)) {1557strcpy(refname_buffer, buffer);1558 refname = refname_buffer;1559if(flags)1560*flags |= REF_ISSYMREF;1561if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1562hashclr(sha1);1563return refname;1564}1565continue;1566}1567}15681569/* Is it a directory? */1570if(S_ISDIR(st.st_mode)) {1571 errno = EISDIR;1572return NULL;1573}15741575/*1576 * Anything else, just open it and try to use it as1577 * a ref1578 */1579 fd =open(path, O_RDONLY);1580if(fd <0) {1581if(errno == ENOENT)1582/* inconsistent with lstat; retry */1583goto stat_ref;1584else1585return NULL;1586}1587 len =read_in_full(fd, buffer,sizeof(buffer)-1);1588if(len <0) {1589int save_errno = errno;1590close(fd);1591 errno = save_errno;1592return NULL;1593}1594close(fd);1595while(len &&isspace(buffer[len-1]))1596 len--;1597 buffer[len] ='\0';15981599/*1600 * Is it a symbolic ref?1601 */1602if(!starts_with(buffer,"ref:")) {1603/*1604 * Please note that FETCH_HEAD has a second1605 * line containing other data.1606 */1607if(get_sha1_hex(buffer, sha1) ||1608(buffer[40] !='\0'&& !isspace(buffer[40]))) {1609if(flags)1610*flags |= REF_ISBROKEN;1611 errno = EINVAL;1612return NULL;1613}1614if(bad_name) {1615hashclr(sha1);1616if(flags)1617*flags |= REF_ISBROKEN;1618}1619return refname;1620}1621if(flags)1622*flags |= REF_ISSYMREF;1623 buf = buffer +4;1624while(isspace(*buf))1625 buf++;1626 refname =strcpy(refname_buffer, buf);1627if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1628hashclr(sha1);1629return refname;1630}1631if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1632if(flags)1633*flags |= REF_ISBROKEN;16341635if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1636!refname_is_safe(buf)) {1637 errno = EINVAL;1638return NULL;1639}1640 bad_name =1;1641}1642}1643}16441645char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1646{1647returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1648}16491650/* The argument to filter_refs */1651struct ref_filter {1652const char*pattern;1653 each_ref_fn *fn;1654void*cb_data;1655};16561657intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1658{1659if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1660return0;1661return-1;1662}16631664intread_ref(const char*refname,unsigned char*sha1)1665{1666returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1667}16681669intref_exists(const char*refname)1670{1671unsigned char sha1[20];1672return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1673}16741675static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1676void*data)1677{1678struct ref_filter *filter = (struct ref_filter *)data;1679if(wildmatch(filter->pattern, refname,0, NULL))1680return0;1681return filter->fn(refname, sha1, flags, filter->cb_data);1682}16831684enum peel_status {1685/* object was peeled successfully: */1686 PEEL_PEELED =0,16871688/*1689 * object cannot be peeled because the named object (or an1690 * object referred to by a tag in the peel chain), does not1691 * exist.1692 */1693 PEEL_INVALID = -1,16941695/* object cannot be peeled because it is not a tag: */1696 PEEL_NON_TAG = -2,16971698/* ref_entry contains no peeled value because it is a symref: */1699 PEEL_IS_SYMREF = -3,17001701/*1702 * ref_entry cannot be peeled because it is broken (i.e., the1703 * symbolic reference cannot even be resolved to an object1704 * name):1705 */1706 PEEL_BROKEN = -41707};17081709/*1710 * Peel the named object; i.e., if the object is a tag, resolve the1711 * tag recursively until a non-tag is found. If successful, store the1712 * result to sha1 and return PEEL_PEELED. If the object is not a tag1713 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1714 * and leave sha1 unchanged.1715 */1716static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1717{1718struct object *o =lookup_unknown_object(name);17191720if(o->type == OBJ_NONE) {1721int type =sha1_object_info(name, NULL);1722if(type <0|| !object_as_type(o, type,0))1723return PEEL_INVALID;1724}17251726if(o->type != OBJ_TAG)1727return PEEL_NON_TAG;17281729 o =deref_tag_noverify(o);1730if(!o)1731return PEEL_INVALID;17321733hashcpy(sha1, o->sha1);1734return PEEL_PEELED;1735}17361737/*1738 * Peel the entry (if possible) and return its new peel_status. If1739 * repeel is true, re-peel the entry even if there is an old peeled1740 * value that is already stored in it.1741 *1742 * It is OK to call this function with a packed reference entry that1743 * might be stale and might even refer to an object that has since1744 * been garbage-collected. In such a case, if the entry has1745 * REF_KNOWS_PEELED then leave the status unchanged and return1746 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1747 */1748static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1749{1750enum peel_status status;17511752if(entry->flag & REF_KNOWS_PEELED) {1753if(repeel) {1754 entry->flag &= ~REF_KNOWS_PEELED;1755hashclr(entry->u.value.peeled);1756}else{1757returnis_null_sha1(entry->u.value.peeled) ?1758 PEEL_NON_TAG : PEEL_PEELED;1759}1760}1761if(entry->flag & REF_ISBROKEN)1762return PEEL_BROKEN;1763if(entry->flag & REF_ISSYMREF)1764return PEEL_IS_SYMREF;17651766 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1767if(status == PEEL_PEELED || status == PEEL_NON_TAG)1768 entry->flag |= REF_KNOWS_PEELED;1769return status;1770}17711772intpeel_ref(const char*refname,unsigned char*sha1)1773{1774int flag;1775unsigned char base[20];17761777if(current_ref && (current_ref->name == refname1778|| !strcmp(current_ref->name, refname))) {1779if(peel_entry(current_ref,0))1780return-1;1781hashcpy(sha1, current_ref->u.value.peeled);1782return0;1783}17841785if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1786return-1;17871788/*1789 * If the reference is packed, read its ref_entry from the1790 * cache in the hope that we already know its peeled value.1791 * We only try this optimization on packed references because1792 * (a) forcing the filling of the loose reference cache could1793 * be expensive and (b) loose references anyway usually do not1794 * have REF_KNOWS_PEELED.1795 */1796if(flag & REF_ISPACKED) {1797struct ref_entry *r =get_packed_ref(refname);1798if(r) {1799if(peel_entry(r,0))1800return-1;1801hashcpy(sha1, r->u.value.peeled);1802return0;1803}1804}18051806returnpeel_object(base, sha1);1807}18081809struct warn_if_dangling_data {1810FILE*fp;1811const char*refname;1812const struct string_list *refnames;1813const char*msg_fmt;1814};18151816static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1817int flags,void*cb_data)1818{1819struct warn_if_dangling_data *d = cb_data;1820const char*resolves_to;1821unsigned char junk[20];18221823if(!(flags & REF_ISSYMREF))1824return0;18251826 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1827if(!resolves_to1828|| (d->refname1829?strcmp(resolves_to, d->refname)1830: !string_list_has_string(d->refnames, resolves_to))) {1831return0;1832}18331834fprintf(d->fp, d->msg_fmt, refname);1835fputc('\n', d->fp);1836return0;1837}18381839voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1840{1841struct warn_if_dangling_data data;18421843 data.fp = fp;1844 data.refname = refname;1845 data.refnames = NULL;1846 data.msg_fmt = msg_fmt;1847for_each_rawref(warn_if_dangling_symref, &data);1848}18491850voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1851{1852struct warn_if_dangling_data data;18531854 data.fp = fp;1855 data.refname = NULL;1856 data.refnames = refnames;1857 data.msg_fmt = msg_fmt;1858for_each_rawref(warn_if_dangling_symref, &data);1859}18601861/*1862 * Call fn for each reference in the specified ref_cache, omitting1863 * references not in the containing_dir of base. fn is called for all1864 * references, including broken ones. If fn ever returns a non-zero1865 * value, stop the iteration and return that value; otherwise, return1866 * 0.1867 */1868static intdo_for_each_entry(struct ref_cache *refs,const char*base,1869 each_ref_entry_fn fn,void*cb_data)1870{1871struct packed_ref_cache *packed_ref_cache;1872struct ref_dir *loose_dir;1873struct ref_dir *packed_dir;1874int retval =0;18751876/*1877 * We must make sure that all loose refs are read before accessing the1878 * packed-refs file; this avoids a race condition in which loose refs1879 * are migrated to the packed-refs file by a simultaneous process, but1880 * our in-memory view is from before the migration. get_packed_ref_cache()1881 * takes care of making sure our view is up to date with what is on1882 * disk.1883 */1884 loose_dir =get_loose_refs(refs);1885if(base && *base) {1886 loose_dir =find_containing_dir(loose_dir, base,0);1887}1888if(loose_dir)1889prime_ref_dir(loose_dir);18901891 packed_ref_cache =get_packed_ref_cache(refs);1892acquire_packed_ref_cache(packed_ref_cache);1893 packed_dir =get_packed_ref_dir(packed_ref_cache);1894if(base && *base) {1895 packed_dir =find_containing_dir(packed_dir, base,0);1896}18971898if(packed_dir && loose_dir) {1899sort_ref_dir(packed_dir);1900sort_ref_dir(loose_dir);1901 retval =do_for_each_entry_in_dirs(1902 packed_dir, loose_dir, fn, cb_data);1903}else if(packed_dir) {1904sort_ref_dir(packed_dir);1905 retval =do_for_each_entry_in_dir(1906 packed_dir,0, fn, cb_data);1907}else if(loose_dir) {1908sort_ref_dir(loose_dir);1909 retval =do_for_each_entry_in_dir(1910 loose_dir,0, fn, cb_data);1911}19121913release_packed_ref_cache(packed_ref_cache);1914return retval;1915}19161917/*1918 * Call fn for each reference in the specified ref_cache for which the1919 * refname begins with base. If trim is non-zero, then trim that many1920 * characters off the beginning of each refname before passing the1921 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1922 * broken references in the iteration. If fn ever returns a non-zero1923 * value, stop the iteration and return that value; otherwise, return1924 * 0.1925 */1926static intdo_for_each_ref(struct ref_cache *refs,const char*base,1927 each_ref_fn fn,int trim,int flags,void*cb_data)1928{1929struct ref_entry_cb data;1930 data.base = base;1931 data.trim = trim;1932 data.flags = flags;1933 data.fn = fn;1934 data.cb_data = cb_data;19351936if(ref_paranoia <0)1937 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1938if(ref_paranoia)1939 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;19401941returndo_for_each_entry(refs, base, do_one_ref, &data);1942}19431944static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1945{1946unsigned char sha1[20];1947int flag;19481949if(submodule) {1950if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1951returnfn("HEAD", sha1,0, cb_data);19521953return0;1954}19551956if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1957returnfn("HEAD", sha1, flag, cb_data);19581959return0;1960}19611962inthead_ref(each_ref_fn fn,void*cb_data)1963{1964returndo_head_ref(NULL, fn, cb_data);1965}19661967inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1968{1969returndo_head_ref(submodule, fn, cb_data);1970}19711972intfor_each_ref(each_ref_fn fn,void*cb_data)1973{1974returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1975}19761977intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1978{1979returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1980}19811982intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1983{1984returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1985}19861987intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1988 each_ref_fn fn,void*cb_data)1989{1990returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1991}19921993intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1994{1995returnfor_each_ref_in("refs/tags/", fn, cb_data);1996}19971998intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1999{2000returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2001}20022003intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2004{2005returnfor_each_ref_in("refs/heads/", fn, cb_data);2006}20072008intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2009{2010returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2011}20122013intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2014{2015returnfor_each_ref_in("refs/remotes/", fn, cb_data);2016}20172018intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2019{2020returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2021}20222023intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2024{2025returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2026}20272028inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2029{2030struct strbuf buf = STRBUF_INIT;2031int ret =0;2032unsigned char sha1[20];2033int flag;20342035strbuf_addf(&buf,"%sHEAD",get_git_namespace());2036if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2037 ret =fn(buf.buf, sha1, flag, cb_data);2038strbuf_release(&buf);20392040return ret;2041}20422043intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2044{2045struct strbuf buf = STRBUF_INIT;2046int ret;2047strbuf_addf(&buf,"%srefs/",get_git_namespace());2048 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2049strbuf_release(&buf);2050return ret;2051}20522053intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2054const char*prefix,void*cb_data)2055{2056struct strbuf real_pattern = STRBUF_INIT;2057struct ref_filter filter;2058int ret;20592060if(!prefix && !starts_with(pattern,"refs/"))2061strbuf_addstr(&real_pattern,"refs/");2062else if(prefix)2063strbuf_addstr(&real_pattern, prefix);2064strbuf_addstr(&real_pattern, pattern);20652066if(!has_glob_specials(pattern)) {2067/* Append implied '/' '*' if not present. */2068if(real_pattern.buf[real_pattern.len -1] !='/')2069strbuf_addch(&real_pattern,'/');2070/* No need to check for '*', there is none. */2071strbuf_addch(&real_pattern,'*');2072}20732074 filter.pattern = real_pattern.buf;2075 filter.fn = fn;2076 filter.cb_data = cb_data;2077 ret =for_each_ref(filter_refs, &filter);20782079strbuf_release(&real_pattern);2080return ret;2081}20822083intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2084{2085returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2086}20872088intfor_each_rawref(each_ref_fn fn,void*cb_data)2089{2090returndo_for_each_ref(&ref_cache,"", fn,0,2091 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2092}20932094const char*prettify_refname(const char*name)2095{2096return name + (2097starts_with(name,"refs/heads/") ?11:2098starts_with(name,"refs/tags/") ?10:2099starts_with(name,"refs/remotes/") ?13:21000);2101}21022103static const char*ref_rev_parse_rules[] = {2104"%.*s",2105"refs/%.*s",2106"refs/tags/%.*s",2107"refs/heads/%.*s",2108"refs/remotes/%.*s",2109"refs/remotes/%.*s/HEAD",2110 NULL2111};21122113intrefname_match(const char*abbrev_name,const char*full_name)2114{2115const char**p;2116const int abbrev_name_len =strlen(abbrev_name);21172118for(p = ref_rev_parse_rules; *p; p++) {2119if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2120return1;2121}2122}21232124return0;2125}21262127static voidunlock_ref(struct ref_lock *lock)2128{2129/* Do not free lock->lk -- atexit() still looks at them */2130if(lock->lk)2131rollback_lock_file(lock->lk);2132free(lock->ref_name);2133free(lock->orig_ref_name);2134free(lock);2135}21362137/* This function should make sure errno is meaningful on error */2138static struct ref_lock *verify_lock(struct ref_lock *lock,2139const unsigned char*old_sha1,int mustexist)2140{2141if(read_ref_full(lock->ref_name,2142 mustexist ? RESOLVE_REF_READING :0,2143 lock->old_sha1, NULL)) {2144int save_errno = errno;2145error("Can't verify ref%s", lock->ref_name);2146unlock_ref(lock);2147 errno = save_errno;2148return NULL;2149}2150if(hashcmp(lock->old_sha1, old_sha1)) {2151error("Ref%sis at%sbut expected%s", lock->ref_name,2152sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2153unlock_ref(lock);2154 errno = EBUSY;2155return NULL;2156}2157return lock;2158}21592160static intremove_empty_directories(const char*file)2161{2162/* we want to create a file but there is a directory there;2163 * if that is an empty directory (or a directory that contains2164 * only empty directories), remove them.2165 */2166struct strbuf path;2167int result, save_errno;21682169strbuf_init(&path,20);2170strbuf_addstr(&path, file);21712172 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2173 save_errno = errno;21742175strbuf_release(&path);2176 errno = save_errno;21772178return result;2179}21802181/*2182 * *string and *len will only be substituted, and *string returned (for2183 * later free()ing) if the string passed in is a magic short-hand form2184 * to name a branch.2185 */2186static char*substitute_branch_name(const char**string,int*len)2187{2188struct strbuf buf = STRBUF_INIT;2189int ret =interpret_branch_name(*string, *len, &buf);21902191if(ret == *len) {2192size_t size;2193*string =strbuf_detach(&buf, &size);2194*len = size;2195return(char*)*string;2196}21972198return NULL;2199}22002201intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2202{2203char*last_branch =substitute_branch_name(&str, &len);2204const char**p, *r;2205int refs_found =0;22062207*ref = NULL;2208for(p = ref_rev_parse_rules; *p; p++) {2209char fullref[PATH_MAX];2210unsigned char sha1_from_ref[20];2211unsigned char*this_result;2212int flag;22132214 this_result = refs_found ? sha1_from_ref : sha1;2215mksnpath(fullref,sizeof(fullref), *p, len, str);2216 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2217 this_result, &flag);2218if(r) {2219if(!refs_found++)2220*ref =xstrdup(r);2221if(!warn_ambiguous_refs)2222break;2223}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2224warning("ignoring dangling symref%s.", fullref);2225}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2226warning("ignoring broken ref%s.", fullref);2227}2228}2229free(last_branch);2230return refs_found;2231}22322233intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2234{2235char*last_branch =substitute_branch_name(&str, &len);2236const char**p;2237int logs_found =0;22382239*log = NULL;2240for(p = ref_rev_parse_rules; *p; p++) {2241unsigned char hash[20];2242char path[PATH_MAX];2243const char*ref, *it;22442245mksnpath(path,sizeof(path), *p, len, str);2246 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2247 hash, NULL);2248if(!ref)2249continue;2250if(reflog_exists(path))2251 it = path;2252else if(strcmp(ref, path) &&reflog_exists(ref))2253 it = ref;2254else2255continue;2256if(!logs_found++) {2257*log =xstrdup(it);2258hashcpy(sha1, hash);2259}2260if(!warn_ambiguous_refs)2261break;2262}2263free(last_branch);2264return logs_found;2265}22662267/*2268 * Locks a ref returning the lock on success and NULL on failure.2269 * On failure errno is set to something meaningful.2270 */2271static struct ref_lock *lock_ref_sha1_basic(const char*refname,2272const unsigned char*old_sha1,2273const struct string_list *skip,2274unsigned int flags,int*type_p)2275{2276char*ref_file;2277const char*orig_refname = refname;2278struct ref_lock *lock;2279int last_errno =0;2280int type, lflags;2281int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2282int resolve_flags =0;2283int attempts_remaining =3;22842285 lock =xcalloc(1,sizeof(struct ref_lock));22862287if(mustexist)2288 resolve_flags |= RESOLVE_REF_READING;2289if(flags & REF_DELETING) {2290 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2291if(flags & REF_NODEREF)2292 resolve_flags |= RESOLVE_REF_NO_RECURSE;2293}22942295 refname =resolve_ref_unsafe(refname, resolve_flags,2296 lock->old_sha1, &type);2297if(!refname && errno == EISDIR) {2298/* we are trying to lock foo but we used to2299 * have foo/bar which now does not exist;2300 * it is normal for the empty directory 'foo'2301 * to remain.2302 */2303 ref_file =git_path("%s", orig_refname);2304if(remove_empty_directories(ref_file)) {2305 last_errno = errno;2306error("there are still refs under '%s'", orig_refname);2307goto error_return;2308}2309 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2310 lock->old_sha1, &type);2311}2312if(type_p)2313*type_p = type;2314if(!refname) {2315 last_errno = errno;2316error("unable to resolve reference%s:%s",2317 orig_refname,strerror(errno));2318goto error_return;2319}2320/*2321 * If the ref did not exist and we are creating it, make sure2322 * there is no existing packed ref whose name begins with our2323 * refname, nor a packed ref whose name is a proper prefix of2324 * our refname.2325 */2326if(is_null_sha1(lock->old_sha1) &&2327!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2328 last_errno = ENOTDIR;2329goto error_return;2330}23312332 lock->lk =xcalloc(1,sizeof(struct lock_file));23332334 lflags =0;2335if(flags & REF_NODEREF) {2336 refname = orig_refname;2337 lflags |= LOCK_NO_DEREF;2338}2339 lock->ref_name =xstrdup(refname);2340 lock->orig_ref_name =xstrdup(orig_refname);2341 ref_file =git_path("%s", refname);23422343 retry:2344switch(safe_create_leading_directories(ref_file)) {2345case SCLD_OK:2346break;/* success */2347case SCLD_VANISHED:2348if(--attempts_remaining >0)2349goto retry;2350/* fall through */2351default:2352 last_errno = errno;2353error("unable to create directory for%s", ref_file);2354goto error_return;2355}23562357if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2358 last_errno = errno;2359if(errno == ENOENT && --attempts_remaining >0)2360/*2361 * Maybe somebody just deleted one of the2362 * directories leading to ref_file. Try2363 * again:2364 */2365goto retry;2366else{2367struct strbuf err = STRBUF_INIT;2368unable_to_lock_message(ref_file, errno, &err);2369error("%s", err.buf);2370strbuf_release(&err);2371goto error_return;2372}2373}2374return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23752376 error_return:2377unlock_ref(lock);2378 errno = last_errno;2379return NULL;2380}23812382/*2383 * Write an entry to the packed-refs file for the specified refname.2384 * If peeled is non-NULL, write it as the entry's peeled value.2385 */2386static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2387unsigned char*peeled)2388{2389fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2390if(peeled)2391fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2392}23932394/*2395 * An each_ref_entry_fn that writes the entry to a packed-refs file.2396 */2397static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2398{2399enum peel_status peel_status =peel_entry(entry,0);24002401if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2402error("internal error:%sis not a valid packed reference!",2403 entry->name);2404write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2405 peel_status == PEEL_PEELED ?2406 entry->u.value.peeled : NULL);2407return0;2408}24092410/* This should return a meaningful errno on failure */2411intlock_packed_refs(int flags)2412{2413struct packed_ref_cache *packed_ref_cache;24142415if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2416return-1;2417/*2418 * Get the current packed-refs while holding the lock. If the2419 * packed-refs file has been modified since we last read it,2420 * this will automatically invalidate the cache and re-read2421 * the packed-refs file.2422 */2423 packed_ref_cache =get_packed_ref_cache(&ref_cache);2424 packed_ref_cache->lock = &packlock;2425/* Increment the reference count to prevent it from being freed: */2426acquire_packed_ref_cache(packed_ref_cache);2427return0;2428}24292430/*2431 * Commit the packed refs changes.2432 * On error we must make sure that errno contains a meaningful value.2433 */2434intcommit_packed_refs(void)2435{2436struct packed_ref_cache *packed_ref_cache =2437get_packed_ref_cache(&ref_cache);2438int error =0;2439int save_errno =0;2440FILE*out;24412442if(!packed_ref_cache->lock)2443die("internal error: packed-refs not locked");24442445 out =fdopen_lock_file(packed_ref_cache->lock,"w");2446if(!out)2447die_errno("unable to fdopen packed-refs descriptor");24482449fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2450do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24510, write_packed_entry_fn, out);24522453if(commit_lock_file(packed_ref_cache->lock)) {2454 save_errno = errno;2455 error = -1;2456}2457 packed_ref_cache->lock = NULL;2458release_packed_ref_cache(packed_ref_cache);2459 errno = save_errno;2460return error;2461}24622463voidrollback_packed_refs(void)2464{2465struct packed_ref_cache *packed_ref_cache =2466get_packed_ref_cache(&ref_cache);24672468if(!packed_ref_cache->lock)2469die("internal error: packed-refs not locked");2470rollback_lock_file(packed_ref_cache->lock);2471 packed_ref_cache->lock = NULL;2472release_packed_ref_cache(packed_ref_cache);2473clear_packed_ref_cache(&ref_cache);2474}24752476struct ref_to_prune {2477struct ref_to_prune *next;2478unsigned char sha1[20];2479char name[FLEX_ARRAY];2480};24812482struct pack_refs_cb_data {2483unsigned int flags;2484struct ref_dir *packed_refs;2485struct ref_to_prune *ref_to_prune;2486};24872488/*2489 * An each_ref_entry_fn that is run over loose references only. If2490 * the loose reference can be packed, add an entry in the packed ref2491 * cache. If the reference should be pruned, also add it to2492 * ref_to_prune in the pack_refs_cb_data.2493 */2494static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2495{2496struct pack_refs_cb_data *cb = cb_data;2497enum peel_status peel_status;2498struct ref_entry *packed_entry;2499int is_tag_ref =starts_with(entry->name,"refs/tags/");25002501/* ALWAYS pack tags */2502if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2503return0;25042505/* Do not pack symbolic or broken refs: */2506if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2507return0;25082509/* Add a packed ref cache entry equivalent to the loose entry. */2510 peel_status =peel_entry(entry,1);2511if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2512die("internal error peeling reference%s(%s)",2513 entry->name,sha1_to_hex(entry->u.value.sha1));2514 packed_entry =find_ref(cb->packed_refs, entry->name);2515if(packed_entry) {2516/* Overwrite existing packed entry with info from loose entry */2517 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2518hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2519}else{2520 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2521 REF_ISPACKED | REF_KNOWS_PEELED,0);2522add_ref(cb->packed_refs, packed_entry);2523}2524hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25252526/* Schedule the loose reference for pruning if requested. */2527if((cb->flags & PACK_REFS_PRUNE)) {2528int namelen =strlen(entry->name) +1;2529struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2530hashcpy(n->sha1, entry->u.value.sha1);2531strcpy(n->name, entry->name);2532 n->next = cb->ref_to_prune;2533 cb->ref_to_prune = n;2534}2535return0;2536}25372538/*2539 * Remove empty parents, but spare refs/ and immediate subdirs.2540 * Note: munges *name.2541 */2542static voidtry_remove_empty_parents(char*name)2543{2544char*p, *q;2545int i;2546 p = name;2547for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2548while(*p && *p !='/')2549 p++;2550/* tolerate duplicate slashes; see check_refname_format() */2551while(*p =='/')2552 p++;2553}2554for(q = p; *q; q++)2555;2556while(1) {2557while(q > p && *q !='/')2558 q--;2559while(q > p && *(q-1) =='/')2560 q--;2561if(q == p)2562break;2563*q ='\0';2564if(rmdir(git_path("%s", name)))2565break;2566}2567}25682569/* make sure nobody touched the ref, and unlink */2570static voidprune_ref(struct ref_to_prune *r)2571{2572struct ref_transaction *transaction;2573struct strbuf err = STRBUF_INIT;25742575if(check_refname_format(r->name,0))2576return;25772578 transaction =ref_transaction_begin(&err);2579if(!transaction ||2580ref_transaction_delete(transaction, r->name, r->sha1,2581 REF_ISPRUNING, NULL, &err) ||2582ref_transaction_commit(transaction, &err)) {2583ref_transaction_free(transaction);2584error("%s", err.buf);2585strbuf_release(&err);2586return;2587}2588ref_transaction_free(transaction);2589strbuf_release(&err);2590try_remove_empty_parents(r->name);2591}25922593static voidprune_refs(struct ref_to_prune *r)2594{2595while(r) {2596prune_ref(r);2597 r = r->next;2598}2599}26002601intpack_refs(unsigned int flags)2602{2603struct pack_refs_cb_data cbdata;26042605memset(&cbdata,0,sizeof(cbdata));2606 cbdata.flags = flags;26072608lock_packed_refs(LOCK_DIE_ON_ERROR);2609 cbdata.packed_refs =get_packed_refs(&ref_cache);26102611do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2612 pack_if_possible_fn, &cbdata);26132614if(commit_packed_refs())2615die_errno("unable to overwrite old ref-pack file");26162617prune_refs(cbdata.ref_to_prune);2618return0;2619}26202621intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2622{2623struct ref_dir *packed;2624struct string_list_item *refname;2625int ret, needs_repacking =0, removed =0;26262627assert(err);26282629/* Look for a packed ref */2630for_each_string_list_item(refname, refnames) {2631if(get_packed_ref(refname->string)) {2632 needs_repacking =1;2633break;2634}2635}26362637/* Avoid locking if we have nothing to do */2638if(!needs_repacking)2639return0;/* no refname exists in packed refs */26402641if(lock_packed_refs(0)) {2642unable_to_lock_message(git_path("packed-refs"), errno, err);2643return-1;2644}2645 packed =get_packed_refs(&ref_cache);26462647/* Remove refnames from the cache */2648for_each_string_list_item(refname, refnames)2649if(remove_entry(packed, refname->string) != -1)2650 removed =1;2651if(!removed) {2652/*2653 * All packed entries disappeared while we were2654 * acquiring the lock.2655 */2656rollback_packed_refs();2657return0;2658}26592660/* Write what remains */2661 ret =commit_packed_refs();2662if(ret)2663strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2664strerror(errno));2665return ret;2666}26672668static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2669{2670assert(err);26712672if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2673/*2674 * loose. The loose file name is the same as the2675 * lockfile name, minus ".lock":2676 */2677char*loose_filename =get_locked_file_path(lock->lk);2678int res =unlink_or_msg(loose_filename, err);2679free(loose_filename);2680if(res)2681return1;2682}2683return0;2684}26852686intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2687{2688struct ref_transaction *transaction;2689struct strbuf err = STRBUF_INIT;26902691 transaction =ref_transaction_begin(&err);2692if(!transaction ||2693ref_transaction_delete(transaction, refname,2694(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2695 flags, NULL, &err) ||2696ref_transaction_commit(transaction, &err)) {2697error("%s", err.buf);2698ref_transaction_free(transaction);2699strbuf_release(&err);2700return1;2701}2702ref_transaction_free(transaction);2703strbuf_release(&err);2704return0;2705}27062707/*2708 * People using contrib's git-new-workdir have .git/logs/refs ->2709 * /some/other/path/.git/logs/refs, and that may live on another device.2710 *2711 * IOW, to avoid cross device rename errors, the temporary renamed log must2712 * live into logs/refs.2713 */2714#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27152716static intrename_tmp_log(const char*newrefname)2717{2718int attempts_remaining =4;27192720 retry:2721switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2722case SCLD_OK:2723break;/* success */2724case SCLD_VANISHED:2725if(--attempts_remaining >0)2726goto retry;2727/* fall through */2728default:2729error("unable to create directory for%s", newrefname);2730return-1;2731}27322733if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2734if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2735/*2736 * rename(a, b) when b is an existing2737 * directory ought to result in ISDIR, but2738 * Solaris 5.8 gives ENOTDIR. Sheesh.2739 */2740if(remove_empty_directories(git_path("logs/%s", newrefname))) {2741error("Directory not empty: logs/%s", newrefname);2742return-1;2743}2744goto retry;2745}else if(errno == ENOENT && --attempts_remaining >0) {2746/*2747 * Maybe another process just deleted one of2748 * the directories in the path to newrefname.2749 * Try again from the beginning.2750 */2751goto retry;2752}else{2753error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2754 newrefname,strerror(errno));2755return-1;2756}2757}2758return0;2759}27602761static intrename_ref_available(const char*oldname,const char*newname)2762{2763struct string_list skip = STRING_LIST_INIT_NODUP;2764int ret;27652766string_list_insert(&skip, oldname);2767 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2768&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2769string_list_clear(&skip,0);2770return ret;2771}27722773static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2774const char*logmsg);27752776intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2777{2778unsigned char sha1[20], orig_sha1[20];2779int flag =0, logmoved =0;2780struct ref_lock *lock;2781struct stat loginfo;2782int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2783const char*symref = NULL;27842785if(log &&S_ISLNK(loginfo.st_mode))2786returnerror("reflog for%sis a symlink", oldrefname);27872788 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2789 orig_sha1, &flag);2790if(flag & REF_ISSYMREF)2791returnerror("refname%sis a symbolic ref, renaming it is not supported",2792 oldrefname);2793if(!symref)2794returnerror("refname%snot found", oldrefname);27952796if(!rename_ref_available(oldrefname, newrefname))2797return1;27982799if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2800returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2801 oldrefname,strerror(errno));28022803if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2804error("unable to delete old%s", oldrefname);2805goto rollback;2806}28072808if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2809delete_ref(newrefname, sha1, REF_NODEREF)) {2810if(errno==EISDIR) {2811if(remove_empty_directories(git_path("%s", newrefname))) {2812error("Directory not empty:%s", newrefname);2813goto rollback;2814}2815}else{2816error("unable to delete existing%s", newrefname);2817goto rollback;2818}2819}28202821if(log &&rename_tmp_log(newrefname))2822goto rollback;28232824 logmoved = log;28252826 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2827if(!lock) {2828error("unable to lock%sfor update", newrefname);2829goto rollback;2830}2831hashcpy(lock->old_sha1, orig_sha1);2832if(write_ref_sha1(lock, orig_sha1, logmsg)) {2833error("unable to write current sha1 into%s", newrefname);2834goto rollback;2835}28362837return0;28382839 rollback:2840 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2841if(!lock) {2842error("unable to lock%sfor rollback", oldrefname);2843goto rollbacklog;2844}28452846 flag = log_all_ref_updates;2847 log_all_ref_updates =0;2848if(write_ref_sha1(lock, orig_sha1, NULL))2849error("unable to write current sha1 into%s", oldrefname);2850 log_all_ref_updates = flag;28512852 rollbacklog:2853if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2854error("unable to restore logfile%sfrom%s:%s",2855 oldrefname, newrefname,strerror(errno));2856if(!logmoved && log &&2857rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2858error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2859 oldrefname,strerror(errno));28602861return1;2862}28632864static intclose_ref(struct ref_lock *lock)2865{2866if(close_lock_file(lock->lk))2867return-1;2868return0;2869}28702871static intcommit_ref(struct ref_lock *lock)2872{2873if(commit_lock_file(lock->lk))2874return-1;2875return0;2876}28772878/*2879 * copy the reflog message msg to buf, which has been allocated sufficiently2880 * large, while cleaning up the whitespaces. Especially, convert LF to space,2881 * because reflog file is one line per entry.2882 */2883static intcopy_msg(char*buf,const char*msg)2884{2885char*cp = buf;2886char c;2887int wasspace =1;28882889*cp++ ='\t';2890while((c = *msg++)) {2891if(wasspace &&isspace(c))2892continue;2893 wasspace =isspace(c);2894if(wasspace)2895 c =' ';2896*cp++ = c;2897}2898while(buf < cp &&isspace(cp[-1]))2899 cp--;2900*cp++ ='\n';2901return cp - buf;2902}29032904/* This function must set a meaningful errno on failure */2905intlog_ref_setup(const char*refname,char*logfile,int bufsize)2906{2907int logfd, oflags = O_APPEND | O_WRONLY;29082909git_snpath(logfile, bufsize,"logs/%s", refname);2910if(log_all_ref_updates &&2911(starts_with(refname,"refs/heads/") ||2912starts_with(refname,"refs/remotes/") ||2913starts_with(refname,"refs/notes/") ||2914!strcmp(refname,"HEAD"))) {2915if(safe_create_leading_directories(logfile) <0) {2916int save_errno = errno;2917error("unable to create directory for%s", logfile);2918 errno = save_errno;2919return-1;2920}2921 oflags |= O_CREAT;2922}29232924 logfd =open(logfile, oflags,0666);2925if(logfd <0) {2926if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2927return0;29282929if(errno == EISDIR) {2930if(remove_empty_directories(logfile)) {2931int save_errno = errno;2932error("There are still logs under '%s'",2933 logfile);2934 errno = save_errno;2935return-1;2936}2937 logfd =open(logfile, oflags,0666);2938}29392940if(logfd <0) {2941int save_errno = errno;2942error("Unable to append to%s:%s", logfile,2943strerror(errno));2944 errno = save_errno;2945return-1;2946}2947}29482949adjust_shared_perm(logfile);2950close(logfd);2951return0;2952}29532954static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2955const unsigned char*new_sha1,2956const char*committer,const char*msg)2957{2958int msglen, written;2959unsigned maxlen, len;2960char*logrec;29612962 msglen = msg ?strlen(msg) :0;2963 maxlen =strlen(committer) + msglen +100;2964 logrec =xmalloc(maxlen);2965 len =sprintf(logrec,"%s %s %s\n",2966sha1_to_hex(old_sha1),2967sha1_to_hex(new_sha1),2968 committer);2969if(msglen)2970 len +=copy_msg(logrec + len -1, msg) -1;29712972 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2973free(logrec);2974if(written != len)2975return-1;29762977return0;2978}29792980static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2981const unsigned char*new_sha1,const char*msg)2982{2983int logfd, result, oflags = O_APPEND | O_WRONLY;2984char log_file[PATH_MAX];29852986if(log_all_ref_updates <0)2987 log_all_ref_updates = !is_bare_repository();29882989 result =log_ref_setup(refname, log_file,sizeof(log_file));2990if(result)2991return result;29922993 logfd =open(log_file, oflags);2994if(logfd <0)2995return0;2996 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2997git_committer_info(0), msg);2998if(result) {2999int save_errno = errno;3000close(logfd);3001error("Unable to append to%s", log_file);3002 errno = save_errno;3003return-1;3004}3005if(close(logfd)) {3006int save_errno = errno;3007error("Unable to append to%s", log_file);3008 errno = save_errno;3009return-1;3010}3011return0;3012}30133014intis_branch(const char*refname)3015{3016return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3017}30183019/*3020 * Write sha1 into the ref specified by the lock. Make sure that errno3021 * is sane on error.3022 */3023static intwrite_ref_sha1(struct ref_lock *lock,3024const unsigned char*sha1,const char*logmsg)3025{3026static char term ='\n';3027struct object *o;30283029 o =parse_object(sha1);3030if(!o) {3031error("Trying to write ref%swith nonexistent object%s",3032 lock->ref_name,sha1_to_hex(sha1));3033unlock_ref(lock);3034 errno = EINVAL;3035return-1;3036}3037if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3038error("Trying to write non-commit object%sto branch%s",3039sha1_to_hex(sha1), lock->ref_name);3040unlock_ref(lock);3041 errno = EINVAL;3042return-1;3043}3044if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3045write_in_full(lock->lk->fd, &term,1) !=1||3046close_ref(lock) <0) {3047int save_errno = errno;3048error("Couldn't write%s", lock->lk->filename.buf);3049unlock_ref(lock);3050 errno = save_errno;3051return-1;3052}3053clear_loose_ref_cache(&ref_cache);3054if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3055(strcmp(lock->ref_name, lock->orig_ref_name) &&3056log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3057unlock_ref(lock);3058return-1;3059}3060if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3061/*3062 * Special hack: If a branch is updated directly and HEAD3063 * points to it (may happen on the remote side of a push3064 * for example) then logically the HEAD reflog should be3065 * updated too.3066 * A generic solution implies reverse symref information,3067 * but finding all symrefs pointing to the given branch3068 * would be rather costly for this rare event (the direct3069 * update of a branch) to be worth it. So let's cheat and3070 * check with HEAD only which should cover 99% of all usage3071 * scenarios (even 100% of the default ones).3072 */3073unsigned char head_sha1[20];3074int head_flag;3075const char*head_ref;3076 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3077 head_sha1, &head_flag);3078if(head_ref && (head_flag & REF_ISSYMREF) &&3079!strcmp(head_ref, lock->ref_name))3080log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3081}3082if(commit_ref(lock)) {3083error("Couldn't set%s", lock->ref_name);3084unlock_ref(lock);3085return-1;3086}3087unlock_ref(lock);3088return0;3089}30903091intcreate_symref(const char*ref_target,const char*refs_heads_master,3092const char*logmsg)3093{3094const char*lockpath;3095char ref[1000];3096int fd, len, written;3097char*git_HEAD =git_pathdup("%s", ref_target);3098unsigned char old_sha1[20], new_sha1[20];30993100if(logmsg &&read_ref(ref_target, old_sha1))3101hashclr(old_sha1);31023103if(safe_create_leading_directories(git_HEAD) <0)3104returnerror("unable to create directory for%s", git_HEAD);31053106#ifndef NO_SYMLINK_HEAD3107if(prefer_symlink_refs) {3108unlink(git_HEAD);3109if(!symlink(refs_heads_master, git_HEAD))3110goto done;3111fprintf(stderr,"no symlink - falling back to symbolic ref\n");3112}3113#endif31143115 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3116if(sizeof(ref) <= len) {3117error("refname too long:%s", refs_heads_master);3118goto error_free_return;3119}3120 lockpath =mkpath("%s.lock", git_HEAD);3121 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3122if(fd <0) {3123error("Unable to open%sfor writing", lockpath);3124goto error_free_return;3125}3126 written =write_in_full(fd, ref, len);3127if(close(fd) !=0|| written != len) {3128error("Unable to write to%s", lockpath);3129goto error_unlink_return;3130}3131if(rename(lockpath, git_HEAD) <0) {3132error("Unable to create%s", git_HEAD);3133goto error_unlink_return;3134}3135if(adjust_shared_perm(git_HEAD)) {3136error("Unable to fix permissions on%s", lockpath);3137 error_unlink_return:3138unlink_or_warn(lockpath);3139 error_free_return:3140free(git_HEAD);3141return-1;3142}31433144#ifndef NO_SYMLINK_HEAD3145 done:3146#endif3147if(logmsg && !read_ref(refs_heads_master, new_sha1))3148log_ref_write(ref_target, old_sha1, new_sha1, logmsg);31493150free(git_HEAD);3151return0;3152}31533154struct read_ref_at_cb {3155const char*refname;3156unsigned long at_time;3157int cnt;3158int reccnt;3159unsigned char*sha1;3160int found_it;31613162unsigned char osha1[20];3163unsigned char nsha1[20];3164int tz;3165unsigned long date;3166char**msg;3167unsigned long*cutoff_time;3168int*cutoff_tz;3169int*cutoff_cnt;3170};31713172static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3173const char*email,unsigned long timestamp,int tz,3174const char*message,void*cb_data)3175{3176struct read_ref_at_cb *cb = cb_data;31773178 cb->reccnt++;3179 cb->tz = tz;3180 cb->date = timestamp;31813182if(timestamp <= cb->at_time || cb->cnt ==0) {3183if(cb->msg)3184*cb->msg =xstrdup(message);3185if(cb->cutoff_time)3186*cb->cutoff_time = timestamp;3187if(cb->cutoff_tz)3188*cb->cutoff_tz = tz;3189if(cb->cutoff_cnt)3190*cb->cutoff_cnt = cb->reccnt -1;3191/*3192 * we have not yet updated cb->[n|o]sha1 so they still3193 * hold the values for the previous record.3194 */3195if(!is_null_sha1(cb->osha1)) {3196hashcpy(cb->sha1, nsha1);3197if(hashcmp(cb->osha1, nsha1))3198warning("Log for ref%shas gap after%s.",3199 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3200}3201else if(cb->date == cb->at_time)3202hashcpy(cb->sha1, nsha1);3203else if(hashcmp(nsha1, cb->sha1))3204warning("Log for ref%sunexpectedly ended on%s.",3205 cb->refname,show_date(cb->date, cb->tz,3206 DATE_RFC2822));3207hashcpy(cb->osha1, osha1);3208hashcpy(cb->nsha1, nsha1);3209 cb->found_it =1;3210return1;3211}3212hashcpy(cb->osha1, osha1);3213hashcpy(cb->nsha1, nsha1);3214if(cb->cnt >0)3215 cb->cnt--;3216return0;3217}32183219static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3220const char*email,unsigned long timestamp,3221int tz,const char*message,void*cb_data)3222{3223struct read_ref_at_cb *cb = cb_data;32243225if(cb->msg)3226*cb->msg =xstrdup(message);3227if(cb->cutoff_time)3228*cb->cutoff_time = timestamp;3229if(cb->cutoff_tz)3230*cb->cutoff_tz = tz;3231if(cb->cutoff_cnt)3232*cb->cutoff_cnt = cb->reccnt;3233hashcpy(cb->sha1, osha1);3234if(is_null_sha1(cb->sha1))3235hashcpy(cb->sha1, nsha1);3236/* We just want the first entry */3237return1;3238}32393240intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3241unsigned char*sha1,char**msg,3242unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3243{3244struct read_ref_at_cb cb;32453246memset(&cb,0,sizeof(cb));3247 cb.refname = refname;3248 cb.at_time = at_time;3249 cb.cnt = cnt;3250 cb.msg = msg;3251 cb.cutoff_time = cutoff_time;3252 cb.cutoff_tz = cutoff_tz;3253 cb.cutoff_cnt = cutoff_cnt;3254 cb.sha1 = sha1;32553256for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);32573258if(!cb.reccnt) {3259if(flags & GET_SHA1_QUIETLY)3260exit(128);3261else3262die("Log for%sis empty.", refname);3263}3264if(cb.found_it)3265return0;32663267for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);32683269return1;3270}32713272intreflog_exists(const char*refname)3273{3274struct stat st;32753276return!lstat(git_path("logs/%s", refname), &st) &&3277S_ISREG(st.st_mode);3278}32793280intdelete_reflog(const char*refname)3281{3282returnremove_path(git_path("logs/%s", refname));3283}32843285static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3286{3287unsigned char osha1[20], nsha1[20];3288char*email_end, *message;3289unsigned long timestamp;3290int tz;32913292/* old SP new SP name <email> SP time TAB msg LF */3293if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3294get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3295get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3296!(email_end =strchr(sb->buf +82,'>')) ||3297 email_end[1] !=' '||3298!(timestamp =strtoul(email_end +2, &message,10)) ||3299!message || message[0] !=' '||3300(message[1] !='+'&& message[1] !='-') ||3301!isdigit(message[2]) || !isdigit(message[3]) ||3302!isdigit(message[4]) || !isdigit(message[5]))3303return0;/* corrupt? */3304 email_end[1] ='\0';3305 tz =strtol(message +1, NULL,10);3306if(message[6] !='\t')3307 message +=6;3308else3309 message +=7;3310returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3311}33123313static char*find_beginning_of_line(char*bob,char*scan)3314{3315while(bob < scan && *(--scan) !='\n')3316;/* keep scanning backwards */3317/*3318 * Return either beginning of the buffer, or LF at the end of3319 * the previous line.3320 */3321return scan;3322}33233324intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3325{3326struct strbuf sb = STRBUF_INIT;3327FILE*logfp;3328long pos;3329int ret =0, at_tail =1;33303331 logfp =fopen(git_path("logs/%s", refname),"r");3332if(!logfp)3333return-1;33343335/* Jump to the end */3336if(fseek(logfp,0, SEEK_END) <0)3337returnerror("cannot seek back reflog for%s:%s",3338 refname,strerror(errno));3339 pos =ftell(logfp);3340while(!ret &&0< pos) {3341int cnt;3342size_t nread;3343char buf[BUFSIZ];3344char*endp, *scanp;33453346/* Fill next block from the end */3347 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3348if(fseek(logfp, pos - cnt, SEEK_SET))3349returnerror("cannot seek back reflog for%s:%s",3350 refname,strerror(errno));3351 nread =fread(buf, cnt,1, logfp);3352if(nread !=1)3353returnerror("cannot read%dbytes from reflog for%s:%s",3354 cnt, refname,strerror(errno));3355 pos -= cnt;33563357 scanp = endp = buf + cnt;3358if(at_tail && scanp[-1] =='\n')3359/* Looking at the final LF at the end of the file */3360 scanp--;3361 at_tail =0;33623363while(buf < scanp) {3364/*3365 * terminating LF of the previous line, or the beginning3366 * of the buffer.3367 */3368char*bp;33693370 bp =find_beginning_of_line(buf, scanp);33713372if(*bp =='\n') {3373/*3374 * The newline is the end of the previous line,3375 * so we know we have complete line starting3376 * at (bp + 1). Prefix it onto any prior data3377 * we collected for the line and process it.3378 */3379strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3380 scanp = bp;3381 endp = bp +1;3382 ret =show_one_reflog_ent(&sb, fn, cb_data);3383strbuf_reset(&sb);3384if(ret)3385break;3386}else if(!pos) {3387/*3388 * We are at the start of the buffer, and the3389 * start of the file; there is no previous3390 * line, and we have everything for this one.3391 * Process it, and we can end the loop.3392 */3393strbuf_splice(&sb,0,0, buf, endp - buf);3394 ret =show_one_reflog_ent(&sb, fn, cb_data);3395strbuf_reset(&sb);3396break;3397}33983399if(bp == buf) {3400/*3401 * We are at the start of the buffer, and there3402 * is more file to read backwards. Which means3403 * we are in the middle of a line. Note that we3404 * may get here even if *bp was a newline; that3405 * just means we are at the exact end of the3406 * previous line, rather than some spot in the3407 * middle.3408 *3409 * Save away what we have to be combined with3410 * the data from the next read.3411 */3412strbuf_splice(&sb,0,0, buf, endp - buf);3413break;3414}3415}34163417}3418if(!ret && sb.len)3419die("BUG: reverse reflog parser had leftover data");34203421fclose(logfp);3422strbuf_release(&sb);3423return ret;3424}34253426intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3427{3428FILE*logfp;3429struct strbuf sb = STRBUF_INIT;3430int ret =0;34313432 logfp =fopen(git_path("logs/%s", refname),"r");3433if(!logfp)3434return-1;34353436while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3437 ret =show_one_reflog_ent(&sb, fn, cb_data);3438fclose(logfp);3439strbuf_release(&sb);3440return ret;3441}3442/*3443 * Call fn for each reflog in the namespace indicated by name. name3444 * must be empty or end with '/'. Name will be used as a scratch3445 * space, but its contents will be restored before return.3446 */3447static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3448{3449DIR*d =opendir(git_path("logs/%s", name->buf));3450int retval =0;3451struct dirent *de;3452int oldlen = name->len;34533454if(!d)3455return name->len ? errno :0;34563457while((de =readdir(d)) != NULL) {3458struct stat st;34593460if(de->d_name[0] =='.')3461continue;3462if(ends_with(de->d_name,".lock"))3463continue;3464strbuf_addstr(name, de->d_name);3465if(stat(git_path("logs/%s", name->buf), &st) <0) {3466;/* silently ignore */3467}else{3468if(S_ISDIR(st.st_mode)) {3469strbuf_addch(name,'/');3470 retval =do_for_each_reflog(name, fn, cb_data);3471}else{3472unsigned char sha1[20];3473if(read_ref_full(name->buf,0, sha1, NULL))3474 retval =error("bad ref for%s", name->buf);3475else3476 retval =fn(name->buf, sha1,0, cb_data);3477}3478if(retval)3479break;3480}3481strbuf_setlen(name, oldlen);3482}3483closedir(d);3484return retval;3485}34863487intfor_each_reflog(each_ref_fn fn,void*cb_data)3488{3489int retval;3490struct strbuf name;3491strbuf_init(&name, PATH_MAX);3492 retval =do_for_each_reflog(&name, fn, cb_data);3493strbuf_release(&name);3494return retval;3495}34963497/**3498 * Information needed for a single ref update. Set new_sha1 to the new3499 * value or to null_sha1 to delete the ref. To check the old value3500 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3501 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3502 * not exist before update.3503 */3504struct ref_update {3505/*3506 * If (flags & REF_HAVE_NEW), set the reference to this value:3507 */3508unsigned char new_sha1[20];3509/*3510 * If (flags & REF_HAVE_OLD), check that the reference3511 * previously had this value:3512 */3513unsigned char old_sha1[20];3514/*3515 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3516 * REF_DELETING, and REF_ISPRUNING:3517 */3518unsigned int flags;3519struct ref_lock *lock;3520int type;3521char*msg;3522const char refname[FLEX_ARRAY];3523};35243525/*3526 * Transaction states.3527 * OPEN: The transaction is in a valid state and can accept new updates.3528 * An OPEN transaction can be committed.3529 * CLOSED: A closed transaction is no longer active and no other operations3530 * than free can be used on it in this state.3531 * A transaction can either become closed by successfully committing3532 * an active transaction or if there is a failure while building3533 * the transaction thus rendering it failed/inactive.3534 */3535enum ref_transaction_state {3536 REF_TRANSACTION_OPEN =0,3537 REF_TRANSACTION_CLOSED =13538};35393540/*3541 * Data structure for holding a reference transaction, which can3542 * consist of checks and updates to multiple references, carried out3543 * as atomically as possible. This structure is opaque to callers.3544 */3545struct ref_transaction {3546struct ref_update **updates;3547size_t alloc;3548size_t nr;3549enum ref_transaction_state state;3550};35513552struct ref_transaction *ref_transaction_begin(struct strbuf *err)3553{3554assert(err);35553556returnxcalloc(1,sizeof(struct ref_transaction));3557}35583559voidref_transaction_free(struct ref_transaction *transaction)3560{3561int i;35623563if(!transaction)3564return;35653566for(i =0; i < transaction->nr; i++) {3567free(transaction->updates[i]->msg);3568free(transaction->updates[i]);3569}3570free(transaction->updates);3571free(transaction);3572}35733574static struct ref_update *add_update(struct ref_transaction *transaction,3575const char*refname)3576{3577size_t len =strlen(refname);3578struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);35793580strcpy((char*)update->refname, refname);3581ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3582 transaction->updates[transaction->nr++] = update;3583return update;3584}35853586intref_transaction_update(struct ref_transaction *transaction,3587const char*refname,3588const unsigned char*new_sha1,3589const unsigned char*old_sha1,3590unsigned int flags,const char*msg,3591struct strbuf *err)3592{3593struct ref_update *update;35943595assert(err);35963597if(transaction->state != REF_TRANSACTION_OPEN)3598die("BUG: update called for transaction that is not open");35993600if(new_sha1 && !is_null_sha1(new_sha1) &&3601check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3602strbuf_addf(err,"refusing to update ref with bad name%s",3603 refname);3604return-1;3605}36063607 update =add_update(transaction, refname);3608if(new_sha1) {3609hashcpy(update->new_sha1, new_sha1);3610 flags |= REF_HAVE_NEW;3611}3612if(old_sha1) {3613hashcpy(update->old_sha1, old_sha1);3614 flags |= REF_HAVE_OLD;3615}3616 update->flags = flags;3617if(msg)3618 update->msg =xstrdup(msg);3619return0;3620}36213622intref_transaction_create(struct ref_transaction *transaction,3623const char*refname,3624const unsigned char*new_sha1,3625unsigned int flags,const char*msg,3626struct strbuf *err)3627{3628if(!new_sha1 ||is_null_sha1(new_sha1))3629die("BUG: create called without valid new_sha1");3630returnref_transaction_update(transaction, refname, new_sha1,3631 null_sha1, flags, msg, err);3632}36333634intref_transaction_delete(struct ref_transaction *transaction,3635const char*refname,3636const unsigned char*old_sha1,3637unsigned int flags,const char*msg,3638struct strbuf *err)3639{3640if(old_sha1 &&is_null_sha1(old_sha1))3641die("BUG: delete called with old_sha1 set to zeros");3642returnref_transaction_update(transaction, refname,3643 null_sha1, old_sha1,3644 flags, msg, err);3645}36463647intref_transaction_verify(struct ref_transaction *transaction,3648const char*refname,3649const unsigned char*old_sha1,3650unsigned int flags,3651struct strbuf *err)3652{3653if(!old_sha1)3654die("BUG: verify called with old_sha1 set to NULL");3655returnref_transaction_update(transaction, refname,3656 NULL, old_sha1,3657 flags, NULL, err);3658}36593660intupdate_ref(const char*msg,const char*refname,3661const unsigned char*new_sha1,const unsigned char*old_sha1,3662unsigned int flags,enum action_on_err onerr)3663{3664struct ref_transaction *t;3665struct strbuf err = STRBUF_INIT;36663667 t =ref_transaction_begin(&err);3668if(!t ||3669ref_transaction_update(t, refname, new_sha1, old_sha1,3670 flags, msg, &err) ||3671ref_transaction_commit(t, &err)) {3672const char*str ="update_ref failed for ref '%s':%s";36733674ref_transaction_free(t);3675switch(onerr) {3676case UPDATE_REFS_MSG_ON_ERR:3677error(str, refname, err.buf);3678break;3679case UPDATE_REFS_DIE_ON_ERR:3680die(str, refname, err.buf);3681break;3682case UPDATE_REFS_QUIET_ON_ERR:3683break;3684}3685strbuf_release(&err);3686return1;3687}3688strbuf_release(&err);3689ref_transaction_free(t);3690return0;3691}36923693static intref_update_compare(const void*r1,const void*r2)3694{3695const struct ref_update *const*u1 = r1;3696const struct ref_update *const*u2 = r2;3697returnstrcmp((*u1)->refname, (*u2)->refname);3698}36993700static intref_update_reject_duplicates(struct ref_update **updates,int n,3701struct strbuf *err)3702{3703int i;37043705assert(err);37063707for(i =1; i < n; i++)3708if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3709strbuf_addf(err,3710"Multiple updates for ref '%s' not allowed.",3711 updates[i]->refname);3712return1;3713}3714return0;3715}37163717intref_transaction_commit(struct ref_transaction *transaction,3718struct strbuf *err)3719{3720int ret =0, i;3721int n = transaction->nr;3722struct ref_update **updates = transaction->updates;3723struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3724struct string_list_item *ref_to_delete;37253726assert(err);37273728if(transaction->state != REF_TRANSACTION_OPEN)3729die("BUG: commit called for transaction that is not open");37303731if(!n) {3732 transaction->state = REF_TRANSACTION_CLOSED;3733return0;3734}37353736/* Copy, sort, and reject duplicate refs */3737qsort(updates, n,sizeof(*updates), ref_update_compare);3738if(ref_update_reject_duplicates(updates, n, err)) {3739 ret = TRANSACTION_GENERIC_ERROR;3740goto cleanup;3741}37423743/* Acquire all locks while verifying old values */3744for(i =0; i < n; i++) {3745struct ref_update *update = updates[i];3746unsigned int flags = update->flags;37473748if((flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3749 flags |= REF_DELETING;3750 update->lock =lock_ref_sha1_basic(3751 update->refname,3752((update->flags & REF_HAVE_OLD) ?3753 update->old_sha1 : NULL),3754 NULL,3755 flags,3756&update->type);3757if(!update->lock) {3758 ret = (errno == ENOTDIR)3759? TRANSACTION_NAME_CONFLICT3760: TRANSACTION_GENERIC_ERROR;3761strbuf_addf(err,"Cannot lock the ref '%s'.",3762 update->refname);3763goto cleanup;3764}3765}37663767/* Perform updates first so live commits remain referenced */3768for(i =0; i < n; i++) {3769struct ref_update *update = updates[i];3770int flags = update->flags;37713772if((flags & REF_HAVE_NEW) && !is_null_sha1(update->new_sha1)) {3773int overwriting_symref = ((update->type & REF_ISSYMREF) &&3774(update->flags & REF_NODEREF));37753776if(!overwriting_symref3777&& !hashcmp(update->lock->old_sha1, update->new_sha1)) {3778/*3779 * The reference already has the desired3780 * value, so we don't need to write it.3781 */3782unlock_ref(update->lock);3783 update->lock = NULL;3784}else if(write_ref_sha1(update->lock, update->new_sha1,3785 update->msg)) {3786 update->lock = NULL;/* freed by write_ref_sha1 */3787strbuf_addf(err,"Cannot update the ref '%s'.",3788 update->refname);3789 ret = TRANSACTION_GENERIC_ERROR;3790goto cleanup;3791}else{3792/* freed by write_ref_sha1(): */3793 update->lock = NULL;3794}3795}3796}37973798/* Perform deletes now that updates are safely completed */3799for(i =0; i < n; i++) {3800struct ref_update *update = updates[i];3801int flags = update->flags;38023803if((flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1)) {3804if(delete_ref_loose(update->lock, update->type, err)) {3805 ret = TRANSACTION_GENERIC_ERROR;3806goto cleanup;3807}38083809if(!(flags & REF_ISPRUNING))3810string_list_append(&refs_to_delete,3811 update->lock->ref_name);3812}3813}38143815if(repack_without_refs(&refs_to_delete, err)) {3816 ret = TRANSACTION_GENERIC_ERROR;3817goto cleanup;3818}3819for_each_string_list_item(ref_to_delete, &refs_to_delete)3820unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3821clear_loose_ref_cache(&ref_cache);38223823cleanup:3824 transaction->state = REF_TRANSACTION_CLOSED;38253826for(i =0; i < n; i++)3827if(updates[i]->lock)3828unlock_ref(updates[i]->lock);3829string_list_clear(&refs_to_delete,0);3830return ret;3831}38323833char*shorten_unambiguous_ref(const char*refname,int strict)3834{3835int i;3836static char**scanf_fmts;3837static int nr_rules;3838char*short_name;38393840if(!nr_rules) {3841/*3842 * Pre-generate scanf formats from ref_rev_parse_rules[].3843 * Generate a format suitable for scanf from a3844 * ref_rev_parse_rules rule by interpolating "%s" at the3845 * location of the "%.*s".3846 */3847size_t total_len =0;3848size_t offset =0;38493850/* the rule list is NULL terminated, count them first */3851for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3852/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3853 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38543855 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38563857 offset =0;3858for(i =0; i < nr_rules; i++) {3859assert(offset < total_len);3860 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3861 offset +=snprintf(scanf_fmts[i], total_len - offset,3862 ref_rev_parse_rules[i],2,"%s") +1;3863}3864}38653866/* bail out if there are no rules */3867if(!nr_rules)3868returnxstrdup(refname);38693870/* buffer for scanf result, at most refname must fit */3871 short_name =xstrdup(refname);38723873/* skip first rule, it will always match */3874for(i = nr_rules -1; i >0; --i) {3875int j;3876int rules_to_fail = i;3877int short_name_len;38783879if(1!=sscanf(refname, scanf_fmts[i], short_name))3880continue;38813882 short_name_len =strlen(short_name);38833884/*3885 * in strict mode, all (except the matched one) rules3886 * must fail to resolve to a valid non-ambiguous ref3887 */3888if(strict)3889 rules_to_fail = nr_rules;38903891/*3892 * check if the short name resolves to a valid ref,3893 * but use only rules prior to the matched one3894 */3895for(j =0; j < rules_to_fail; j++) {3896const char*rule = ref_rev_parse_rules[j];3897char refname[PATH_MAX];38983899/* skip matched rule */3900if(i == j)3901continue;39023903/*3904 * the short name is ambiguous, if it resolves3905 * (with this previous rule) to a valid ref3906 * read_ref() returns 0 on success3907 */3908mksnpath(refname,sizeof(refname),3909 rule, short_name_len, short_name);3910if(ref_exists(refname))3911break;3912}39133914/*3915 * short name is non-ambiguous if all previous rules3916 * haven't resolved to a valid ref3917 */3918if(j == rules_to_fail)3919return short_name;3920}39213922free(short_name);3923returnxstrdup(refname);3924}39253926static struct string_list *hide_refs;39273928intparse_hide_refs_config(const char*var,const char*value,const char*section)3929{3930if(!strcmp("transfer.hiderefs", var) ||3931/* NEEDSWORK: use parse_config_key() once both are merged */3932(starts_with(var, section) && var[strlen(section)] =='.'&&3933!strcmp(var +strlen(section),".hiderefs"))) {3934char*ref;3935int len;39363937if(!value)3938returnconfig_error_nonbool(var);3939 ref =xstrdup(value);3940 len =strlen(ref);3941while(len && ref[len -1] =='/')3942 ref[--len] ='\0';3943if(!hide_refs) {3944 hide_refs =xcalloc(1,sizeof(*hide_refs));3945 hide_refs->strdup_strings =1;3946}3947string_list_append(hide_refs, ref);3948}3949return0;3950}39513952intref_is_hidden(const char*refname)3953{3954struct string_list_item *item;39553956if(!hide_refs)3957return0;3958for_each_string_list_item(item, hide_refs) {3959int len;3960if(!starts_with(refname, item->string))3961continue;3962 len =strlen(item->string);3963if(!refname[len] || refname[len] =='/')3964return1;3965}3966return0;3967}39683969struct expire_reflog_cb {3970unsigned int flags;3971 reflog_expiry_should_prune_fn *should_prune_fn;3972void*policy_cb;3973FILE*newlog;3974unsigned char last_kept_sha1[20];3975};39763977static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3978const char*email,unsigned long timestamp,int tz,3979const char*message,void*cb_data)3980{3981struct expire_reflog_cb *cb = cb_data;3982struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;39833984if(cb->flags & EXPIRE_REFLOGS_REWRITE)3985 osha1 = cb->last_kept_sha1;39863987if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3988 message, policy_cb)) {3989if(!cb->newlog)3990printf("would prune%s", message);3991else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3992printf("prune%s", message);3993}else{3994if(cb->newlog) {3995fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3996sha1_to_hex(osha1),sha1_to_hex(nsha1),3997 email, timestamp, tz, message);3998hashcpy(cb->last_kept_sha1, nsha1);3999}4000if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4001printf("keep%s", message);4002}4003return0;4004}40054006intreflog_expire(const char*refname,const unsigned char*sha1,4007unsigned int flags,4008 reflog_expiry_prepare_fn prepare_fn,4009 reflog_expiry_should_prune_fn should_prune_fn,4010 reflog_expiry_cleanup_fn cleanup_fn,4011void*policy_cb_data)4012{4013static struct lock_file reflog_lock;4014struct expire_reflog_cb cb;4015struct ref_lock *lock;4016char*log_file;4017int status =0;4018int type;40194020memset(&cb,0,sizeof(cb));4021 cb.flags = flags;4022 cb.policy_cb = policy_cb_data;4023 cb.should_prune_fn = should_prune_fn;40244025/*4026 * The reflog file is locked by holding the lock on the4027 * reference itself, plus we might need to update the4028 * reference if --updateref was specified:4029 */4030 lock =lock_ref_sha1_basic(refname, sha1, NULL,0, &type);4031if(!lock)4032returnerror("cannot lock ref '%s'", refname);4033if(!reflog_exists(refname)) {4034unlock_ref(lock);4035return0;4036}40374038 log_file =git_pathdup("logs/%s", refname);4039if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4040/*4041 * Even though holding $GIT_DIR/logs/$reflog.lock has4042 * no locking implications, we use the lock_file4043 * machinery here anyway because it does a lot of the4044 * work we need, including cleaning up if the program4045 * exits unexpectedly.4046 */4047if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4048struct strbuf err = STRBUF_INIT;4049unable_to_lock_message(log_file, errno, &err);4050error("%s", err.buf);4051strbuf_release(&err);4052goto failure;4053}4054 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4055if(!cb.newlog) {4056error("cannot fdopen%s(%s)",4057 reflog_lock.filename.buf,strerror(errno));4058goto failure;4059}4060}40614062(*prepare_fn)(refname, sha1, cb.policy_cb);4063for_each_reflog_ent(refname, expire_reflog_ent, &cb);4064(*cleanup_fn)(cb.policy_cb);40654066if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4067/*4068 * It doesn't make sense to adjust a reference pointed4069 * to by a symbolic ref based on expiring entries in4070 * the symbolic reference's reflog. Nor can we update4071 * a reference if there are no remaining reflog4072 * entries.4073 */4074int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4075!(type & REF_ISSYMREF) &&4076!is_null_sha1(cb.last_kept_sha1);40774078if(close_lock_file(&reflog_lock)) {4079 status |=error("couldn't write%s:%s", log_file,4080strerror(errno));4081}else if(update &&4082(write_in_full(lock->lk->fd,4083sha1_to_hex(cb.last_kept_sha1),40) !=40||4084write_str_in_full(lock->lk->fd,"\n") !=1||4085close_ref(lock) <0)) {4086 status |=error("couldn't write%s",4087 lock->lk->filename.buf);4088rollback_lock_file(&reflog_lock);4089}else if(commit_lock_file(&reflog_lock)) {4090 status |=error("unable to commit reflog '%s' (%s)",4091 log_file,strerror(errno));4092}else if(update &&commit_ref(lock)) {4093 status |=error("couldn't set%s", lock->ref_name);4094}4095}4096free(log_file);4097unlock_ref(lock);4098return status;40994100 failure:4101rollback_lock_file(&reflog_lock);4102free(log_file);4103unlock_ref(lock);4104return-1;4105}