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]; 14int lock_fd; 15int force_write; 16}; 17 18/* 19 * How to handle various characters in refnames: 20 * 0: An acceptable character for refs 21 * 1: End-of-component 22 * 2: ., look for a preceding . to reject .. in refs 23 * 3: {, look for a preceding @ to reject @{ in refs 24 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag to ref_transaction_delete when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Try to read one refname component from the front of refname. 51 * Return the length of the component found, or -1 if the component is 52 * not legal. It is legal if it is something reasonable to have under 53 * ".git/refs/"; We do not like it if: 54 * 55 * - any path component of it begins with ".", or 56 * - it has double dots "..", or 57 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 58 * - it ends with a "/". 59 * - it ends with ".lock" 60 * - it contains a "\" (backslash) 61 */ 62static intcheck_refname_component(const char*refname,int flags) 63{ 64const char*cp; 65char last ='\0'; 66 67for(cp = refname; ; cp++) { 68int ch = *cp &255; 69unsigned char disp = refname_disposition[ch]; 70switch(disp) { 71case1: 72goto out; 73case2: 74if(last =='.') 75return-1;/* Refname contains "..". */ 76break; 77case3: 78if(last =='@') 79return-1;/* Refname contains "@{". */ 80break; 81case4: 82return-1; 83} 84 last = ch; 85} 86out: 87if(cp == refname) 88return0;/* Component has zero length. */ 89if(refname[0] =='.') 90return-1;/* Component starts with '.'. */ 91if(cp - refname >= LOCK_SUFFIX_LEN && 92!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 93return-1;/* Refname ends with ".lock". */ 94return cp - refname; 95} 96 97intcheck_refname_format(const char*refname,int flags) 98{ 99int component_len, component_count =0; 100 101if(!strcmp(refname,"@")) 102/* Refname is a single character '@'. */ 103return-1; 104 105while(1) { 106/* We are at the start of a path component. */ 107 component_len =check_refname_component(refname, flags); 108if(component_len <=0) { 109if((flags & REFNAME_REFSPEC_PATTERN) && 110 refname[0] =='*'&& 111(refname[1] =='\0'|| refname[1] =='/')) { 112/* Accept one wildcard as a full refname component. */ 113 flags &= ~REFNAME_REFSPEC_PATTERN; 114 component_len =1; 115}else{ 116return-1; 117} 118} 119 component_count++; 120if(refname[component_len] =='\0') 121break; 122/* Skip to next component. */ 123 refname += component_len +1; 124} 125 126if(refname[component_len -1] =='.') 127return-1;/* Refname ends with '.'. */ 128if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 129return-1;/* Refname has only one component. */ 130return0; 131} 132 133struct ref_entry; 134 135/* 136 * Information used (along with the information in ref_entry) to 137 * describe a single cached reference. This data structure only 138 * occurs embedded in a union in struct ref_entry, and only when 139 * (ref_entry->flag & REF_DIR) is zero. 140 */ 141struct ref_value { 142/* 143 * The name of the object to which this reference resolves 144 * (which may be a tag object). If REF_ISBROKEN, this is 145 * null. If REF_ISSYMREF, then this is the name of the object 146 * referred to by the last reference in the symlink chain. 147 */ 148unsigned char sha1[20]; 149 150/* 151 * If REF_KNOWS_PEELED, then this field holds the peeled value 152 * of this reference, or null if the reference is known not to 153 * be peelable. See the documentation for peel_ref() for an 154 * exact definition of "peelable". 155 */ 156unsigned char peeled[20]; 157}; 158 159struct ref_cache; 160 161/* 162 * Information used (along with the information in ref_entry) to 163 * describe a level in the hierarchy of references. This data 164 * structure only occurs embedded in a union in struct ref_entry, and 165 * only when (ref_entry.flag & REF_DIR) is set. In that case, 166 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 167 * in the directory have already been read: 168 * 169 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 170 * or packed references, already read. 171 * 172 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 173 * references that hasn't been read yet (nor has any of its 174 * subdirectories). 175 * 176 * Entries within a directory are stored within a growable array of 177 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 178 * sorted are sorted by their component name in strcmp() order and the 179 * remaining entries are unsorted. 180 * 181 * Loose references are read lazily, one directory at a time. When a 182 * directory of loose references is read, then all of the references 183 * in that directory are stored, and REF_INCOMPLETE stubs are created 184 * for any subdirectories, but the subdirectories themselves are not 185 * read. The reading is triggered by get_ref_dir(). 186 */ 187struct ref_dir { 188int nr, alloc; 189 190/* 191 * Entries with index 0 <= i < sorted are sorted by name. New 192 * entries are appended to the list unsorted, and are sorted 193 * only when required; thus we avoid the need to sort the list 194 * after the addition of every reference. 195 */ 196int sorted; 197 198/* A pointer to the ref_cache that contains this ref_dir. */ 199struct ref_cache *ref_cache; 200 201struct ref_entry **entries; 202}; 203 204/* 205 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 206 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 207 * public values; see refs.h. 208 */ 209 210/* 211 * The field ref_entry->u.value.peeled of this value entry contains 212 * the correct peeled value for the reference, which might be 213 * null_sha1 if the reference is not a tag or if it is broken. 214 */ 215#define REF_KNOWS_PEELED 0x10 216 217/* ref_entry represents a directory of references */ 218#define REF_DIR 0x20 219 220/* 221 * Entry has not yet been read from disk (used only for REF_DIR 222 * entries representing loose references) 223 */ 224#define REF_INCOMPLETE 0x40 225 226/* 227 * A ref_entry represents either a reference or a "subdirectory" of 228 * references. 229 * 230 * Each directory in the reference namespace is represented by a 231 * ref_entry with (flags & REF_DIR) set and containing a subdir member 232 * that holds the entries in that directory that have been read so 233 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 234 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 235 * used for loose reference directories. 236 * 237 * References are represented by a ref_entry with (flags & REF_DIR) 238 * unset and a value member that describes the reference's value. The 239 * flag member is at the ref_entry level, but it is also needed to 240 * interpret the contents of the value field (in other words, a 241 * ref_value object is not very much use without the enclosing 242 * ref_entry). 243 * 244 * Reference names cannot end with slash and directories' names are 245 * always stored with a trailing slash (except for the top-level 246 * directory, which is always denoted by ""). This has two nice 247 * consequences: (1) when the entries in each subdir are sorted 248 * lexicographically by name (as they usually are), the references in 249 * a whole tree can be generated in lexicographic order by traversing 250 * the tree in left-to-right, depth-first order; (2) the names of 251 * references and subdirectories cannot conflict, and therefore the 252 * presence of an empty subdirectory does not block the creation of a 253 * similarly-named reference. (The fact that reference names with the 254 * same leading components can conflict *with each other* is a 255 * separate issue that is regulated by is_refname_available().) 256 * 257 * Please note that the name field contains the fully-qualified 258 * reference (or subdirectory) name. Space could be saved by only 259 * storing the relative names. But that would require the full names 260 * to be generated on the fly when iterating in do_for_each_ref(), and 261 * would break callback functions, who have always been able to assume 262 * that the name strings that they are passed will not be freed during 263 * the iteration. 264 */ 265struct ref_entry { 266unsigned char flag;/* ISSYMREF? ISPACKED? */ 267union{ 268struct ref_value value;/* if not (flags&REF_DIR) */ 269struct ref_dir subdir;/* if (flags&REF_DIR) */ 270} u; 271/* 272 * The full name of the reference (e.g., "refs/heads/master") 273 * or the full name of the directory with a trailing slash 274 * (e.g., "refs/heads/"): 275 */ 276char name[FLEX_ARRAY]; 277}; 278 279static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 280 281static struct ref_dir *get_ref_dir(struct ref_entry *entry) 282{ 283struct ref_dir *dir; 284assert(entry->flag & REF_DIR); 285 dir = &entry->u.subdir; 286if(entry->flag & REF_INCOMPLETE) { 287read_loose_refs(entry->name, dir); 288 entry->flag &= ~REF_INCOMPLETE; 289} 290return dir; 291} 292 293/* 294 * Check if a refname is safe. 295 * For refs that start with "refs/" we consider it safe as long they do 296 * not try to resolve to outside of refs/. 297 * 298 * For all other refs we only consider them safe iff they only contain 299 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 300 * "config"). 301 */ 302static intrefname_is_safe(const char*refname) 303{ 304if(starts_with(refname,"refs/")) { 305char*buf; 306int result; 307 308 buf =xmalloc(strlen(refname) +1); 309/* 310 * Does the refname try to escape refs/? 311 * For example: refs/foo/../bar is safe but refs/foo/../../bar 312 * is not. 313 */ 314 result = !normalize_path_copy(buf, refname +strlen("refs/")); 315free(buf); 316return result; 317} 318while(*refname) { 319if(!isupper(*refname) && *refname !='_') 320return0; 321 refname++; 322} 323return1; 324} 325 326static struct ref_entry *create_ref_entry(const char*refname, 327const unsigned char*sha1,int flag, 328int check_name) 329{ 330int len; 331struct ref_entry *ref; 332 333if(check_name && 334check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 335die("Reference has invalid format: '%s'", refname); 336if(!check_name && !refname_is_safe(refname)) 337die("Reference has invalid name: '%s'", refname); 338 len =strlen(refname) +1; 339 ref =xmalloc(sizeof(struct ref_entry) + len); 340hashcpy(ref->u.value.sha1, sha1); 341hashclr(ref->u.value.peeled); 342memcpy(ref->name, refname, len); 343 ref->flag = flag; 344return ref; 345} 346 347static voidclear_ref_dir(struct ref_dir *dir); 348 349static voidfree_ref_entry(struct ref_entry *entry) 350{ 351if(entry->flag & REF_DIR) { 352/* 353 * Do not use get_ref_dir() here, as that might 354 * trigger the reading of loose refs. 355 */ 356clear_ref_dir(&entry->u.subdir); 357} 358free(entry); 359} 360 361/* 362 * Add a ref_entry to the end of dir (unsorted). Entry is always 363 * stored directly in dir; no recursion into subdirectories is 364 * done. 365 */ 366static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 367{ 368ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 369 dir->entries[dir->nr++] = entry; 370/* optimize for the case that entries are added in order */ 371if(dir->nr ==1|| 372(dir->nr == dir->sorted +1&& 373strcmp(dir->entries[dir->nr -2]->name, 374 dir->entries[dir->nr -1]->name) <0)) 375 dir->sorted = dir->nr; 376} 377 378/* 379 * Clear and free all entries in dir, recursively. 380 */ 381static voidclear_ref_dir(struct ref_dir *dir) 382{ 383int i; 384for(i =0; i < dir->nr; i++) 385free_ref_entry(dir->entries[i]); 386free(dir->entries); 387 dir->sorted = dir->nr = dir->alloc =0; 388 dir->entries = NULL; 389} 390 391/* 392 * Create a struct ref_entry object for the specified dirname. 393 * dirname is the name of the directory with a trailing slash (e.g., 394 * "refs/heads/") or "" for the top-level directory. 395 */ 396static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 397const char*dirname,size_t len, 398int incomplete) 399{ 400struct ref_entry *direntry; 401 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 402memcpy(direntry->name, dirname, len); 403 direntry->name[len] ='\0'; 404 direntry->u.subdir.ref_cache = ref_cache; 405 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 406return direntry; 407} 408 409static intref_entry_cmp(const void*a,const void*b) 410{ 411struct ref_entry *one = *(struct ref_entry **)a; 412struct ref_entry *two = *(struct ref_entry **)b; 413returnstrcmp(one->name, two->name); 414} 415 416static voidsort_ref_dir(struct ref_dir *dir); 417 418struct string_slice { 419size_t len; 420const char*str; 421}; 422 423static intref_entry_cmp_sslice(const void*key_,const void*ent_) 424{ 425const struct string_slice *key = key_; 426const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 427int cmp =strncmp(key->str, ent->name, key->len); 428if(cmp) 429return cmp; 430return'\0'- (unsigned char)ent->name[key->len]; 431} 432 433/* 434 * Return the index of the entry with the given refname from the 435 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 436 * no such entry is found. dir must already be complete. 437 */ 438static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 439{ 440struct ref_entry **r; 441struct string_slice key; 442 443if(refname == NULL || !dir->nr) 444return-1; 445 446sort_ref_dir(dir); 447 key.len = len; 448 key.str = refname; 449 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 450 ref_entry_cmp_sslice); 451 452if(r == NULL) 453return-1; 454 455return r - dir->entries; 456} 457 458/* 459 * Search for a directory entry directly within dir (without 460 * recursing). Sort dir if necessary. subdirname must be a directory 461 * name (i.e., end in '/'). If mkdir is set, then create the 462 * directory if it is missing; otherwise, return NULL if the desired 463 * directory cannot be found. dir must already be complete. 464 */ 465static struct ref_dir *search_for_subdir(struct ref_dir *dir, 466const char*subdirname,size_t len, 467int mkdir) 468{ 469int entry_index =search_ref_dir(dir, subdirname, len); 470struct ref_entry *entry; 471if(entry_index == -1) { 472if(!mkdir) 473return NULL; 474/* 475 * Since dir is complete, the absence of a subdir 476 * means that the subdir really doesn't exist; 477 * therefore, create an empty record for it but mark 478 * the record complete. 479 */ 480 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 481add_entry_to_dir(dir, entry); 482}else{ 483 entry = dir->entries[entry_index]; 484} 485returnget_ref_dir(entry); 486} 487 488/* 489 * If refname is a reference name, find the ref_dir within the dir 490 * tree that should hold refname. If refname is a directory name 491 * (i.e., ends in '/'), then return that ref_dir itself. dir must 492 * represent the top-level directory and must already be complete. 493 * Sort ref_dirs and recurse into subdirectories as necessary. If 494 * mkdir is set, then create any missing directories; otherwise, 495 * return NULL if the desired directory cannot be found. 496 */ 497static struct ref_dir *find_containing_dir(struct ref_dir *dir, 498const char*refname,int mkdir) 499{ 500const char*slash; 501for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 502size_t dirnamelen = slash - refname +1; 503struct ref_dir *subdir; 504 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 505if(!subdir) { 506 dir = NULL; 507break; 508} 509 dir = subdir; 510} 511 512return dir; 513} 514 515/* 516 * Find the value entry with the given name in dir, sorting ref_dirs 517 * and recursing into subdirectories as necessary. If the name is not 518 * found or it corresponds to a directory entry, return NULL. 519 */ 520static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 521{ 522int entry_index; 523struct ref_entry *entry; 524 dir =find_containing_dir(dir, refname,0); 525if(!dir) 526return NULL; 527 entry_index =search_ref_dir(dir, refname,strlen(refname)); 528if(entry_index == -1) 529return NULL; 530 entry = dir->entries[entry_index]; 531return(entry->flag & REF_DIR) ? NULL : entry; 532} 533 534/* 535 * Remove the entry with the given name from dir, recursing into 536 * subdirectories as necessary. If refname is the name of a directory 537 * (i.e., ends with '/'), then remove the directory and its contents. 538 * If the removal was successful, return the number of entries 539 * remaining in the directory entry that contained the deleted entry. 540 * If the name was not found, return -1. Please note that this 541 * function only deletes the entry from the cache; it does not delete 542 * it from the filesystem or ensure that other cache entries (which 543 * might be symbolic references to the removed entry) are updated. 544 * Nor does it remove any containing dir entries that might be made 545 * empty by the removal. dir must represent the top-level directory 546 * and must already be complete. 547 */ 548static intremove_entry(struct ref_dir *dir,const char*refname) 549{ 550int refname_len =strlen(refname); 551int entry_index; 552struct ref_entry *entry; 553int is_dir = refname[refname_len -1] =='/'; 554if(is_dir) { 555/* 556 * refname represents a reference directory. Remove 557 * the trailing slash; otherwise we will get the 558 * directory *representing* refname rather than the 559 * one *containing* it. 560 */ 561char*dirname =xmemdupz(refname, refname_len -1); 562 dir =find_containing_dir(dir, dirname,0); 563free(dirname); 564}else{ 565 dir =find_containing_dir(dir, refname,0); 566} 567if(!dir) 568return-1; 569 entry_index =search_ref_dir(dir, refname, refname_len); 570if(entry_index == -1) 571return-1; 572 entry = dir->entries[entry_index]; 573 574memmove(&dir->entries[entry_index], 575&dir->entries[entry_index +1], 576(dir->nr - entry_index -1) *sizeof(*dir->entries) 577); 578 dir->nr--; 579if(dir->sorted > entry_index) 580 dir->sorted--; 581free_ref_entry(entry); 582return dir->nr; 583} 584 585/* 586 * Add a ref_entry to the ref_dir (unsorted), recursing into 587 * subdirectories as necessary. dir must represent the top-level 588 * directory. Return 0 on success. 589 */ 590static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 591{ 592 dir =find_containing_dir(dir, ref->name,1); 593if(!dir) 594return-1; 595add_entry_to_dir(dir, ref); 596return0; 597} 598 599/* 600 * Emit a warning and return true iff ref1 and ref2 have the same name 601 * and the same sha1. Die if they have the same name but different 602 * sha1s. 603 */ 604static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 605{ 606if(strcmp(ref1->name, ref2->name)) 607return0; 608 609/* Duplicate name; make sure that they don't conflict: */ 610 611if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 612/* This is impossible by construction */ 613die("Reference directory conflict:%s", ref1->name); 614 615if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 616die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 617 618warning("Duplicated ref:%s", ref1->name); 619return1; 620} 621 622/* 623 * Sort the entries in dir non-recursively (if they are not already 624 * sorted) and remove any duplicate entries. 625 */ 626static voidsort_ref_dir(struct ref_dir *dir) 627{ 628int i, j; 629struct ref_entry *last = NULL; 630 631/* 632 * This check also prevents passing a zero-length array to qsort(), 633 * which is a problem on some platforms. 634 */ 635if(dir->sorted == dir->nr) 636return; 637 638qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 639 640/* Remove any duplicates: */ 641for(i =0, j =0; j < dir->nr; j++) { 642struct ref_entry *entry = dir->entries[j]; 643if(last &&is_dup_ref(last, entry)) 644free_ref_entry(entry); 645else 646 last = dir->entries[i++] = entry; 647} 648 dir->sorted = dir->nr = i; 649} 650 651/* Include broken references in a do_for_each_ref*() iteration: */ 652#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 653 654/* 655 * Return true iff the reference described by entry can be resolved to 656 * an object in the database. Emit a warning if the referred-to 657 * object does not exist. 658 */ 659static intref_resolves_to_object(struct ref_entry *entry) 660{ 661if(entry->flag & REF_ISBROKEN) 662return0; 663if(!has_sha1_file(entry->u.value.sha1)) { 664error("%sdoes not point to a valid object!", entry->name); 665return0; 666} 667return1; 668} 669 670/* 671 * current_ref is a performance hack: when iterating over references 672 * using the for_each_ref*() functions, current_ref is set to the 673 * current reference's entry before calling the callback function. If 674 * the callback function calls peel_ref(), then peel_ref() first 675 * checks whether the reference to be peeled is the current reference 676 * (it usually is) and if so, returns that reference's peeled version 677 * if it is available. This avoids a refname lookup in a common case. 678 */ 679static struct ref_entry *current_ref; 680 681typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 682 683struct ref_entry_cb { 684const char*base; 685int trim; 686int flags; 687 each_ref_fn *fn; 688void*cb_data; 689}; 690 691/* 692 * Handle one reference in a do_for_each_ref*()-style iteration, 693 * calling an each_ref_fn for each entry. 694 */ 695static intdo_one_ref(struct ref_entry *entry,void*cb_data) 696{ 697struct ref_entry_cb *data = cb_data; 698struct ref_entry *old_current_ref; 699int retval; 700 701if(!starts_with(entry->name, data->base)) 702return0; 703 704if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 705!ref_resolves_to_object(entry)) 706return0; 707 708/* Store the old value, in case this is a recursive call: */ 709 old_current_ref = current_ref; 710 current_ref = entry; 711 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 712 entry->flag, data->cb_data); 713 current_ref = old_current_ref; 714return retval; 715} 716 717/* 718 * Call fn for each reference in dir that has index in the range 719 * offset <= index < dir->nr. Recurse into subdirectories that are in 720 * that index range, sorting them before iterating. This function 721 * does not sort dir itself; it should be sorted beforehand. fn is 722 * called for all references, including broken ones. 723 */ 724static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 725 each_ref_entry_fn fn,void*cb_data) 726{ 727int i; 728assert(dir->sorted == dir->nr); 729for(i = offset; i < dir->nr; i++) { 730struct ref_entry *entry = dir->entries[i]; 731int retval; 732if(entry->flag & REF_DIR) { 733struct ref_dir *subdir =get_ref_dir(entry); 734sort_ref_dir(subdir); 735 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 736}else{ 737 retval =fn(entry, cb_data); 738} 739if(retval) 740return retval; 741} 742return0; 743} 744 745/* 746 * Call fn for each reference in the union of dir1 and dir2, in order 747 * by refname. Recurse into subdirectories. If a value entry appears 748 * in both dir1 and dir2, then only process the version that is in 749 * dir2. The input dirs must already be sorted, but subdirs will be 750 * sorted as needed. fn is called for all references, including 751 * broken ones. 752 */ 753static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 754struct ref_dir *dir2, 755 each_ref_entry_fn fn,void*cb_data) 756{ 757int retval; 758int i1 =0, i2 =0; 759 760assert(dir1->sorted == dir1->nr); 761assert(dir2->sorted == dir2->nr); 762while(1) { 763struct ref_entry *e1, *e2; 764int cmp; 765if(i1 == dir1->nr) { 766returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 767} 768if(i2 == dir2->nr) { 769returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 770} 771 e1 = dir1->entries[i1]; 772 e2 = dir2->entries[i2]; 773 cmp =strcmp(e1->name, e2->name); 774if(cmp ==0) { 775if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 776/* Both are directories; descend them in parallel. */ 777struct ref_dir *subdir1 =get_ref_dir(e1); 778struct ref_dir *subdir2 =get_ref_dir(e2); 779sort_ref_dir(subdir1); 780sort_ref_dir(subdir2); 781 retval =do_for_each_entry_in_dirs( 782 subdir1, subdir2, fn, cb_data); 783 i1++; 784 i2++; 785}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 786/* Both are references; ignore the one from dir1. */ 787 retval =fn(e2, cb_data); 788 i1++; 789 i2++; 790}else{ 791die("conflict between reference and directory:%s", 792 e1->name); 793} 794}else{ 795struct ref_entry *e; 796if(cmp <0) { 797 e = e1; 798 i1++; 799}else{ 800 e = e2; 801 i2++; 802} 803if(e->flag & REF_DIR) { 804struct ref_dir *subdir =get_ref_dir(e); 805sort_ref_dir(subdir); 806 retval =do_for_each_entry_in_dir( 807 subdir,0, fn, cb_data); 808}else{ 809 retval =fn(e, cb_data); 810} 811} 812if(retval) 813return retval; 814} 815} 816 817/* 818 * Load all of the refs from the dir into our in-memory cache. The hard work 819 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 820 * through all of the sub-directories. We do not even need to care about 821 * sorting, as traversal order does not matter to us. 822 */ 823static voidprime_ref_dir(struct ref_dir *dir) 824{ 825int i; 826for(i =0; i < dir->nr; i++) { 827struct ref_entry *entry = dir->entries[i]; 828if(entry->flag & REF_DIR) 829prime_ref_dir(get_ref_dir(entry)); 830} 831} 832 833static intentry_matches(struct ref_entry *entry,const struct string_list *list) 834{ 835return list &&string_list_has_string(list, entry->name); 836} 837 838struct nonmatching_ref_data { 839const struct string_list *skip; 840struct ref_entry *found; 841}; 842 843static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 844{ 845struct nonmatching_ref_data *data = vdata; 846 847if(entry_matches(entry, data->skip)) 848return0; 849 850 data->found = entry; 851return1; 852} 853 854static voidreport_refname_conflict(struct ref_entry *entry, 855const char*refname) 856{ 857error("'%s' exists; cannot create '%s'", entry->name, refname); 858} 859 860/* 861 * Return true iff a reference named refname could be created without 862 * conflicting with the name of an existing reference in dir. If 863 * skip is non-NULL, ignore potential conflicts with refs in skip 864 * (e.g., because they are scheduled for deletion in the same 865 * operation). 866 * 867 * Two reference names conflict if one of them exactly matches the 868 * leading components of the other; e.g., "foo/bar" conflicts with 869 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 870 * "foo/barbados". 871 * 872 * skip must be sorted. 873 */ 874static intis_refname_available(const char*refname, 875const struct string_list *skip, 876struct ref_dir *dir) 877{ 878const char*slash; 879size_t len; 880int pos; 881char*dirname; 882 883for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 884/* 885 * We are still at a leading dir of the refname; we are 886 * looking for a conflict with a leaf entry. 887 * 888 * If we find one, we still must make sure it is 889 * not in "skip". 890 */ 891 pos =search_ref_dir(dir, refname, slash - refname); 892if(pos >=0) { 893struct ref_entry *entry = dir->entries[pos]; 894if(entry_matches(entry, skip)) 895return1; 896report_refname_conflict(entry, refname); 897return0; 898} 899 900 901/* 902 * Otherwise, we can try to continue our search with 903 * the next component; if we come up empty, we know 904 * there is nothing under this whole prefix. 905 */ 906 pos =search_ref_dir(dir, refname, slash +1- refname); 907if(pos <0) 908return1; 909 910 dir =get_ref_dir(dir->entries[pos]); 911} 912 913/* 914 * We are at the leaf of our refname; we want to 915 * make sure there are no directories which match it. 916 */ 917 len =strlen(refname); 918 dirname =xmallocz(len +1); 919sprintf(dirname,"%s/", refname); 920 pos =search_ref_dir(dir, dirname, len +1); 921free(dirname); 922 923if(pos >=0) { 924/* 925 * We found a directory named "refname". It is a 926 * problem iff it contains any ref that is not 927 * in "skip". 928 */ 929struct ref_entry *entry = dir->entries[pos]; 930struct ref_dir *dir =get_ref_dir(entry); 931struct nonmatching_ref_data data; 932 933 data.skip = skip; 934sort_ref_dir(dir); 935if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 936return1; 937 938report_refname_conflict(data.found, refname); 939return0; 940} 941 942/* 943 * There is no point in searching for another leaf 944 * node which matches it; such an entry would be the 945 * ref we are looking for, not a conflict. 946 */ 947return1; 948} 949 950struct packed_ref_cache { 951struct ref_entry *root; 952 953/* 954 * Count of references to the data structure in this instance, 955 * including the pointer from ref_cache::packed if any. The 956 * data will not be freed as long as the reference count is 957 * nonzero. 958 */ 959unsigned int referrers; 960 961/* 962 * Iff the packed-refs file associated with this instance is 963 * currently locked for writing, this points at the associated 964 * lock (which is owned by somebody else). The referrer count 965 * is also incremented when the file is locked and decremented 966 * when it is unlocked. 967 */ 968struct lock_file *lock; 969 970/* The metadata from when this packed-refs cache was read */ 971struct stat_validity validity; 972}; 973 974/* 975 * Future: need to be in "struct repository" 976 * when doing a full libification. 977 */ 978static struct ref_cache { 979struct ref_cache *next; 980struct ref_entry *loose; 981struct packed_ref_cache *packed; 982/* 983 * The submodule name, or "" for the main repo. We allocate 984 * length 1 rather than FLEX_ARRAY so that the main ref_cache 985 * is initialized correctly. 986 */ 987char name[1]; 988} ref_cache, *submodule_ref_caches; 989 990/* Lock used for the main packed-refs file: */ 991static struct lock_file packlock; 992 993/* 994 * Increment the reference count of *packed_refs. 995 */ 996static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 997{ 998 packed_refs->referrers++; 999}10001001/*1002 * Decrease the reference count of *packed_refs. If it goes to zero,1003 * free *packed_refs and return true; otherwise return false.1004 */1005static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1006{1007if(!--packed_refs->referrers) {1008free_ref_entry(packed_refs->root);1009stat_validity_clear(&packed_refs->validity);1010free(packed_refs);1011return1;1012}else{1013return0;1014}1015}10161017static voidclear_packed_ref_cache(struct ref_cache *refs)1018{1019if(refs->packed) {1020struct packed_ref_cache *packed_refs = refs->packed;10211022if(packed_refs->lock)1023die("internal error: packed-ref cache cleared while locked");1024 refs->packed = NULL;1025release_packed_ref_cache(packed_refs);1026}1027}10281029static voidclear_loose_ref_cache(struct ref_cache *refs)1030{1031if(refs->loose) {1032free_ref_entry(refs->loose);1033 refs->loose = NULL;1034}1035}10361037static struct ref_cache *create_ref_cache(const char*submodule)1038{1039int len;1040struct ref_cache *refs;1041if(!submodule)1042 submodule ="";1043 len =strlen(submodule) +1;1044 refs =xcalloc(1,sizeof(struct ref_cache) + len);1045memcpy(refs->name, submodule, len);1046return refs;1047}10481049/*1050 * Return a pointer to a ref_cache for the specified submodule. For1051 * the main repository, use submodule==NULL. The returned structure1052 * will be allocated and initialized but not necessarily populated; it1053 * should not be freed.1054 */1055static struct ref_cache *get_ref_cache(const char*submodule)1056{1057struct ref_cache *refs;10581059if(!submodule || !*submodule)1060return&ref_cache;10611062for(refs = submodule_ref_caches; refs; refs = refs->next)1063if(!strcmp(submodule, refs->name))1064return refs;10651066 refs =create_ref_cache(submodule);1067 refs->next = submodule_ref_caches;1068 submodule_ref_caches = refs;1069return refs;1070}10711072/* The length of a peeled reference line in packed-refs, including EOL: */1073#define PEELED_LINE_LENGTH 4210741075/*1076 * The packed-refs header line that we write out. Perhaps other1077 * traits will be added later. The trailing space is required.1078 */1079static const char PACKED_REFS_HEADER[] =1080"# pack-refs with: peeled fully-peeled\n";10811082/*1083 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1084 * Return a pointer to the refname within the line (null-terminated),1085 * or NULL if there was a problem.1086 */1087static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1088{1089const char*ref;10901091/*1092 * 42: the answer to everything.1093 *1094 * In this case, it happens to be the answer to1095 * 40 (length of sha1 hex representation)1096 * +1 (space in between hex and name)1097 * +1 (newline at the end of the line)1098 */1099if(line->len <=42)1100return NULL;11011102if(get_sha1_hex(line->buf, sha1) <0)1103return NULL;1104if(!isspace(line->buf[40]))1105return NULL;11061107 ref = line->buf +41;1108if(isspace(*ref))1109return NULL;11101111if(line->buf[line->len -1] !='\n')1112return NULL;1113 line->buf[--line->len] =0;11141115return ref;1116}11171118/*1119 * Read f, which is a packed-refs file, into dir.1120 *1121 * A comment line of the form "# pack-refs with: " may contain zero or1122 * more traits. We interpret the traits as follows:1123 *1124 * No traits:1125 *1126 * Probably no references are peeled. But if the file contains a1127 * peeled value for a reference, we will use it.1128 *1129 * peeled:1130 *1131 * References under "refs/tags/", if they *can* be peeled, *are*1132 * peeled in this file. References outside of "refs/tags/" are1133 * probably not peeled even if they could have been, but if we find1134 * a peeled value for such a reference we will use it.1135 *1136 * fully-peeled:1137 *1138 * All references in the file that can be peeled are peeled.1139 * Inversely (and this is more important), any references in the1140 * file for which no peeled value is recorded is not peelable. This1141 * trait should typically be written alongside "peeled" for1142 * compatibility with older clients, but we do not require it1143 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1144 */1145static voidread_packed_refs(FILE*f,struct ref_dir *dir)1146{1147struct ref_entry *last = NULL;1148struct strbuf line = STRBUF_INIT;1149enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11501151while(strbuf_getwholeline(&line, f,'\n') != EOF) {1152unsigned char sha1[20];1153const char*refname;1154const char*traits;11551156if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1157if(strstr(traits," fully-peeled "))1158 peeled = PEELED_FULLY;1159else if(strstr(traits," peeled "))1160 peeled = PEELED_TAGS;1161/* perhaps other traits later as well */1162continue;1163}11641165 refname =parse_ref_line(&line, sha1);1166if(refname) {1167int flag = REF_ISPACKED;11681169if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1170hashclr(sha1);1171 flag |= REF_BAD_NAME | REF_ISBROKEN;1172}1173 last =create_ref_entry(refname, sha1, flag,0);1174if(peeled == PEELED_FULLY ||1175(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1176 last->flag |= REF_KNOWS_PEELED;1177add_ref(dir, last);1178continue;1179}1180if(last &&1181 line.buf[0] =='^'&&1182 line.len == PEELED_LINE_LENGTH &&1183 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1184!get_sha1_hex(line.buf +1, sha1)) {1185hashcpy(last->u.value.peeled, sha1);1186/*1187 * Regardless of what the file header said,1188 * we definitely know the value of *this*1189 * reference:1190 */1191 last->flag |= REF_KNOWS_PEELED;1192}1193}11941195strbuf_release(&line);1196}11971198/*1199 * Get the packed_ref_cache for the specified ref_cache, creating it1200 * if necessary.1201 */1202static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1203{1204const char*packed_refs_file;12051206if(*refs->name)1207 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1208else1209 packed_refs_file =git_path("packed-refs");12101211if(refs->packed &&1212!stat_validity_check(&refs->packed->validity, packed_refs_file))1213clear_packed_ref_cache(refs);12141215if(!refs->packed) {1216FILE*f;12171218 refs->packed =xcalloc(1,sizeof(*refs->packed));1219acquire_packed_ref_cache(refs->packed);1220 refs->packed->root =create_dir_entry(refs,"",0,0);1221 f =fopen(packed_refs_file,"r");1222if(f) {1223stat_validity_update(&refs->packed->validity,fileno(f));1224read_packed_refs(f,get_ref_dir(refs->packed->root));1225fclose(f);1226}1227}1228return refs->packed;1229}12301231static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1232{1233returnget_ref_dir(packed_ref_cache->root);1234}12351236static struct ref_dir *get_packed_refs(struct ref_cache *refs)1237{1238returnget_packed_ref_dir(get_packed_ref_cache(refs));1239}12401241voidadd_packed_ref(const char*refname,const unsigned char*sha1)1242{1243struct packed_ref_cache *packed_ref_cache =1244get_packed_ref_cache(&ref_cache);12451246if(!packed_ref_cache->lock)1247die("internal error: packed refs not locked");1248add_ref(get_packed_ref_dir(packed_ref_cache),1249create_ref_entry(refname, sha1, REF_ISPACKED,1));1250}12511252/*1253 * Read the loose references from the namespace dirname into dir1254 * (without recursing). dirname must end with '/'. dir must be the1255 * directory entry corresponding to dirname.1256 */1257static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1258{1259struct ref_cache *refs = dir->ref_cache;1260DIR*d;1261const char*path;1262struct dirent *de;1263int dirnamelen =strlen(dirname);1264struct strbuf refname;12651266if(*refs->name)1267 path =git_path_submodule(refs->name,"%s", dirname);1268else1269 path =git_path("%s", dirname);12701271 d =opendir(path);1272if(!d)1273return;12741275strbuf_init(&refname, dirnamelen +257);1276strbuf_add(&refname, dirname, dirnamelen);12771278while((de =readdir(d)) != NULL) {1279unsigned char sha1[20];1280struct stat st;1281int flag;1282const char*refdir;12831284if(de->d_name[0] =='.')1285continue;1286if(ends_with(de->d_name,".lock"))1287continue;1288strbuf_addstr(&refname, de->d_name);1289 refdir = *refs->name1290?git_path_submodule(refs->name,"%s", refname.buf)1291:git_path("%s", refname.buf);1292if(stat(refdir, &st) <0) {1293;/* silently ignore */1294}else if(S_ISDIR(st.st_mode)) {1295strbuf_addch(&refname,'/');1296add_entry_to_dir(dir,1297create_dir_entry(refs, refname.buf,1298 refname.len,1));1299}else{1300if(*refs->name) {1301hashclr(sha1);1302 flag =0;1303if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1304hashclr(sha1);1305 flag |= REF_ISBROKEN;1306}1307}else if(read_ref_full(refname.buf,1308 RESOLVE_REF_READING,1309 sha1, &flag)) {1310hashclr(sha1);1311 flag |= REF_ISBROKEN;1312}1313if(check_refname_format(refname.buf,1314 REFNAME_ALLOW_ONELEVEL)) {1315hashclr(sha1);1316 flag |= REF_BAD_NAME | REF_ISBROKEN;1317}1318add_entry_to_dir(dir,1319create_ref_entry(refname.buf, sha1, flag,0));1320}1321strbuf_setlen(&refname, dirnamelen);1322}1323strbuf_release(&refname);1324closedir(d);1325}13261327static struct ref_dir *get_loose_refs(struct ref_cache *refs)1328{1329if(!refs->loose) {1330/*1331 * Mark the top-level directory complete because we1332 * are about to read the only subdirectory that can1333 * hold references:1334 */1335 refs->loose =create_dir_entry(refs,"",0,0);1336/*1337 * Create an incomplete entry for "refs/":1338 */1339add_entry_to_dir(get_ref_dir(refs->loose),1340create_dir_entry(refs,"refs/",5,1));1341}1342returnget_ref_dir(refs->loose);1343}13441345/* We allow "recursive" symbolic refs. Only within reason, though */1346#define MAXDEPTH 51347#define MAXREFLEN (1024)13481349/*1350 * Called by resolve_gitlink_ref_recursive() after it failed to read1351 * from the loose refs in ref_cache refs. Find <refname> in the1352 * packed-refs file for the submodule.1353 */1354static intresolve_gitlink_packed_ref(struct ref_cache *refs,1355const char*refname,unsigned char*sha1)1356{1357struct ref_entry *ref;1358struct ref_dir *dir =get_packed_refs(refs);13591360 ref =find_ref(dir, refname);1361if(ref == NULL)1362return-1;13631364hashcpy(sha1, ref->u.value.sha1);1365return0;1366}13671368static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1369const char*refname,unsigned char*sha1,1370int recursion)1371{1372int fd, len;1373char buffer[128], *p;1374char*path;13751376if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1377return-1;1378 path = *refs->name1379?git_path_submodule(refs->name,"%s", refname)1380:git_path("%s", refname);1381 fd =open(path, O_RDONLY);1382if(fd <0)1383returnresolve_gitlink_packed_ref(refs, refname, sha1);13841385 len =read(fd, buffer,sizeof(buffer)-1);1386close(fd);1387if(len <0)1388return-1;1389while(len &&isspace(buffer[len-1]))1390 len--;1391 buffer[len] =0;13921393/* Was it a detached head or an old-fashioned symlink? */1394if(!get_sha1_hex(buffer, sha1))1395return0;13961397/* Symref? */1398if(strncmp(buffer,"ref:",4))1399return-1;1400 p = buffer +4;1401while(isspace(*p))1402 p++;14031404returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1405}14061407intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1408{1409int len =strlen(path), retval;1410char*submodule;1411struct ref_cache *refs;14121413while(len && path[len-1] =='/')1414 len--;1415if(!len)1416return-1;1417 submodule =xstrndup(path, len);1418 refs =get_ref_cache(submodule);1419free(submodule);14201421 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1422return retval;1423}14241425/*1426 * Return the ref_entry for the given refname from the packed1427 * references. If it does not exist, return NULL.1428 */1429static struct ref_entry *get_packed_ref(const char*refname)1430{1431returnfind_ref(get_packed_refs(&ref_cache), refname);1432}14331434/*1435 * A loose ref file doesn't exist; check for a packed ref. The1436 * options are forwarded from resolve_safe_unsafe().1437 */1438static intresolve_missing_loose_ref(const char*refname,1439int resolve_flags,1440unsigned char*sha1,1441int*flags)1442{1443struct ref_entry *entry;14441445/*1446 * The loose reference file does not exist; check for a packed1447 * reference.1448 */1449 entry =get_packed_ref(refname);1450if(entry) {1451hashcpy(sha1, entry->u.value.sha1);1452if(flags)1453*flags |= REF_ISPACKED;1454return0;1455}1456/* The reference is not a packed reference, either. */1457if(resolve_flags & RESOLVE_REF_READING) {1458 errno = ENOENT;1459return-1;1460}else{1461hashclr(sha1);1462return0;1463}1464}14651466/* This function needs to return a meaningful errno on failure */1467const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1468{1469int depth = MAXDEPTH;1470 ssize_t len;1471char buffer[256];1472static char refname_buffer[256];1473int bad_name =0;14741475if(flags)1476*flags =0;14771478if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1479if(flags)1480*flags |= REF_BAD_NAME;14811482if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1483!refname_is_safe(refname)) {1484 errno = EINVAL;1485return NULL;1486}1487/*1488 * dwim_ref() uses REF_ISBROKEN to distinguish between1489 * missing refs and refs that were present but invalid,1490 * to complain about the latter to stderr.1491 *1492 * We don't know whether the ref exists, so don't set1493 * REF_ISBROKEN yet.1494 */1495 bad_name =1;1496}1497for(;;) {1498char path[PATH_MAX];1499struct stat st;1500char*buf;1501int fd;15021503if(--depth <0) {1504 errno = ELOOP;1505return NULL;1506}15071508git_snpath(path,sizeof(path),"%s", refname);15091510/*1511 * We might have to loop back here to avoid a race1512 * condition: first we lstat() the file, then we try1513 * to read it as a link or as a file. But if somebody1514 * changes the type of the file (file <-> directory1515 * <-> symlink) between the lstat() and reading, then1516 * we don't want to report that as an error but rather1517 * try again starting with the lstat().1518 */1519 stat_ref:1520if(lstat(path, &st) <0) {1521if(errno != ENOENT)1522return NULL;1523if(resolve_missing_loose_ref(refname, resolve_flags,1524 sha1, flags))1525return NULL;1526if(bad_name) {1527hashclr(sha1);1528if(flags)1529*flags |= REF_ISBROKEN;1530}1531return refname;1532}15331534/* Follow "normalized" - ie "refs/.." symlinks by hand */1535if(S_ISLNK(st.st_mode)) {1536 len =readlink(path, buffer,sizeof(buffer)-1);1537if(len <0) {1538if(errno == ENOENT || errno == EINVAL)1539/* inconsistent with lstat; retry */1540goto stat_ref;1541else1542return NULL;1543}1544 buffer[len] =0;1545if(starts_with(buffer,"refs/") &&1546!check_refname_format(buffer,0)) {1547strcpy(refname_buffer, buffer);1548 refname = refname_buffer;1549if(flags)1550*flags |= REF_ISSYMREF;1551if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1552hashclr(sha1);1553return refname;1554}1555continue;1556}1557}15581559/* Is it a directory? */1560if(S_ISDIR(st.st_mode)) {1561 errno = EISDIR;1562return NULL;1563}15641565/*1566 * Anything else, just open it and try to use it as1567 * a ref1568 */1569 fd =open(path, O_RDONLY);1570if(fd <0) {1571if(errno == ENOENT)1572/* inconsistent with lstat; retry */1573goto stat_ref;1574else1575return NULL;1576}1577 len =read_in_full(fd, buffer,sizeof(buffer)-1);1578if(len <0) {1579int save_errno = errno;1580close(fd);1581 errno = save_errno;1582return NULL;1583}1584close(fd);1585while(len &&isspace(buffer[len-1]))1586 len--;1587 buffer[len] ='\0';15881589/*1590 * Is it a symbolic ref?1591 */1592if(!starts_with(buffer,"ref:")) {1593/*1594 * Please note that FETCH_HEAD has a second1595 * line containing other data.1596 */1597if(get_sha1_hex(buffer, sha1) ||1598(buffer[40] !='\0'&& !isspace(buffer[40]))) {1599if(flags)1600*flags |= REF_ISBROKEN;1601 errno = EINVAL;1602return NULL;1603}1604if(bad_name) {1605hashclr(sha1);1606if(flags)1607*flags |= REF_ISBROKEN;1608}1609return refname;1610}1611if(flags)1612*flags |= REF_ISSYMREF;1613 buf = buffer +4;1614while(isspace(*buf))1615 buf++;1616 refname =strcpy(refname_buffer, buf);1617if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1618hashclr(sha1);1619return refname;1620}1621if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1622if(flags)1623*flags |= REF_ISBROKEN;16241625if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1626!refname_is_safe(buf)) {1627 errno = EINVAL;1628return NULL;1629}1630 bad_name =1;1631}1632}1633}16341635char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1636{1637returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1638}16391640/* The argument to filter_refs */1641struct ref_filter {1642const char*pattern;1643 each_ref_fn *fn;1644void*cb_data;1645};16461647intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1648{1649if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1650return0;1651return-1;1652}16531654intread_ref(const char*refname,unsigned char*sha1)1655{1656returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1657}16581659intref_exists(const char*refname)1660{1661unsigned char sha1[20];1662return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1663}16641665static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1666void*data)1667{1668struct ref_filter *filter = (struct ref_filter *)data;1669if(wildmatch(filter->pattern, refname,0, NULL))1670return0;1671return filter->fn(refname, sha1, flags, filter->cb_data);1672}16731674enum peel_status {1675/* object was peeled successfully: */1676 PEEL_PEELED =0,16771678/*1679 * object cannot be peeled because the named object (or an1680 * object referred to by a tag in the peel chain), does not1681 * exist.1682 */1683 PEEL_INVALID = -1,16841685/* object cannot be peeled because it is not a tag: */1686 PEEL_NON_TAG = -2,16871688/* ref_entry contains no peeled value because it is a symref: */1689 PEEL_IS_SYMREF = -3,16901691/*1692 * ref_entry cannot be peeled because it is broken (i.e., the1693 * symbolic reference cannot even be resolved to an object1694 * name):1695 */1696 PEEL_BROKEN = -41697};16981699/*1700 * Peel the named object; i.e., if the object is a tag, resolve the1701 * tag recursively until a non-tag is found. If successful, store the1702 * result to sha1 and return PEEL_PEELED. If the object is not a tag1703 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1704 * and leave sha1 unchanged.1705 */1706static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1707{1708struct object *o =lookup_unknown_object(name);17091710if(o->type == OBJ_NONE) {1711int type =sha1_object_info(name, NULL);1712if(type <0|| !object_as_type(o, type,0))1713return PEEL_INVALID;1714}17151716if(o->type != OBJ_TAG)1717return PEEL_NON_TAG;17181719 o =deref_tag_noverify(o);1720if(!o)1721return PEEL_INVALID;17221723hashcpy(sha1, o->sha1);1724return PEEL_PEELED;1725}17261727/*1728 * Peel the entry (if possible) and return its new peel_status. If1729 * repeel is true, re-peel the entry even if there is an old peeled1730 * value that is already stored in it.1731 *1732 * It is OK to call this function with a packed reference entry that1733 * might be stale and might even refer to an object that has since1734 * been garbage-collected. In such a case, if the entry has1735 * REF_KNOWS_PEELED then leave the status unchanged and return1736 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1737 */1738static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1739{1740enum peel_status status;17411742if(entry->flag & REF_KNOWS_PEELED) {1743if(repeel) {1744 entry->flag &= ~REF_KNOWS_PEELED;1745hashclr(entry->u.value.peeled);1746}else{1747returnis_null_sha1(entry->u.value.peeled) ?1748 PEEL_NON_TAG : PEEL_PEELED;1749}1750}1751if(entry->flag & REF_ISBROKEN)1752return PEEL_BROKEN;1753if(entry->flag & REF_ISSYMREF)1754return PEEL_IS_SYMREF;17551756 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1757if(status == PEEL_PEELED || status == PEEL_NON_TAG)1758 entry->flag |= REF_KNOWS_PEELED;1759return status;1760}17611762intpeel_ref(const char*refname,unsigned char*sha1)1763{1764int flag;1765unsigned char base[20];17661767if(current_ref && (current_ref->name == refname1768|| !strcmp(current_ref->name, refname))) {1769if(peel_entry(current_ref,0))1770return-1;1771hashcpy(sha1, current_ref->u.value.peeled);1772return0;1773}17741775if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1776return-1;17771778/*1779 * If the reference is packed, read its ref_entry from the1780 * cache in the hope that we already know its peeled value.1781 * We only try this optimization on packed references because1782 * (a) forcing the filling of the loose reference cache could1783 * be expensive and (b) loose references anyway usually do not1784 * have REF_KNOWS_PEELED.1785 */1786if(flag & REF_ISPACKED) {1787struct ref_entry *r =get_packed_ref(refname);1788if(r) {1789if(peel_entry(r,0))1790return-1;1791hashcpy(sha1, r->u.value.peeled);1792return0;1793}1794}17951796returnpeel_object(base, sha1);1797}17981799struct warn_if_dangling_data {1800FILE*fp;1801const char*refname;1802const struct string_list *refnames;1803const char*msg_fmt;1804};18051806static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1807int flags,void*cb_data)1808{1809struct warn_if_dangling_data *d = cb_data;1810const char*resolves_to;1811unsigned char junk[20];18121813if(!(flags & REF_ISSYMREF))1814return0;18151816 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1817if(!resolves_to1818|| (d->refname1819?strcmp(resolves_to, d->refname)1820: !string_list_has_string(d->refnames, resolves_to))) {1821return0;1822}18231824fprintf(d->fp, d->msg_fmt, refname);1825fputc('\n', d->fp);1826return0;1827}18281829voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1830{1831struct warn_if_dangling_data data;18321833 data.fp = fp;1834 data.refname = refname;1835 data.refnames = NULL;1836 data.msg_fmt = msg_fmt;1837for_each_rawref(warn_if_dangling_symref, &data);1838}18391840voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1841{1842struct warn_if_dangling_data data;18431844 data.fp = fp;1845 data.refname = NULL;1846 data.refnames = refnames;1847 data.msg_fmt = msg_fmt;1848for_each_rawref(warn_if_dangling_symref, &data);1849}18501851/*1852 * Call fn for each reference in the specified ref_cache, omitting1853 * references not in the containing_dir of base. fn is called for all1854 * references, including broken ones. If fn ever returns a non-zero1855 * value, stop the iteration and return that value; otherwise, return1856 * 0.1857 */1858static intdo_for_each_entry(struct ref_cache *refs,const char*base,1859 each_ref_entry_fn fn,void*cb_data)1860{1861struct packed_ref_cache *packed_ref_cache;1862struct ref_dir *loose_dir;1863struct ref_dir *packed_dir;1864int retval =0;18651866/*1867 * We must make sure that all loose refs are read before accessing the1868 * packed-refs file; this avoids a race condition in which loose refs1869 * are migrated to the packed-refs file by a simultaneous process, but1870 * our in-memory view is from before the migration. get_packed_ref_cache()1871 * takes care of making sure our view is up to date with what is on1872 * disk.1873 */1874 loose_dir =get_loose_refs(refs);1875if(base && *base) {1876 loose_dir =find_containing_dir(loose_dir, base,0);1877}1878if(loose_dir)1879prime_ref_dir(loose_dir);18801881 packed_ref_cache =get_packed_ref_cache(refs);1882acquire_packed_ref_cache(packed_ref_cache);1883 packed_dir =get_packed_ref_dir(packed_ref_cache);1884if(base && *base) {1885 packed_dir =find_containing_dir(packed_dir, base,0);1886}18871888if(packed_dir && loose_dir) {1889sort_ref_dir(packed_dir);1890sort_ref_dir(loose_dir);1891 retval =do_for_each_entry_in_dirs(1892 packed_dir, loose_dir, fn, cb_data);1893}else if(packed_dir) {1894sort_ref_dir(packed_dir);1895 retval =do_for_each_entry_in_dir(1896 packed_dir,0, fn, cb_data);1897}else if(loose_dir) {1898sort_ref_dir(loose_dir);1899 retval =do_for_each_entry_in_dir(1900 loose_dir,0, fn, cb_data);1901}19021903release_packed_ref_cache(packed_ref_cache);1904return retval;1905}19061907/*1908 * Call fn for each reference in the specified ref_cache for which the1909 * refname begins with base. If trim is non-zero, then trim that many1910 * characters off the beginning of each refname before passing the1911 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1912 * broken references in the iteration. If fn ever returns a non-zero1913 * value, stop the iteration and return that value; otherwise, return1914 * 0.1915 */1916static intdo_for_each_ref(struct ref_cache *refs,const char*base,1917 each_ref_fn fn,int trim,int flags,void*cb_data)1918{1919struct ref_entry_cb data;1920 data.base = base;1921 data.trim = trim;1922 data.flags = flags;1923 data.fn = fn;1924 data.cb_data = cb_data;19251926returndo_for_each_entry(refs, base, do_one_ref, &data);1927}19281929static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1930{1931unsigned char sha1[20];1932int flag;19331934if(submodule) {1935if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1936returnfn("HEAD", sha1,0, cb_data);19371938return0;1939}19401941if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1942returnfn("HEAD", sha1, flag, cb_data);19431944return0;1945}19461947inthead_ref(each_ref_fn fn,void*cb_data)1948{1949returndo_head_ref(NULL, fn, cb_data);1950}19511952inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1953{1954returndo_head_ref(submodule, fn, cb_data);1955}19561957intfor_each_ref(each_ref_fn fn,void*cb_data)1958{1959returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1960}19611962intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1963{1964returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1965}19661967intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1968{1969returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1970}19711972intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1973 each_ref_fn fn,void*cb_data)1974{1975returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1976}19771978intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1979{1980returnfor_each_ref_in("refs/tags/", fn, cb_data);1981}19821983intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1984{1985returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1986}19871988intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1989{1990returnfor_each_ref_in("refs/heads/", fn, cb_data);1991}19921993intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1994{1995returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1996}19971998intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1999{2000returnfor_each_ref_in("refs/remotes/", fn, cb_data);2001}20022003intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2004{2005returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2006}20072008intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2009{2010returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2011}20122013inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2014{2015struct strbuf buf = STRBUF_INIT;2016int ret =0;2017unsigned char sha1[20];2018int flag;20192020strbuf_addf(&buf,"%sHEAD",get_git_namespace());2021if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2022 ret =fn(buf.buf, sha1, flag, cb_data);2023strbuf_release(&buf);20242025return ret;2026}20272028intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2029{2030struct strbuf buf = STRBUF_INIT;2031int ret;2032strbuf_addf(&buf,"%srefs/",get_git_namespace());2033 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2034strbuf_release(&buf);2035return ret;2036}20372038intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2039const char*prefix,void*cb_data)2040{2041struct strbuf real_pattern = STRBUF_INIT;2042struct ref_filter filter;2043int ret;20442045if(!prefix && !starts_with(pattern,"refs/"))2046strbuf_addstr(&real_pattern,"refs/");2047else if(prefix)2048strbuf_addstr(&real_pattern, prefix);2049strbuf_addstr(&real_pattern, pattern);20502051if(!has_glob_specials(pattern)) {2052/* Append implied '/' '*' if not present. */2053if(real_pattern.buf[real_pattern.len -1] !='/')2054strbuf_addch(&real_pattern,'/');2055/* No need to check for '*', there is none. */2056strbuf_addch(&real_pattern,'*');2057}20582059 filter.pattern = real_pattern.buf;2060 filter.fn = fn;2061 filter.cb_data = cb_data;2062 ret =for_each_ref(filter_refs, &filter);20632064strbuf_release(&real_pattern);2065return ret;2066}20672068intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2069{2070returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2071}20722073intfor_each_rawref(each_ref_fn fn,void*cb_data)2074{2075returndo_for_each_ref(&ref_cache,"", fn,0,2076 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2077}20782079const char*prettify_refname(const char*name)2080{2081return name + (2082starts_with(name,"refs/heads/") ?11:2083starts_with(name,"refs/tags/") ?10:2084starts_with(name,"refs/remotes/") ?13:20850);2086}20872088static const char*ref_rev_parse_rules[] = {2089"%.*s",2090"refs/%.*s",2091"refs/tags/%.*s",2092"refs/heads/%.*s",2093"refs/remotes/%.*s",2094"refs/remotes/%.*s/HEAD",2095 NULL2096};20972098intrefname_match(const char*abbrev_name,const char*full_name)2099{2100const char**p;2101const int abbrev_name_len =strlen(abbrev_name);21022103for(p = ref_rev_parse_rules; *p; p++) {2104if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2105return1;2106}2107}21082109return0;2110}21112112static voidunlock_ref(struct ref_lock *lock)2113{2114/* Do not free lock->lk -- atexit() still looks at them */2115if(lock->lk)2116rollback_lock_file(lock->lk);2117free(lock->ref_name);2118free(lock->orig_ref_name);2119free(lock);2120}21212122/* This function should make sure errno is meaningful on error */2123static struct ref_lock *verify_lock(struct ref_lock *lock,2124const unsigned char*old_sha1,int mustexist)2125{2126if(read_ref_full(lock->ref_name,2127 mustexist ? RESOLVE_REF_READING :0,2128 lock->old_sha1, NULL)) {2129int save_errno = errno;2130error("Can't verify ref%s", lock->ref_name);2131unlock_ref(lock);2132 errno = save_errno;2133return NULL;2134}2135if(hashcmp(lock->old_sha1, old_sha1)) {2136error("Ref%sis at%sbut expected%s", lock->ref_name,2137sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2138unlock_ref(lock);2139 errno = EBUSY;2140return NULL;2141}2142return lock;2143}21442145static intremove_empty_directories(const char*file)2146{2147/* we want to create a file but there is a directory there;2148 * if that is an empty directory (or a directory that contains2149 * only empty directories), remove them.2150 */2151struct strbuf path;2152int result, save_errno;21532154strbuf_init(&path,20);2155strbuf_addstr(&path, file);21562157 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2158 save_errno = errno;21592160strbuf_release(&path);2161 errno = save_errno;21622163return result;2164}21652166/*2167 * *string and *len will only be substituted, and *string returned (for2168 * later free()ing) if the string passed in is a magic short-hand form2169 * to name a branch.2170 */2171static char*substitute_branch_name(const char**string,int*len)2172{2173struct strbuf buf = STRBUF_INIT;2174int ret =interpret_branch_name(*string, *len, &buf);21752176if(ret == *len) {2177size_t size;2178*string =strbuf_detach(&buf, &size);2179*len = size;2180return(char*)*string;2181}21822183return NULL;2184}21852186intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2187{2188char*last_branch =substitute_branch_name(&str, &len);2189const char**p, *r;2190int refs_found =0;21912192*ref = NULL;2193for(p = ref_rev_parse_rules; *p; p++) {2194char fullref[PATH_MAX];2195unsigned char sha1_from_ref[20];2196unsigned char*this_result;2197int flag;21982199 this_result = refs_found ? sha1_from_ref : sha1;2200mksnpath(fullref,sizeof(fullref), *p, len, str);2201 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2202 this_result, &flag);2203if(r) {2204if(!refs_found++)2205*ref =xstrdup(r);2206if(!warn_ambiguous_refs)2207break;2208}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2209warning("ignoring dangling symref%s.", fullref);2210}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2211warning("ignoring broken ref%s.", fullref);2212}2213}2214free(last_branch);2215return refs_found;2216}22172218intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2219{2220char*last_branch =substitute_branch_name(&str, &len);2221const char**p;2222int logs_found =0;22232224*log = NULL;2225for(p = ref_rev_parse_rules; *p; p++) {2226unsigned char hash[20];2227char path[PATH_MAX];2228const char*ref, *it;22292230mksnpath(path,sizeof(path), *p, len, str);2231 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2232 hash, NULL);2233if(!ref)2234continue;2235if(reflog_exists(path))2236 it = path;2237else if(strcmp(ref, path) &&reflog_exists(ref))2238 it = ref;2239else2240continue;2241if(!logs_found++) {2242*log =xstrdup(it);2243hashcpy(sha1, hash);2244}2245if(!warn_ambiguous_refs)2246break;2247}2248free(last_branch);2249return logs_found;2250}22512252/*2253 * Locks a ref returning the lock on success and NULL on failure.2254 * On failure errno is set to something meaningful.2255 */2256static struct ref_lock *lock_ref_sha1_basic(const char*refname,2257const unsigned char*old_sha1,2258const struct string_list *skip,2259int flags,int*type_p)2260{2261char*ref_file;2262const char*orig_refname = refname;2263struct ref_lock *lock;2264int last_errno =0;2265int type, lflags;2266int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2267int resolve_flags =0;2268int missing =0;2269int attempts_remaining =3;22702271 lock =xcalloc(1,sizeof(struct ref_lock));2272 lock->lock_fd = -1;22732274if(mustexist)2275 resolve_flags |= RESOLVE_REF_READING;2276if(flags & REF_DELETING) {2277 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2278if(flags & REF_NODEREF)2279 resolve_flags |= RESOLVE_REF_NO_RECURSE;2280}22812282 refname =resolve_ref_unsafe(refname, resolve_flags,2283 lock->old_sha1, &type);2284if(!refname && errno == EISDIR) {2285/* we are trying to lock foo but we used to2286 * have foo/bar which now does not exist;2287 * it is normal for the empty directory 'foo'2288 * to remain.2289 */2290 ref_file =git_path("%s", orig_refname);2291if(remove_empty_directories(ref_file)) {2292 last_errno = errno;2293error("there are still refs under '%s'", orig_refname);2294goto error_return;2295}2296 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2297 lock->old_sha1, &type);2298}2299if(type_p)2300*type_p = type;2301if(!refname) {2302 last_errno = errno;2303error("unable to resolve reference%s:%s",2304 orig_refname,strerror(errno));2305goto error_return;2306}2307 missing =is_null_sha1(lock->old_sha1);2308/* When the ref did not exist and we are creating it,2309 * make sure there is no existing ref that is packed2310 * whose name begins with our refname, nor a ref whose2311 * name is a proper prefix of our refname.2312 */2313if(missing &&2314!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2315 last_errno = ENOTDIR;2316goto error_return;2317}23182319 lock->lk =xcalloc(1,sizeof(struct lock_file));23202321 lflags =0;2322if(flags & REF_NODEREF) {2323 refname = orig_refname;2324 lflags |= LOCK_NO_DEREF;2325}2326 lock->ref_name =xstrdup(refname);2327 lock->orig_ref_name =xstrdup(orig_refname);2328 ref_file =git_path("%s", refname);2329if(missing)2330 lock->force_write =1;2331if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2332 lock->force_write =1;23332334 retry:2335switch(safe_create_leading_directories(ref_file)) {2336case SCLD_OK:2337break;/* success */2338case SCLD_VANISHED:2339if(--attempts_remaining >0)2340goto retry;2341/* fall through */2342default:2343 last_errno = errno;2344error("unable to create directory for%s", ref_file);2345goto error_return;2346}23472348 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2349if(lock->lock_fd <0) {2350 last_errno = errno;2351if(errno == ENOENT && --attempts_remaining >0)2352/*2353 * Maybe somebody just deleted one of the2354 * directories leading to ref_file. Try2355 * again:2356 */2357goto retry;2358else{2359struct strbuf err = STRBUF_INIT;2360unable_to_lock_message(ref_file, errno, &err);2361error("%s", err.buf);2362strbuf_release(&err);2363goto error_return;2364}2365}2366return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23672368 error_return:2369unlock_ref(lock);2370 errno = last_errno;2371return NULL;2372}23732374/*2375 * Write an entry to the packed-refs file for the specified refname.2376 * If peeled is non-NULL, write it as the entry's peeled value.2377 */2378static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2379unsigned char*peeled)2380{2381fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2382if(peeled)2383fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2384}23852386/*2387 * An each_ref_entry_fn that writes the entry to a packed-refs file.2388 */2389static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2390{2391enum peel_status peel_status =peel_entry(entry,0);23922393if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2394error("internal error:%sis not a valid packed reference!",2395 entry->name);2396write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2397 peel_status == PEEL_PEELED ?2398 entry->u.value.peeled : NULL);2399return0;2400}24012402/* This should return a meaningful errno on failure */2403intlock_packed_refs(int flags)2404{2405struct packed_ref_cache *packed_ref_cache;24062407if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2408return-1;2409/*2410 * Get the current packed-refs while holding the lock. If the2411 * packed-refs file has been modified since we last read it,2412 * this will automatically invalidate the cache and re-read2413 * the packed-refs file.2414 */2415 packed_ref_cache =get_packed_ref_cache(&ref_cache);2416 packed_ref_cache->lock = &packlock;2417/* Increment the reference count to prevent it from being freed: */2418acquire_packed_ref_cache(packed_ref_cache);2419return0;2420}24212422/*2423 * Commit the packed refs changes.2424 * On error we must make sure that errno contains a meaningful value.2425 */2426intcommit_packed_refs(void)2427{2428struct packed_ref_cache *packed_ref_cache =2429get_packed_ref_cache(&ref_cache);2430int error =0;2431int save_errno =0;2432FILE*out;24332434if(!packed_ref_cache->lock)2435die("internal error: packed-refs not locked");24362437 out =fdopen_lock_file(packed_ref_cache->lock,"w");2438if(!out)2439die_errno("unable to fdopen packed-refs descriptor");24402441fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2442do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24430, write_packed_entry_fn, out);24442445if(commit_lock_file(packed_ref_cache->lock)) {2446 save_errno = errno;2447 error = -1;2448}2449 packed_ref_cache->lock = NULL;2450release_packed_ref_cache(packed_ref_cache);2451 errno = save_errno;2452return error;2453}24542455voidrollback_packed_refs(void)2456{2457struct packed_ref_cache *packed_ref_cache =2458get_packed_ref_cache(&ref_cache);24592460if(!packed_ref_cache->lock)2461die("internal error: packed-refs not locked");2462rollback_lock_file(packed_ref_cache->lock);2463 packed_ref_cache->lock = NULL;2464release_packed_ref_cache(packed_ref_cache);2465clear_packed_ref_cache(&ref_cache);2466}24672468struct ref_to_prune {2469struct ref_to_prune *next;2470unsigned char sha1[20];2471char name[FLEX_ARRAY];2472};24732474struct pack_refs_cb_data {2475unsigned int flags;2476struct ref_dir *packed_refs;2477struct ref_to_prune *ref_to_prune;2478};24792480/*2481 * An each_ref_entry_fn that is run over loose references only. If2482 * the loose reference can be packed, add an entry in the packed ref2483 * cache. If the reference should be pruned, also add it to2484 * ref_to_prune in the pack_refs_cb_data.2485 */2486static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2487{2488struct pack_refs_cb_data *cb = cb_data;2489enum peel_status peel_status;2490struct ref_entry *packed_entry;2491int is_tag_ref =starts_with(entry->name,"refs/tags/");24922493/* ALWAYS pack tags */2494if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2495return0;24962497/* Do not pack symbolic or broken refs: */2498if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2499return0;25002501/* Add a packed ref cache entry equivalent to the loose entry. */2502 peel_status =peel_entry(entry,1);2503if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2504die("internal error peeling reference%s(%s)",2505 entry->name,sha1_to_hex(entry->u.value.sha1));2506 packed_entry =find_ref(cb->packed_refs, entry->name);2507if(packed_entry) {2508/* Overwrite existing packed entry with info from loose entry */2509 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2510hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2511}else{2512 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2513 REF_ISPACKED | REF_KNOWS_PEELED,0);2514add_ref(cb->packed_refs, packed_entry);2515}2516hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25172518/* Schedule the loose reference for pruning if requested. */2519if((cb->flags & PACK_REFS_PRUNE)) {2520int namelen =strlen(entry->name) +1;2521struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2522hashcpy(n->sha1, entry->u.value.sha1);2523strcpy(n->name, entry->name);2524 n->next = cb->ref_to_prune;2525 cb->ref_to_prune = n;2526}2527return0;2528}25292530/*2531 * Remove empty parents, but spare refs/ and immediate subdirs.2532 * Note: munges *name.2533 */2534static voidtry_remove_empty_parents(char*name)2535{2536char*p, *q;2537int i;2538 p = name;2539for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2540while(*p && *p !='/')2541 p++;2542/* tolerate duplicate slashes; see check_refname_format() */2543while(*p =='/')2544 p++;2545}2546for(q = p; *q; q++)2547;2548while(1) {2549while(q > p && *q !='/')2550 q--;2551while(q > p && *(q-1) =='/')2552 q--;2553if(q == p)2554break;2555*q ='\0';2556if(rmdir(git_path("%s", name)))2557break;2558}2559}25602561/* make sure nobody touched the ref, and unlink */2562static voidprune_ref(struct ref_to_prune *r)2563{2564struct ref_transaction *transaction;2565struct strbuf err = STRBUF_INIT;25662567if(check_refname_format(r->name,0))2568return;25692570 transaction =ref_transaction_begin(&err);2571if(!transaction ||2572ref_transaction_delete(transaction, r->name, r->sha1,2573 REF_ISPRUNING,1, NULL, &err) ||2574ref_transaction_commit(transaction, &err)) {2575ref_transaction_free(transaction);2576error("%s", err.buf);2577strbuf_release(&err);2578return;2579}2580ref_transaction_free(transaction);2581strbuf_release(&err);2582try_remove_empty_parents(r->name);2583}25842585static voidprune_refs(struct ref_to_prune *r)2586{2587while(r) {2588prune_ref(r);2589 r = r->next;2590}2591}25922593intpack_refs(unsigned int flags)2594{2595struct pack_refs_cb_data cbdata;25962597memset(&cbdata,0,sizeof(cbdata));2598 cbdata.flags = flags;25992600lock_packed_refs(LOCK_DIE_ON_ERROR);2601 cbdata.packed_refs =get_packed_refs(&ref_cache);26022603do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2604 pack_if_possible_fn, &cbdata);26052606if(commit_packed_refs())2607die_errno("unable to overwrite old ref-pack file");26082609prune_refs(cbdata.ref_to_prune);2610return0;2611}26122613/*2614 * If entry is no longer needed in packed-refs, add it to the string2615 * list pointed to by cb_data. Reasons for deleting entries:2616 *2617 * - Entry is broken.2618 * - Entry is overridden by a loose ref.2619 * - Entry does not point at a valid object.2620 *2621 * In the first and third cases, also emit an error message because these2622 * are indications of repository corruption.2623 */2624static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2625{2626struct string_list *refs_to_delete = cb_data;26272628if(entry->flag & REF_ISBROKEN) {2629/* This shouldn't happen to packed refs. */2630error("%sis broken!", entry->name);2631string_list_append(refs_to_delete, entry->name);2632return0;2633}2634if(!has_sha1_file(entry->u.value.sha1)) {2635unsigned char sha1[20];2636int flags;26372638if(read_ref_full(entry->name,0, sha1, &flags))2639/* We should at least have found the packed ref. */2640die("Internal error");2641if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2642/*2643 * This packed reference is overridden by a2644 * loose reference, so it is OK that its value2645 * is no longer valid; for example, it might2646 * refer to an object that has been garbage2647 * collected. For this purpose we don't even2648 * care whether the loose reference itself is2649 * invalid, broken, symbolic, etc. Silently2650 * remove the packed reference.2651 */2652string_list_append(refs_to_delete, entry->name);2653return0;2654}2655/*2656 * There is no overriding loose reference, so the fact2657 * that this reference doesn't refer to a valid object2658 * indicates some kind of repository corruption.2659 * Report the problem, then omit the reference from2660 * the output.2661 */2662error("%sdoes not point to a valid object!", entry->name);2663string_list_append(refs_to_delete, entry->name);2664return0;2665}26662667return0;2668}26692670intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2671{2672struct ref_dir *packed;2673struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2674struct string_list_item *refname, *ref_to_delete;2675int ret, needs_repacking =0, removed =0;26762677assert(err);26782679/* Look for a packed ref */2680for_each_string_list_item(refname, refnames) {2681if(get_packed_ref(refname->string)) {2682 needs_repacking =1;2683break;2684}2685}26862687/* Avoid locking if we have nothing to do */2688if(!needs_repacking)2689return0;/* no refname exists in packed refs */26902691if(lock_packed_refs(0)) {2692unable_to_lock_message(git_path("packed-refs"), errno, err);2693return-1;2694}2695 packed =get_packed_refs(&ref_cache);26962697/* Remove refnames from the cache */2698for_each_string_list_item(refname, refnames)2699if(remove_entry(packed, refname->string) != -1)2700 removed =1;2701if(!removed) {2702/*2703 * All packed entries disappeared while we were2704 * acquiring the lock.2705 */2706rollback_packed_refs();2707return0;2708}27092710/* Remove any other accumulated cruft */2711do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2712for_each_string_list_item(ref_to_delete, &refs_to_delete) {2713if(remove_entry(packed, ref_to_delete->string) == -1)2714die("internal error");2715}27162717/* Write what remains */2718 ret =commit_packed_refs();2719if(ret)2720strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2721strerror(errno));2722return ret;2723}27242725static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2726{2727assert(err);27282729if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2730/*2731 * loose. The loose file name is the same as the2732 * lockfile name, minus ".lock":2733 */2734char*loose_filename =get_locked_file_path(lock->lk);2735int res =unlink_or_msg(loose_filename, err);2736free(loose_filename);2737if(res)2738return1;2739}2740return0;2741}27422743intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2744{2745struct ref_transaction *transaction;2746struct strbuf err = STRBUF_INIT;27472748 transaction =ref_transaction_begin(&err);2749if(!transaction ||2750ref_transaction_delete(transaction, refname, sha1, delopt,2751 sha1 && !is_null_sha1(sha1), NULL, &err) ||2752ref_transaction_commit(transaction, &err)) {2753error("%s", err.buf);2754ref_transaction_free(transaction);2755strbuf_release(&err);2756return1;2757}2758ref_transaction_free(transaction);2759strbuf_release(&err);2760return0;2761}27622763/*2764 * People using contrib's git-new-workdir have .git/logs/refs ->2765 * /some/other/path/.git/logs/refs, and that may live on another device.2766 *2767 * IOW, to avoid cross device rename errors, the temporary renamed log must2768 * live into logs/refs.2769 */2770#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27712772static intrename_tmp_log(const char*newrefname)2773{2774int attempts_remaining =4;27752776 retry:2777switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2778case SCLD_OK:2779break;/* success */2780case SCLD_VANISHED:2781if(--attempts_remaining >0)2782goto retry;2783/* fall through */2784default:2785error("unable to create directory for%s", newrefname);2786return-1;2787}27882789if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2790if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2791/*2792 * rename(a, b) when b is an existing2793 * directory ought to result in ISDIR, but2794 * Solaris 5.8 gives ENOTDIR. Sheesh.2795 */2796if(remove_empty_directories(git_path("logs/%s", newrefname))) {2797error("Directory not empty: logs/%s", newrefname);2798return-1;2799}2800goto retry;2801}else if(errno == ENOENT && --attempts_remaining >0) {2802/*2803 * Maybe another process just deleted one of2804 * the directories in the path to newrefname.2805 * Try again from the beginning.2806 */2807goto retry;2808}else{2809error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2810 newrefname,strerror(errno));2811return-1;2812}2813}2814return0;2815}28162817static intrename_ref_available(const char*oldname,const char*newname)2818{2819struct string_list skip = STRING_LIST_INIT_NODUP;2820int ret;28212822string_list_insert(&skip, oldname);2823 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2824&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2825string_list_clear(&skip,0);2826return ret;2827}28282829static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2830const char*logmsg);28312832intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2833{2834unsigned char sha1[20], orig_sha1[20];2835int flag =0, logmoved =0;2836struct ref_lock *lock;2837struct stat loginfo;2838int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2839const char*symref = NULL;28402841if(log &&S_ISLNK(loginfo.st_mode))2842returnerror("reflog for%sis a symlink", oldrefname);28432844 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2845 orig_sha1, &flag);2846if(flag & REF_ISSYMREF)2847returnerror("refname%sis a symbolic ref, renaming it is not supported",2848 oldrefname);2849if(!symref)2850returnerror("refname%snot found", oldrefname);28512852if(!rename_ref_available(oldrefname, newrefname))2853return1;28542855if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2856returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2857 oldrefname,strerror(errno));28582859if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2860error("unable to delete old%s", oldrefname);2861goto rollback;2862}28632864if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2865delete_ref(newrefname, sha1, REF_NODEREF)) {2866if(errno==EISDIR) {2867if(remove_empty_directories(git_path("%s", newrefname))) {2868error("Directory not empty:%s", newrefname);2869goto rollback;2870}2871}else{2872error("unable to delete existing%s", newrefname);2873goto rollback;2874}2875}28762877if(log &&rename_tmp_log(newrefname))2878goto rollback;28792880 logmoved = log;28812882 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2883if(!lock) {2884error("unable to lock%sfor update", newrefname);2885goto rollback;2886}2887 lock->force_write =1;2888hashcpy(lock->old_sha1, orig_sha1);2889if(write_ref_sha1(lock, orig_sha1, logmsg)) {2890error("unable to write current sha1 into%s", newrefname);2891goto rollback;2892}28932894return0;28952896 rollback:2897 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2898if(!lock) {2899error("unable to lock%sfor rollback", oldrefname);2900goto rollbacklog;2901}29022903 lock->force_write =1;2904 flag = log_all_ref_updates;2905 log_all_ref_updates =0;2906if(write_ref_sha1(lock, orig_sha1, NULL))2907error("unable to write current sha1 into%s", oldrefname);2908 log_all_ref_updates = flag;29092910 rollbacklog:2911if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2912error("unable to restore logfile%sfrom%s:%s",2913 oldrefname, newrefname,strerror(errno));2914if(!logmoved && log &&2915rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2916error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2917 oldrefname,strerror(errno));29182919return1;2920}29212922static intclose_ref(struct ref_lock *lock)2923{2924if(close_lock_file(lock->lk))2925return-1;2926 lock->lock_fd = -1;2927return0;2928}29292930static intcommit_ref(struct ref_lock *lock)2931{2932if(commit_lock_file(lock->lk))2933return-1;2934 lock->lock_fd = -1;2935return0;2936}29372938/*2939 * copy the reflog message msg to buf, which has been allocated sufficiently2940 * large, while cleaning up the whitespaces. Especially, convert LF to space,2941 * because reflog file is one line per entry.2942 */2943static intcopy_msg(char*buf,const char*msg)2944{2945char*cp = buf;2946char c;2947int wasspace =1;29482949*cp++ ='\t';2950while((c = *msg++)) {2951if(wasspace &&isspace(c))2952continue;2953 wasspace =isspace(c);2954if(wasspace)2955 c =' ';2956*cp++ = c;2957}2958while(buf < cp &&isspace(cp[-1]))2959 cp--;2960*cp++ ='\n';2961return cp - buf;2962}29632964/* This function must set a meaningful errno on failure */2965intlog_ref_setup(const char*refname,char*logfile,int bufsize)2966{2967int logfd, oflags = O_APPEND | O_WRONLY;29682969git_snpath(logfile, bufsize,"logs/%s", refname);2970if(log_all_ref_updates &&2971(starts_with(refname,"refs/heads/") ||2972starts_with(refname,"refs/remotes/") ||2973starts_with(refname,"refs/notes/") ||2974!strcmp(refname,"HEAD"))) {2975if(safe_create_leading_directories(logfile) <0) {2976int save_errno = errno;2977error("unable to create directory for%s", logfile);2978 errno = save_errno;2979return-1;2980}2981 oflags |= O_CREAT;2982}29832984 logfd =open(logfile, oflags,0666);2985if(logfd <0) {2986if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2987return0;29882989if(errno == EISDIR) {2990if(remove_empty_directories(logfile)) {2991int save_errno = errno;2992error("There are still logs under '%s'",2993 logfile);2994 errno = save_errno;2995return-1;2996}2997 logfd =open(logfile, oflags,0666);2998}29993000if(logfd <0) {3001int save_errno = errno;3002error("Unable to append to%s:%s", logfile,3003strerror(errno));3004 errno = save_errno;3005return-1;3006}3007}30083009adjust_shared_perm(logfile);3010close(logfd);3011return0;3012}30133014static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3015const unsigned char*new_sha1,3016const char*committer,const char*msg)3017{3018int msglen, written;3019unsigned maxlen, len;3020char*logrec;30213022 msglen = msg ?strlen(msg) :0;3023 maxlen =strlen(committer) + msglen +100;3024 logrec =xmalloc(maxlen);3025 len =sprintf(logrec,"%s %s %s\n",3026sha1_to_hex(old_sha1),3027sha1_to_hex(new_sha1),3028 committer);3029if(msglen)3030 len +=copy_msg(logrec + len -1, msg) -1;30313032 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3033free(logrec);3034if(written != len)3035return-1;30363037return0;3038}30393040static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3041const unsigned char*new_sha1,const char*msg)3042{3043int logfd, result, oflags = O_APPEND | O_WRONLY;3044char log_file[PATH_MAX];30453046if(log_all_ref_updates <0)3047 log_all_ref_updates = !is_bare_repository();30483049 result =log_ref_setup(refname, log_file,sizeof(log_file));3050if(result)3051return result;30523053 logfd =open(log_file, oflags);3054if(logfd <0)3055return0;3056 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3057git_committer_info(0), msg);3058if(result) {3059int save_errno = errno;3060close(logfd);3061error("Unable to append to%s", log_file);3062 errno = save_errno;3063return-1;3064}3065if(close(logfd)) {3066int save_errno = errno;3067error("Unable to append to%s", log_file);3068 errno = save_errno;3069return-1;3070}3071return0;3072}30733074intis_branch(const char*refname)3075{3076return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3077}30783079/*3080 * Write sha1 into the ref specified by the lock. Make sure that errno3081 * is sane on error.3082 */3083static intwrite_ref_sha1(struct ref_lock *lock,3084const unsigned char*sha1,const char*logmsg)3085{3086static char term ='\n';3087struct object *o;30883089if(!lock) {3090 errno = EINVAL;3091return-1;3092}3093if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3094unlock_ref(lock);3095return0;3096}3097 o =parse_object(sha1);3098if(!o) {3099error("Trying to write ref%swith nonexistent object%s",3100 lock->ref_name,sha1_to_hex(sha1));3101unlock_ref(lock);3102 errno = EINVAL;3103return-1;3104}3105if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3106error("Trying to write non-commit object%sto branch%s",3107sha1_to_hex(sha1), lock->ref_name);3108unlock_ref(lock);3109 errno = EINVAL;3110return-1;3111}3112if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3113write_in_full(lock->lock_fd, &term,1) !=1||3114close_ref(lock) <0) {3115int save_errno = errno;3116error("Couldn't write%s", lock->lk->filename.buf);3117unlock_ref(lock);3118 errno = save_errno;3119return-1;3120}3121clear_loose_ref_cache(&ref_cache);3122if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3123(strcmp(lock->ref_name, lock->orig_ref_name) &&3124log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3125unlock_ref(lock);3126return-1;3127}3128if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3129/*3130 * Special hack: If a branch is updated directly and HEAD3131 * points to it (may happen on the remote side of a push3132 * for example) then logically the HEAD reflog should be3133 * updated too.3134 * A generic solution implies reverse symref information,3135 * but finding all symrefs pointing to the given branch3136 * would be rather costly for this rare event (the direct3137 * update of a branch) to be worth it. So let's cheat and3138 * check with HEAD only which should cover 99% of all usage3139 * scenarios (even 100% of the default ones).3140 */3141unsigned char head_sha1[20];3142int head_flag;3143const char*head_ref;3144 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3145 head_sha1, &head_flag);3146if(head_ref && (head_flag & REF_ISSYMREF) &&3147!strcmp(head_ref, lock->ref_name))3148log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3149}3150if(commit_ref(lock)) {3151error("Couldn't set%s", lock->ref_name);3152unlock_ref(lock);3153return-1;3154}3155unlock_ref(lock);3156return0;3157}31583159intcreate_symref(const char*ref_target,const char*refs_heads_master,3160const char*logmsg)3161{3162const char*lockpath;3163char ref[1000];3164int fd, len, written;3165char*git_HEAD =git_pathdup("%s", ref_target);3166unsigned char old_sha1[20], new_sha1[20];31673168if(logmsg &&read_ref(ref_target, old_sha1))3169hashclr(old_sha1);31703171if(safe_create_leading_directories(git_HEAD) <0)3172returnerror("unable to create directory for%s", git_HEAD);31733174#ifndef NO_SYMLINK_HEAD3175if(prefer_symlink_refs) {3176unlink(git_HEAD);3177if(!symlink(refs_heads_master, git_HEAD))3178goto done;3179fprintf(stderr,"no symlink - falling back to symbolic ref\n");3180}3181#endif31823183 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3184if(sizeof(ref) <= len) {3185error("refname too long:%s", refs_heads_master);3186goto error_free_return;3187}3188 lockpath =mkpath("%s.lock", git_HEAD);3189 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3190if(fd <0) {3191error("Unable to open%sfor writing", lockpath);3192goto error_free_return;3193}3194 written =write_in_full(fd, ref, len);3195if(close(fd) !=0|| written != len) {3196error("Unable to write to%s", lockpath);3197goto error_unlink_return;3198}3199if(rename(lockpath, git_HEAD) <0) {3200error("Unable to create%s", git_HEAD);3201goto error_unlink_return;3202}3203if(adjust_shared_perm(git_HEAD)) {3204error("Unable to fix permissions on%s", lockpath);3205 error_unlink_return:3206unlink_or_warn(lockpath);3207 error_free_return:3208free(git_HEAD);3209return-1;3210}32113212#ifndef NO_SYMLINK_HEAD3213 done:3214#endif3215if(logmsg && !read_ref(refs_heads_master, new_sha1))3216log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32173218free(git_HEAD);3219return0;3220}32213222struct read_ref_at_cb {3223const char*refname;3224unsigned long at_time;3225int cnt;3226int reccnt;3227unsigned char*sha1;3228int found_it;32293230unsigned char osha1[20];3231unsigned char nsha1[20];3232int tz;3233unsigned long date;3234char**msg;3235unsigned long*cutoff_time;3236int*cutoff_tz;3237int*cutoff_cnt;3238};32393240static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3241const char*email,unsigned long timestamp,int tz,3242const char*message,void*cb_data)3243{3244struct read_ref_at_cb *cb = cb_data;32453246 cb->reccnt++;3247 cb->tz = tz;3248 cb->date = timestamp;32493250if(timestamp <= cb->at_time || cb->cnt ==0) {3251if(cb->msg)3252*cb->msg =xstrdup(message);3253if(cb->cutoff_time)3254*cb->cutoff_time = timestamp;3255if(cb->cutoff_tz)3256*cb->cutoff_tz = tz;3257if(cb->cutoff_cnt)3258*cb->cutoff_cnt = cb->reccnt -1;3259/*3260 * we have not yet updated cb->[n|o]sha1 so they still3261 * hold the values for the previous record.3262 */3263if(!is_null_sha1(cb->osha1)) {3264hashcpy(cb->sha1, nsha1);3265if(hashcmp(cb->osha1, nsha1))3266warning("Log for ref%shas gap after%s.",3267 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3268}3269else if(cb->date == cb->at_time)3270hashcpy(cb->sha1, nsha1);3271else if(hashcmp(nsha1, cb->sha1))3272warning("Log for ref%sunexpectedly ended on%s.",3273 cb->refname,show_date(cb->date, cb->tz,3274 DATE_RFC2822));3275hashcpy(cb->osha1, osha1);3276hashcpy(cb->nsha1, nsha1);3277 cb->found_it =1;3278return1;3279}3280hashcpy(cb->osha1, osha1);3281hashcpy(cb->nsha1, nsha1);3282if(cb->cnt >0)3283 cb->cnt--;3284return0;3285}32863287static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3288const char*email,unsigned long timestamp,3289int tz,const char*message,void*cb_data)3290{3291struct read_ref_at_cb *cb = cb_data;32923293if(cb->msg)3294*cb->msg =xstrdup(message);3295if(cb->cutoff_time)3296*cb->cutoff_time = timestamp;3297if(cb->cutoff_tz)3298*cb->cutoff_tz = tz;3299if(cb->cutoff_cnt)3300*cb->cutoff_cnt = cb->reccnt;3301hashcpy(cb->sha1, osha1);3302if(is_null_sha1(cb->sha1))3303hashcpy(cb->sha1, nsha1);3304/* We just want the first entry */3305return1;3306}33073308intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3309unsigned char*sha1,char**msg,3310unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3311{3312struct read_ref_at_cb cb;33133314memset(&cb,0,sizeof(cb));3315 cb.refname = refname;3316 cb.at_time = at_time;3317 cb.cnt = cnt;3318 cb.msg = msg;3319 cb.cutoff_time = cutoff_time;3320 cb.cutoff_tz = cutoff_tz;3321 cb.cutoff_cnt = cutoff_cnt;3322 cb.sha1 = sha1;33233324for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33253326if(!cb.reccnt) {3327if(flags & GET_SHA1_QUIETLY)3328exit(128);3329else3330die("Log for%sis empty.", refname);3331}3332if(cb.found_it)3333return0;33343335for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33363337return1;3338}33393340intreflog_exists(const char*refname)3341{3342struct stat st;33433344return!lstat(git_path("logs/%s", refname), &st) &&3345S_ISREG(st.st_mode);3346}33473348intdelete_reflog(const char*refname)3349{3350returnremove_path(git_path("logs/%s", refname));3351}33523353static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3354{3355unsigned char osha1[20], nsha1[20];3356char*email_end, *message;3357unsigned long timestamp;3358int tz;33593360/* old SP new SP name <email> SP time TAB msg LF */3361if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3362get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3363get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3364!(email_end =strchr(sb->buf +82,'>')) ||3365 email_end[1] !=' '||3366!(timestamp =strtoul(email_end +2, &message,10)) ||3367!message || message[0] !=' '||3368(message[1] !='+'&& message[1] !='-') ||3369!isdigit(message[2]) || !isdigit(message[3]) ||3370!isdigit(message[4]) || !isdigit(message[5]))3371return0;/* corrupt? */3372 email_end[1] ='\0';3373 tz =strtol(message +1, NULL,10);3374if(message[6] !='\t')3375 message +=6;3376else3377 message +=7;3378returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3379}33803381static char*find_beginning_of_line(char*bob,char*scan)3382{3383while(bob < scan && *(--scan) !='\n')3384;/* keep scanning backwards */3385/*3386 * Return either beginning of the buffer, or LF at the end of3387 * the previous line.3388 */3389return scan;3390}33913392intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3393{3394struct strbuf sb = STRBUF_INIT;3395FILE*logfp;3396long pos;3397int ret =0, at_tail =1;33983399 logfp =fopen(git_path("logs/%s", refname),"r");3400if(!logfp)3401return-1;34023403/* Jump to the end */3404if(fseek(logfp,0, SEEK_END) <0)3405returnerror("cannot seek back reflog for%s:%s",3406 refname,strerror(errno));3407 pos =ftell(logfp);3408while(!ret &&0< pos) {3409int cnt;3410size_t nread;3411char buf[BUFSIZ];3412char*endp, *scanp;34133414/* Fill next block from the end */3415 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3416if(fseek(logfp, pos - cnt, SEEK_SET))3417returnerror("cannot seek back reflog for%s:%s",3418 refname,strerror(errno));3419 nread =fread(buf, cnt,1, logfp);3420if(nread !=1)3421returnerror("cannot read%dbytes from reflog for%s:%s",3422 cnt, refname,strerror(errno));3423 pos -= cnt;34243425 scanp = endp = buf + cnt;3426if(at_tail && scanp[-1] =='\n')3427/* Looking at the final LF at the end of the file */3428 scanp--;3429 at_tail =0;34303431while(buf < scanp) {3432/*3433 * terminating LF of the previous line, or the beginning3434 * of the buffer.3435 */3436char*bp;34373438 bp =find_beginning_of_line(buf, scanp);34393440if(*bp =='\n') {3441/*3442 * The newline is the end of the previous line,3443 * so we know we have complete line starting3444 * at (bp + 1). Prefix it onto any prior data3445 * we collected for the line and process it.3446 */3447strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3448 scanp = bp;3449 endp = bp +1;3450 ret =show_one_reflog_ent(&sb, fn, cb_data);3451strbuf_reset(&sb);3452if(ret)3453break;3454}else if(!pos) {3455/*3456 * We are at the start of the buffer, and the3457 * start of the file; there is no previous3458 * line, and we have everything for this one.3459 * Process it, and we can end the loop.3460 */3461strbuf_splice(&sb,0,0, buf, endp - buf);3462 ret =show_one_reflog_ent(&sb, fn, cb_data);3463strbuf_reset(&sb);3464break;3465}34663467if(bp == buf) {3468/*3469 * We are at the start of the buffer, and there3470 * is more file to read backwards. Which means3471 * we are in the middle of a line. Note that we3472 * may get here even if *bp was a newline; that3473 * just means we are at the exact end of the3474 * previous line, rather than some spot in the3475 * middle.3476 *3477 * Save away what we have to be combined with3478 * the data from the next read.3479 */3480strbuf_splice(&sb,0,0, buf, endp - buf);3481break;3482}3483}34843485}3486if(!ret && sb.len)3487die("BUG: reverse reflog parser had leftover data");34883489fclose(logfp);3490strbuf_release(&sb);3491return ret;3492}34933494intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3495{3496FILE*logfp;3497struct strbuf sb = STRBUF_INIT;3498int ret =0;34993500 logfp =fopen(git_path("logs/%s", refname),"r");3501if(!logfp)3502return-1;35033504while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3505 ret =show_one_reflog_ent(&sb, fn, cb_data);3506fclose(logfp);3507strbuf_release(&sb);3508return ret;3509}3510/*3511 * Call fn for each reflog in the namespace indicated by name. name3512 * must be empty or end with '/'. Name will be used as a scratch3513 * space, but its contents will be restored before return.3514 */3515static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3516{3517DIR*d =opendir(git_path("logs/%s", name->buf));3518int retval =0;3519struct dirent *de;3520int oldlen = name->len;35213522if(!d)3523return name->len ? errno :0;35243525while((de =readdir(d)) != NULL) {3526struct stat st;35273528if(de->d_name[0] =='.')3529continue;3530if(ends_with(de->d_name,".lock"))3531continue;3532strbuf_addstr(name, de->d_name);3533if(stat(git_path("logs/%s", name->buf), &st) <0) {3534;/* silently ignore */3535}else{3536if(S_ISDIR(st.st_mode)) {3537strbuf_addch(name,'/');3538 retval =do_for_each_reflog(name, fn, cb_data);3539}else{3540unsigned char sha1[20];3541if(read_ref_full(name->buf,0, sha1, NULL))3542 retval =error("bad ref for%s", name->buf);3543else3544 retval =fn(name->buf, sha1,0, cb_data);3545}3546if(retval)3547break;3548}3549strbuf_setlen(name, oldlen);3550}3551closedir(d);3552return retval;3553}35543555intfor_each_reflog(each_ref_fn fn,void*cb_data)3556{3557int retval;3558struct strbuf name;3559strbuf_init(&name, PATH_MAX);3560 retval =do_for_each_reflog(&name, fn, cb_data);3561strbuf_release(&name);3562return retval;3563}35643565/**3566 * Information needed for a single ref update. Set new_sha1 to the3567 * new value or to zero to delete the ref. To check the old value3568 * while locking the ref, set have_old to 1 and set old_sha1 to the3569 * value or to zero to ensure the ref does not exist before update.3570 */3571struct ref_update {3572unsigned char new_sha1[20];3573unsigned char old_sha1[20];3574int flags;/* REF_NODEREF? */3575int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3576struct ref_lock *lock;3577int type;3578char*msg;3579const char refname[FLEX_ARRAY];3580};35813582/*3583 * Transaction states.3584 * OPEN: The transaction is in a valid state and can accept new updates.3585 * An OPEN transaction can be committed.3586 * CLOSED: A closed transaction is no longer active and no other operations3587 * than free can be used on it in this state.3588 * A transaction can either become closed by successfully committing3589 * an active transaction or if there is a failure while building3590 * the transaction thus rendering it failed/inactive.3591 */3592enum ref_transaction_state {3593 REF_TRANSACTION_OPEN =0,3594 REF_TRANSACTION_CLOSED =13595};35963597/*3598 * Data structure for holding a reference transaction, which can3599 * consist of checks and updates to multiple references, carried out3600 * as atomically as possible. This structure is opaque to callers.3601 */3602struct ref_transaction {3603struct ref_update **updates;3604size_t alloc;3605size_t nr;3606enum ref_transaction_state state;3607};36083609struct ref_transaction *ref_transaction_begin(struct strbuf *err)3610{3611assert(err);36123613returnxcalloc(1,sizeof(struct ref_transaction));3614}36153616voidref_transaction_free(struct ref_transaction *transaction)3617{3618int i;36193620if(!transaction)3621return;36223623for(i =0; i < transaction->nr; i++) {3624free(transaction->updates[i]->msg);3625free(transaction->updates[i]);3626}3627free(transaction->updates);3628free(transaction);3629}36303631static struct ref_update *add_update(struct ref_transaction *transaction,3632const char*refname)3633{3634size_t len =strlen(refname);3635struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36363637strcpy((char*)update->refname, refname);3638ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3639 transaction->updates[transaction->nr++] = update;3640return update;3641}36423643intref_transaction_update(struct ref_transaction *transaction,3644const char*refname,3645const unsigned char*new_sha1,3646const unsigned char*old_sha1,3647int flags,int have_old,const char*msg,3648struct strbuf *err)3649{3650struct ref_update *update;36513652assert(err);36533654if(transaction->state != REF_TRANSACTION_OPEN)3655die("BUG: update called for transaction that is not open");36563657if(have_old && !old_sha1)3658die("BUG: have_old is true but old_sha1 is NULL");36593660if(!is_null_sha1(new_sha1) &&3661check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3662strbuf_addf(err,"refusing to update ref with bad name%s",3663 refname);3664return-1;3665}36663667 update =add_update(transaction, refname);3668hashcpy(update->new_sha1, new_sha1);3669 update->flags = flags;3670 update->have_old = have_old;3671if(have_old)3672hashcpy(update->old_sha1, old_sha1);3673if(msg)3674 update->msg =xstrdup(msg);3675return0;3676}36773678intref_transaction_create(struct ref_transaction *transaction,3679const char*refname,3680const unsigned char*new_sha1,3681int flags,const char*msg,3682struct strbuf *err)3683{3684returnref_transaction_update(transaction, refname, new_sha1,3685 null_sha1, flags,1, msg, err);3686}36873688intref_transaction_delete(struct ref_transaction *transaction,3689const char*refname,3690const unsigned char*old_sha1,3691int flags,int have_old,const char*msg,3692struct strbuf *err)3693{3694returnref_transaction_update(transaction, refname, null_sha1,3695 old_sha1, flags, have_old, msg, err);3696}36973698intupdate_ref(const char*action,const char*refname,3699const unsigned char*sha1,const unsigned char*oldval,3700int flags,enum action_on_err onerr)3701{3702struct ref_transaction *t;3703struct strbuf err = STRBUF_INIT;37043705 t =ref_transaction_begin(&err);3706if(!t ||3707ref_transaction_update(t, refname, sha1, oldval, flags,3708!!oldval, action, &err) ||3709ref_transaction_commit(t, &err)) {3710const char*str ="update_ref failed for ref '%s':%s";37113712ref_transaction_free(t);3713switch(onerr) {3714case UPDATE_REFS_MSG_ON_ERR:3715error(str, refname, err.buf);3716break;3717case UPDATE_REFS_DIE_ON_ERR:3718die(str, refname, err.buf);3719break;3720case UPDATE_REFS_QUIET_ON_ERR:3721break;3722}3723strbuf_release(&err);3724return1;3725}3726strbuf_release(&err);3727ref_transaction_free(t);3728return0;3729}37303731static intref_update_compare(const void*r1,const void*r2)3732{3733const struct ref_update *const*u1 = r1;3734const struct ref_update *const*u2 = r2;3735returnstrcmp((*u1)->refname, (*u2)->refname);3736}37373738static intref_update_reject_duplicates(struct ref_update **updates,int n,3739struct strbuf *err)3740{3741int i;37423743assert(err);37443745for(i =1; i < n; i++)3746if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3747strbuf_addf(err,3748"Multiple updates for ref '%s' not allowed.",3749 updates[i]->refname);3750return1;3751}3752return0;3753}37543755intref_transaction_commit(struct ref_transaction *transaction,3756struct strbuf *err)3757{3758int ret =0, i;3759int n = transaction->nr;3760struct ref_update **updates = transaction->updates;3761struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3762struct string_list_item *ref_to_delete;37633764assert(err);37653766if(transaction->state != REF_TRANSACTION_OPEN)3767die("BUG: commit called for transaction that is not open");37683769if(!n) {3770 transaction->state = REF_TRANSACTION_CLOSED;3771return0;3772}37733774/* Copy, sort, and reject duplicate refs */3775qsort(updates, n,sizeof(*updates), ref_update_compare);3776if(ref_update_reject_duplicates(updates, n, err)) {3777 ret = TRANSACTION_GENERIC_ERROR;3778goto cleanup;3779}37803781/* Acquire all locks while verifying old values */3782for(i =0; i < n; i++) {3783struct ref_update *update = updates[i];3784int flags = update->flags;37853786if(is_null_sha1(update->new_sha1))3787 flags |= REF_DELETING;3788 update->lock =lock_ref_sha1_basic(update->refname,3789(update->have_old ?3790 update->old_sha1 :3791 NULL),3792 NULL,3793 flags,3794&update->type);3795if(!update->lock) {3796 ret = (errno == ENOTDIR)3797? TRANSACTION_NAME_CONFLICT3798: TRANSACTION_GENERIC_ERROR;3799strbuf_addf(err,"Cannot lock the ref '%s'.",3800 update->refname);3801goto cleanup;3802}3803}38043805/* Perform updates first so live commits remain referenced */3806for(i =0; i < n; i++) {3807struct ref_update *update = updates[i];38083809if(!is_null_sha1(update->new_sha1)) {3810if(write_ref_sha1(update->lock, update->new_sha1,3811 update->msg)) {3812 update->lock = NULL;/* freed by write_ref_sha1 */3813strbuf_addf(err,"Cannot update the ref '%s'.",3814 update->refname);3815 ret = TRANSACTION_GENERIC_ERROR;3816goto cleanup;3817}3818 update->lock = NULL;/* freed by write_ref_sha1 */3819}3820}38213822/* Perform deletes now that updates are safely completed */3823for(i =0; i < n; i++) {3824struct ref_update *update = updates[i];38253826if(update->lock) {3827if(delete_ref_loose(update->lock, update->type, err)) {3828 ret = TRANSACTION_GENERIC_ERROR;3829goto cleanup;3830}38313832if(!(update->flags & REF_ISPRUNING))3833string_list_append(&refs_to_delete,3834 update->lock->ref_name);3835}3836}38373838if(repack_without_refs(&refs_to_delete, err)) {3839 ret = TRANSACTION_GENERIC_ERROR;3840goto cleanup;3841}3842for_each_string_list_item(ref_to_delete, &refs_to_delete)3843unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3844clear_loose_ref_cache(&ref_cache);38453846cleanup:3847 transaction->state = REF_TRANSACTION_CLOSED;38483849for(i =0; i < n; i++)3850if(updates[i]->lock)3851unlock_ref(updates[i]->lock);3852string_list_clear(&refs_to_delete,0);3853return ret;3854}38553856char*shorten_unambiguous_ref(const char*refname,int strict)3857{3858int i;3859static char**scanf_fmts;3860static int nr_rules;3861char*short_name;38623863if(!nr_rules) {3864/*3865 * Pre-generate scanf formats from ref_rev_parse_rules[].3866 * Generate a format suitable for scanf from a3867 * ref_rev_parse_rules rule by interpolating "%s" at the3868 * location of the "%.*s".3869 */3870size_t total_len =0;3871size_t offset =0;38723873/* the rule list is NULL terminated, count them first */3874for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3875/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3876 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38773878 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38793880 offset =0;3881for(i =0; i < nr_rules; i++) {3882assert(offset < total_len);3883 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3884 offset +=snprintf(scanf_fmts[i], total_len - offset,3885 ref_rev_parse_rules[i],2,"%s") +1;3886}3887}38883889/* bail out if there are no rules */3890if(!nr_rules)3891returnxstrdup(refname);38923893/* buffer for scanf result, at most refname must fit */3894 short_name =xstrdup(refname);38953896/* skip first rule, it will always match */3897for(i = nr_rules -1; i >0; --i) {3898int j;3899int rules_to_fail = i;3900int short_name_len;39013902if(1!=sscanf(refname, scanf_fmts[i], short_name))3903continue;39043905 short_name_len =strlen(short_name);39063907/*3908 * in strict mode, all (except the matched one) rules3909 * must fail to resolve to a valid non-ambiguous ref3910 */3911if(strict)3912 rules_to_fail = nr_rules;39133914/*3915 * check if the short name resolves to a valid ref,3916 * but use only rules prior to the matched one3917 */3918for(j =0; j < rules_to_fail; j++) {3919const char*rule = ref_rev_parse_rules[j];3920char refname[PATH_MAX];39213922/* skip matched rule */3923if(i == j)3924continue;39253926/*3927 * the short name is ambiguous, if it resolves3928 * (with this previous rule) to a valid ref3929 * read_ref() returns 0 on success3930 */3931mksnpath(refname,sizeof(refname),3932 rule, short_name_len, short_name);3933if(ref_exists(refname))3934break;3935}39363937/*3938 * short name is non-ambiguous if all previous rules3939 * haven't resolved to a valid ref3940 */3941if(j == rules_to_fail)3942return short_name;3943}39443945free(short_name);3946returnxstrdup(refname);3947}39483949static struct string_list *hide_refs;39503951intparse_hide_refs_config(const char*var,const char*value,const char*section)3952{3953if(!strcmp("transfer.hiderefs", var) ||3954/* NEEDSWORK: use parse_config_key() once both are merged */3955(starts_with(var, section) && var[strlen(section)] =='.'&&3956!strcmp(var +strlen(section),".hiderefs"))) {3957char*ref;3958int len;39593960if(!value)3961returnconfig_error_nonbool(var);3962 ref =xstrdup(value);3963 len =strlen(ref);3964while(len && ref[len -1] =='/')3965 ref[--len] ='\0';3966if(!hide_refs) {3967 hide_refs =xcalloc(1,sizeof(*hide_refs));3968 hide_refs->strdup_strings =1;3969}3970string_list_append(hide_refs, ref);3971}3972return0;3973}39743975intref_is_hidden(const char*refname)3976{3977struct string_list_item *item;39783979if(!hide_refs)3980return0;3981for_each_string_list_item(item, hide_refs) {3982int len;3983if(!starts_with(refname, item->string))3984continue;3985 len =strlen(item->string);3986if(!refname[len] || refname[len] =='/')3987return1;3988}3989return0;3990}39913992struct expire_reflog_cb {3993unsigned int flags;3994 reflog_expiry_should_prune_fn *should_prune_fn;3995void*policy_cb;3996FILE*newlog;3997unsigned char last_kept_sha1[20];3998};39994000static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4001const char*email,unsigned long timestamp,int tz,4002const char*message,void*cb_data)4003{4004struct expire_reflog_cb *cb = cb_data;4005struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;40064007if(cb->flags & EXPIRE_REFLOGS_REWRITE)4008 osha1 = cb->last_kept_sha1;40094010if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4011 message, policy_cb)) {4012if(!cb->newlog)4013printf("would prune%s", message);4014else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4015printf("prune%s", message);4016}else{4017if(cb->newlog) {4018fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4019sha1_to_hex(osha1),sha1_to_hex(nsha1),4020 email, timestamp, tz, message);4021hashcpy(cb->last_kept_sha1, nsha1);4022}4023if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4024printf("keep%s", message);4025}4026return0;4027}40284029intreflog_expire(const char*refname,const unsigned char*sha1,4030unsigned int flags,4031 reflog_expiry_prepare_fn prepare_fn,4032 reflog_expiry_should_prune_fn should_prune_fn,4033 reflog_expiry_cleanup_fn cleanup_fn,4034void*policy_cb_data)4035{4036static struct lock_file reflog_lock;4037struct expire_reflog_cb cb;4038struct ref_lock *lock;4039char*log_file;4040int status =0;40414042memset(&cb,0,sizeof(cb));4043 cb.flags = flags;4044 cb.policy_cb = policy_cb_data;4045 cb.should_prune_fn = should_prune_fn;40464047/*4048 * The reflog file is locked by holding the lock on the4049 * reference itself, plus we might need to update the4050 * reference if --updateref was specified:4051 */4052 lock =lock_ref_sha1_basic(refname, sha1, NULL,0, NULL);4053if(!lock)4054returnerror("cannot lock ref '%s'", refname);4055if(!reflog_exists(refname)) {4056unlock_ref(lock);4057return0;4058}40594060 log_file =git_pathdup("logs/%s", refname);4061if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4062/*4063 * Even though holding $GIT_DIR/logs/$reflog.lock has4064 * no locking implications, we use the lock_file4065 * machinery here anyway because it does a lot of the4066 * work we need, including cleaning up if the program4067 * exits unexpectedly.4068 */4069if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4070struct strbuf err = STRBUF_INIT;4071unable_to_lock_message(log_file, errno, &err);4072error("%s", err.buf);4073strbuf_release(&err);4074goto failure;4075}4076 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4077if(!cb.newlog) {4078error("cannot fdopen%s(%s)",4079 reflog_lock.filename.buf,strerror(errno));4080goto failure;4081}4082}40834084(*prepare_fn)(refname, sha1, cb.policy_cb);4085for_each_reflog_ent(refname, expire_reflog_ent, &cb);4086(*cleanup_fn)(cb.policy_cb);40874088if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4089if(close_lock_file(&reflog_lock)) {4090 status |=error("couldn't write%s:%s", log_file,4091strerror(errno));4092}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&4093(write_in_full(lock->lock_fd,4094sha1_to_hex(cb.last_kept_sha1),40) !=40||4095write_str_in_full(lock->lock_fd,"\n") !=1||4096close_ref(lock) <0)) {4097 status |=error("couldn't write%s",4098 lock->lk->filename.buf);4099rollback_lock_file(&reflog_lock);4100}else if(commit_lock_file(&reflog_lock)) {4101 status |=error("unable to commit reflog '%s' (%s)",4102 log_file,strerror(errno));4103}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&commit_ref(lock)) {4104 status |=error("couldn't set%s", lock->ref_name);4105}4106}4107free(log_file);4108unlock_ref(lock);4109return status;41104111 failure:4112rollback_lock_file(&reflog_lock);4113free(log_file);4114unlock_ref(lock);4115return-1;4116}