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 0x0100 48/* 49 * Try to read one refname component from the front of refname. 50 * Return the length of the component found, or -1 if the component is 51 * not legal. It is legal if it is something reasonable to have under 52 * ".git/refs/"; We do not like it if: 53 * 54 * - any path component of it begins with ".", or 55 * - it has double dots "..", or 56 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 57 * - it ends with a "/". 58 * - it ends with ".lock" 59 * - it contains a "\" (backslash) 60 */ 61static intcheck_refname_component(const char*refname,int flags) 62{ 63const char*cp; 64char last ='\0'; 65 66for(cp = refname; ; cp++) { 67int ch = *cp &255; 68unsigned char disp = refname_disposition[ch]; 69switch(disp) { 70case1: 71goto out; 72case2: 73if(last =='.') 74return-1;/* Refname contains "..". */ 75break; 76case3: 77if(last =='@') 78return-1;/* Refname contains "@{". */ 79break; 80case4: 81return-1; 82} 83 last = ch; 84} 85out: 86if(cp == refname) 87return0;/* Component has zero length. */ 88if(refname[0] =='.') 89return-1;/* Component starts with '.'. */ 90if(cp - refname >= LOCK_SUFFIX_LEN && 91!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 92return-1;/* Refname ends with ".lock". */ 93return cp - refname; 94} 95 96intcheck_refname_format(const char*refname,int flags) 97{ 98int component_len, component_count =0; 99 100if(!strcmp(refname,"@")) 101/* Refname is a single character '@'. */ 102return-1; 103 104while(1) { 105/* We are at the start of a path component. */ 106 component_len =check_refname_component(refname, flags); 107if(component_len <=0) { 108if((flags & REFNAME_REFSPEC_PATTERN) && 109 refname[0] =='*'&& 110(refname[1] =='\0'|| refname[1] =='/')) { 111/* Accept one wildcard as a full refname component. */ 112 flags &= ~REFNAME_REFSPEC_PATTERN; 113 component_len =1; 114}else{ 115return-1; 116} 117} 118 component_count++; 119if(refname[component_len] =='\0') 120break; 121/* Skip to next component. */ 122 refname += component_len +1; 123} 124 125if(refname[component_len -1] =='.') 126return-1;/* Refname ends with '.'. */ 127if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 128return-1;/* Refname has only one component. */ 129return0; 130} 131 132struct ref_entry; 133 134/* 135 * Information used (along with the information in ref_entry) to 136 * describe a single cached reference. This data structure only 137 * occurs embedded in a union in struct ref_entry, and only when 138 * (ref_entry->flag & REF_DIR) is zero. 139 */ 140struct ref_value { 141/* 142 * The name of the object to which this reference resolves 143 * (which may be a tag object). If REF_ISBROKEN, this is 144 * null. If REF_ISSYMREF, then this is the name of the object 145 * referred to by the last reference in the symlink chain. 146 */ 147unsigned char sha1[20]; 148 149/* 150 * If REF_KNOWS_PEELED, then this field holds the peeled value 151 * of this reference, or null if the reference is known not to 152 * be peelable. See the documentation for peel_ref() for an 153 * exact definition of "peelable". 154 */ 155unsigned char peeled[20]; 156}; 157 158struct ref_cache; 159 160/* 161 * Information used (along with the information in ref_entry) to 162 * describe a level in the hierarchy of references. This data 163 * structure only occurs embedded in a union in struct ref_entry, and 164 * only when (ref_entry.flag & REF_DIR) is set. In that case, 165 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 166 * in the directory have already been read: 167 * 168 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 169 * or packed references, already read. 170 * 171 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 172 * references that hasn't been read yet (nor has any of its 173 * subdirectories). 174 * 175 * Entries within a directory are stored within a growable array of 176 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 177 * sorted are sorted by their component name in strcmp() order and the 178 * remaining entries are unsorted. 179 * 180 * Loose references are read lazily, one directory at a time. When a 181 * directory of loose references is read, then all of the references 182 * in that directory are stored, and REF_INCOMPLETE stubs are created 183 * for any subdirectories, but the subdirectories themselves are not 184 * read. The reading is triggered by get_ref_dir(). 185 */ 186struct ref_dir { 187int nr, alloc; 188 189/* 190 * Entries with index 0 <= i < sorted are sorted by name. New 191 * entries are appended to the list unsorted, and are sorted 192 * only when required; thus we avoid the need to sort the list 193 * after the addition of every reference. 194 */ 195int sorted; 196 197/* A pointer to the ref_cache that contains this ref_dir. */ 198struct ref_cache *ref_cache; 199 200struct ref_entry **entries; 201}; 202 203/* 204 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 205 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 206 * public values; see refs.h. 207 */ 208 209/* 210 * The field ref_entry->u.value.peeled of this value entry contains 211 * the correct peeled value for the reference, which might be 212 * null_sha1 if the reference is not a tag or if it is broken. 213 */ 214#define REF_KNOWS_PEELED 0x10 215 216/* ref_entry represents a directory of references */ 217#define REF_DIR 0x20 218 219/* 220 * Entry has not yet been read from disk (used only for REF_DIR 221 * entries representing loose references) 222 */ 223#define REF_INCOMPLETE 0x40 224 225/* 226 * A ref_entry represents either a reference or a "subdirectory" of 227 * references. 228 * 229 * Each directory in the reference namespace is represented by a 230 * ref_entry with (flags & REF_DIR) set and containing a subdir member 231 * that holds the entries in that directory that have been read so 232 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 233 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 234 * used for loose reference directories. 235 * 236 * References are represented by a ref_entry with (flags & REF_DIR) 237 * unset and a value member that describes the reference's value. The 238 * flag member is at the ref_entry level, but it is also needed to 239 * interpret the contents of the value field (in other words, a 240 * ref_value object is not very much use without the enclosing 241 * ref_entry). 242 * 243 * Reference names cannot end with slash and directories' names are 244 * always stored with a trailing slash (except for the top-level 245 * directory, which is always denoted by ""). This has two nice 246 * consequences: (1) when the entries in each subdir are sorted 247 * lexicographically by name (as they usually are), the references in 248 * a whole tree can be generated in lexicographic order by traversing 249 * the tree in left-to-right, depth-first order; (2) the names of 250 * references and subdirectories cannot conflict, and therefore the 251 * presence of an empty subdirectory does not block the creation of a 252 * similarly-named reference. (The fact that reference names with the 253 * same leading components can conflict *with each other* is a 254 * separate issue that is regulated by is_refname_available().) 255 * 256 * Please note that the name field contains the fully-qualified 257 * reference (or subdirectory) name. Space could be saved by only 258 * storing the relative names. But that would require the full names 259 * to be generated on the fly when iterating in do_for_each_ref(), and 260 * would break callback functions, who have always been able to assume 261 * that the name strings that they are passed will not be freed during 262 * the iteration. 263 */ 264struct ref_entry { 265unsigned char flag;/* ISSYMREF? ISPACKED? */ 266union{ 267struct ref_value value;/* if not (flags&REF_DIR) */ 268struct ref_dir subdir;/* if (flags&REF_DIR) */ 269} u; 270/* 271 * The full name of the reference (e.g., "refs/heads/master") 272 * or the full name of the directory with a trailing slash 273 * (e.g., "refs/heads/"): 274 */ 275char name[FLEX_ARRAY]; 276}; 277 278static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 279 280static struct ref_dir *get_ref_dir(struct ref_entry *entry) 281{ 282struct ref_dir *dir; 283assert(entry->flag & REF_DIR); 284 dir = &entry->u.subdir; 285if(entry->flag & REF_INCOMPLETE) { 286read_loose_refs(entry->name, dir); 287 entry->flag &= ~REF_INCOMPLETE; 288} 289return dir; 290} 291 292/* 293 * Check if a refname is safe. 294 * For refs that start with "refs/" we consider it safe as long they do 295 * not try to resolve to outside of refs/. 296 * 297 * For all other refs we only consider them safe iff they only contain 298 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 299 * "config"). 300 */ 301static intrefname_is_safe(const char*refname) 302{ 303if(starts_with(refname,"refs/")) { 304char*buf; 305int result; 306 307 buf =xmalloc(strlen(refname) +1); 308/* 309 * Does the refname try to escape refs/? 310 * For example: refs/foo/../bar is safe but refs/foo/../../bar 311 * is not. 312 */ 313 result = !normalize_path_copy(buf, refname +strlen("refs/")); 314free(buf); 315return result; 316} 317while(*refname) { 318if(!isupper(*refname) && *refname !='_') 319return0; 320 refname++; 321} 322return1; 323} 324 325static struct ref_entry *create_ref_entry(const char*refname, 326const unsigned char*sha1,int flag, 327int check_name) 328{ 329int len; 330struct ref_entry *ref; 331 332if(check_name && 333check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 334die("Reference has invalid format: '%s'", refname); 335if(!check_name && !refname_is_safe(refname)) 336die("Reference has invalid name: '%s'", refname); 337 len =strlen(refname) +1; 338 ref =xmalloc(sizeof(struct ref_entry) + len); 339hashcpy(ref->u.value.sha1, sha1); 340hashclr(ref->u.value.peeled); 341memcpy(ref->name, refname, len); 342 ref->flag = flag; 343return ref; 344} 345 346static voidclear_ref_dir(struct ref_dir *dir); 347 348static voidfree_ref_entry(struct ref_entry *entry) 349{ 350if(entry->flag & REF_DIR) { 351/* 352 * Do not use get_ref_dir() here, as that might 353 * trigger the reading of loose refs. 354 */ 355clear_ref_dir(&entry->u.subdir); 356} 357free(entry); 358} 359 360/* 361 * Add a ref_entry to the end of dir (unsorted). Entry is always 362 * stored directly in dir; no recursion into subdirectories is 363 * done. 364 */ 365static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 366{ 367ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 368 dir->entries[dir->nr++] = entry; 369/* optimize for the case that entries are added in order */ 370if(dir->nr ==1|| 371(dir->nr == dir->sorted +1&& 372strcmp(dir->entries[dir->nr -2]->name, 373 dir->entries[dir->nr -1]->name) <0)) 374 dir->sorted = dir->nr; 375} 376 377/* 378 * Clear and free all entries in dir, recursively. 379 */ 380static voidclear_ref_dir(struct ref_dir *dir) 381{ 382int i; 383for(i =0; i < dir->nr; i++) 384free_ref_entry(dir->entries[i]); 385free(dir->entries); 386 dir->sorted = dir->nr = dir->alloc =0; 387 dir->entries = NULL; 388} 389 390/* 391 * Create a struct ref_entry object for the specified dirname. 392 * dirname is the name of the directory with a trailing slash (e.g., 393 * "refs/heads/") or "" for the top-level directory. 394 */ 395static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 396const char*dirname,size_t len, 397int incomplete) 398{ 399struct ref_entry *direntry; 400 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 401memcpy(direntry->name, dirname, len); 402 direntry->name[len] ='\0'; 403 direntry->u.subdir.ref_cache = ref_cache; 404 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 405return direntry; 406} 407 408static intref_entry_cmp(const void*a,const void*b) 409{ 410struct ref_entry *one = *(struct ref_entry **)a; 411struct ref_entry *two = *(struct ref_entry **)b; 412returnstrcmp(one->name, two->name); 413} 414 415static voidsort_ref_dir(struct ref_dir *dir); 416 417struct string_slice { 418size_t len; 419const char*str; 420}; 421 422static intref_entry_cmp_sslice(const void*key_,const void*ent_) 423{ 424const struct string_slice *key = key_; 425const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 426int cmp =strncmp(key->str, ent->name, key->len); 427if(cmp) 428return cmp; 429return'\0'- (unsigned char)ent->name[key->len]; 430} 431 432/* 433 * Return the index of the entry with the given refname from the 434 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 435 * no such entry is found. dir must already be complete. 436 */ 437static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 438{ 439struct ref_entry **r; 440struct string_slice key; 441 442if(refname == NULL || !dir->nr) 443return-1; 444 445sort_ref_dir(dir); 446 key.len = len; 447 key.str = refname; 448 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 449 ref_entry_cmp_sslice); 450 451if(r == NULL) 452return-1; 453 454return r - dir->entries; 455} 456 457/* 458 * Search for a directory entry directly within dir (without 459 * recursing). Sort dir if necessary. subdirname must be a directory 460 * name (i.e., end in '/'). If mkdir is set, then create the 461 * directory if it is missing; otherwise, return NULL if the desired 462 * directory cannot be found. dir must already be complete. 463 */ 464static struct ref_dir *search_for_subdir(struct ref_dir *dir, 465const char*subdirname,size_t len, 466int mkdir) 467{ 468int entry_index =search_ref_dir(dir, subdirname, len); 469struct ref_entry *entry; 470if(entry_index == -1) { 471if(!mkdir) 472return NULL; 473/* 474 * Since dir is complete, the absence of a subdir 475 * means that the subdir really doesn't exist; 476 * therefore, create an empty record for it but mark 477 * the record complete. 478 */ 479 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 480add_entry_to_dir(dir, entry); 481}else{ 482 entry = dir->entries[entry_index]; 483} 484returnget_ref_dir(entry); 485} 486 487/* 488 * If refname is a reference name, find the ref_dir within the dir 489 * tree that should hold refname. If refname is a directory name 490 * (i.e., ends in '/'), then return that ref_dir itself. dir must 491 * represent the top-level directory and must already be complete. 492 * Sort ref_dirs and recurse into subdirectories as necessary. If 493 * mkdir is set, then create any missing directories; otherwise, 494 * return NULL if the desired directory cannot be found. 495 */ 496static struct ref_dir *find_containing_dir(struct ref_dir *dir, 497const char*refname,int mkdir) 498{ 499const char*slash; 500for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 501size_t dirnamelen = slash - refname +1; 502struct ref_dir *subdir; 503 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 504if(!subdir) { 505 dir = NULL; 506break; 507} 508 dir = subdir; 509} 510 511return dir; 512} 513 514/* 515 * Find the value entry with the given name in dir, sorting ref_dirs 516 * and recursing into subdirectories as necessary. If the name is not 517 * found or it corresponds to a directory entry, return NULL. 518 */ 519static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 520{ 521int entry_index; 522struct ref_entry *entry; 523 dir =find_containing_dir(dir, refname,0); 524if(!dir) 525return NULL; 526 entry_index =search_ref_dir(dir, refname,strlen(refname)); 527if(entry_index == -1) 528return NULL; 529 entry = dir->entries[entry_index]; 530return(entry->flag & REF_DIR) ? NULL : entry; 531} 532 533/* 534 * Remove the entry with the given name from dir, recursing into 535 * subdirectories as necessary. If refname is the name of a directory 536 * (i.e., ends with '/'), then remove the directory and its contents. 537 * If the removal was successful, return the number of entries 538 * remaining in the directory entry that contained the deleted entry. 539 * If the name was not found, return -1. Please note that this 540 * function only deletes the entry from the cache; it does not delete 541 * it from the filesystem or ensure that other cache entries (which 542 * might be symbolic references to the removed entry) are updated. 543 * Nor does it remove any containing dir entries that might be made 544 * empty by the removal. dir must represent the top-level directory 545 * and must already be complete. 546 */ 547static intremove_entry(struct ref_dir *dir,const char*refname) 548{ 549int refname_len =strlen(refname); 550int entry_index; 551struct ref_entry *entry; 552int is_dir = refname[refname_len -1] =='/'; 553if(is_dir) { 554/* 555 * refname represents a reference directory. Remove 556 * the trailing slash; otherwise we will get the 557 * directory *representing* refname rather than the 558 * one *containing* it. 559 */ 560char*dirname =xmemdupz(refname, refname_len -1); 561 dir =find_containing_dir(dir, dirname,0); 562free(dirname); 563}else{ 564 dir =find_containing_dir(dir, refname,0); 565} 566if(!dir) 567return-1; 568 entry_index =search_ref_dir(dir, refname, refname_len); 569if(entry_index == -1) 570return-1; 571 entry = dir->entries[entry_index]; 572 573memmove(&dir->entries[entry_index], 574&dir->entries[entry_index +1], 575(dir->nr - entry_index -1) *sizeof(*dir->entries) 576); 577 dir->nr--; 578if(dir->sorted > entry_index) 579 dir->sorted--; 580free_ref_entry(entry); 581return dir->nr; 582} 583 584/* 585 * Add a ref_entry to the ref_dir (unsorted), recursing into 586 * subdirectories as necessary. dir must represent the top-level 587 * directory. Return 0 on success. 588 */ 589static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 590{ 591 dir =find_containing_dir(dir, ref->name,1); 592if(!dir) 593return-1; 594add_entry_to_dir(dir, ref); 595return0; 596} 597 598/* 599 * Emit a warning and return true iff ref1 and ref2 have the same name 600 * and the same sha1. Die if they have the same name but different 601 * sha1s. 602 */ 603static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 604{ 605if(strcmp(ref1->name, ref2->name)) 606return0; 607 608/* Duplicate name; make sure that they don't conflict: */ 609 610if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 611/* This is impossible by construction */ 612die("Reference directory conflict:%s", ref1->name); 613 614if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 615die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 616 617warning("Duplicated ref:%s", ref1->name); 618return1; 619} 620 621/* 622 * Sort the entries in dir non-recursively (if they are not already 623 * sorted) and remove any duplicate entries. 624 */ 625static voidsort_ref_dir(struct ref_dir *dir) 626{ 627int i, j; 628struct ref_entry *last = NULL; 629 630/* 631 * This check also prevents passing a zero-length array to qsort(), 632 * which is a problem on some platforms. 633 */ 634if(dir->sorted == dir->nr) 635return; 636 637qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 638 639/* Remove any duplicates: */ 640for(i =0, j =0; j < dir->nr; j++) { 641struct ref_entry *entry = dir->entries[j]; 642if(last &&is_dup_ref(last, entry)) 643free_ref_entry(entry); 644else 645 last = dir->entries[i++] = entry; 646} 647 dir->sorted = dir->nr = i; 648} 649 650/* Include broken references in a do_for_each_ref*() iteration: */ 651#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 652 653/* 654 * Return true iff the reference described by entry can be resolved to 655 * an object in the database. Emit a warning if the referred-to 656 * object does not exist. 657 */ 658static intref_resolves_to_object(struct ref_entry *entry) 659{ 660if(entry->flag & REF_ISBROKEN) 661return0; 662if(!has_sha1_file(entry->u.value.sha1)) { 663error("%sdoes not point to a valid object!", entry->name); 664return0; 665} 666return1; 667} 668 669/* 670 * current_ref is a performance hack: when iterating over references 671 * using the for_each_ref*() functions, current_ref is set to the 672 * current reference's entry before calling the callback function. If 673 * the callback function calls peel_ref(), then peel_ref() first 674 * checks whether the reference to be peeled is the current reference 675 * (it usually is) and if so, returns that reference's peeled version 676 * if it is available. This avoids a refname lookup in a common case. 677 */ 678static struct ref_entry *current_ref; 679 680typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 681 682struct ref_entry_cb { 683const char*base; 684int trim; 685int flags; 686 each_ref_fn *fn; 687void*cb_data; 688}; 689 690/* 691 * Handle one reference in a do_for_each_ref*()-style iteration, 692 * calling an each_ref_fn for each entry. 693 */ 694static intdo_one_ref(struct ref_entry *entry,void*cb_data) 695{ 696struct ref_entry_cb *data = cb_data; 697struct ref_entry *old_current_ref; 698int retval; 699 700if(!starts_with(entry->name, data->base)) 701return0; 702 703if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 704!ref_resolves_to_object(entry)) 705return0; 706 707/* Store the old value, in case this is a recursive call: */ 708 old_current_ref = current_ref; 709 current_ref = entry; 710 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 711 entry->flag, data->cb_data); 712 current_ref = old_current_ref; 713return retval; 714} 715 716/* 717 * Call fn for each reference in dir that has index in the range 718 * offset <= index < dir->nr. Recurse into subdirectories that are in 719 * that index range, sorting them before iterating. This function 720 * does not sort dir itself; it should be sorted beforehand. fn is 721 * called for all references, including broken ones. 722 */ 723static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 724 each_ref_entry_fn fn,void*cb_data) 725{ 726int i; 727assert(dir->sorted == dir->nr); 728for(i = offset; i < dir->nr; i++) { 729struct ref_entry *entry = dir->entries[i]; 730int retval; 731if(entry->flag & REF_DIR) { 732struct ref_dir *subdir =get_ref_dir(entry); 733sort_ref_dir(subdir); 734 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 735}else{ 736 retval =fn(entry, cb_data); 737} 738if(retval) 739return retval; 740} 741return0; 742} 743 744/* 745 * Call fn for each reference in the union of dir1 and dir2, in order 746 * by refname. Recurse into subdirectories. If a value entry appears 747 * in both dir1 and dir2, then only process the version that is in 748 * dir2. The input dirs must already be sorted, but subdirs will be 749 * sorted as needed. fn is called for all references, including 750 * broken ones. 751 */ 752static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 753struct ref_dir *dir2, 754 each_ref_entry_fn fn,void*cb_data) 755{ 756int retval; 757int i1 =0, i2 =0; 758 759assert(dir1->sorted == dir1->nr); 760assert(dir2->sorted == dir2->nr); 761while(1) { 762struct ref_entry *e1, *e2; 763int cmp; 764if(i1 == dir1->nr) { 765returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 766} 767if(i2 == dir2->nr) { 768returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 769} 770 e1 = dir1->entries[i1]; 771 e2 = dir2->entries[i2]; 772 cmp =strcmp(e1->name, e2->name); 773if(cmp ==0) { 774if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 775/* Both are directories; descend them in parallel. */ 776struct ref_dir *subdir1 =get_ref_dir(e1); 777struct ref_dir *subdir2 =get_ref_dir(e2); 778sort_ref_dir(subdir1); 779sort_ref_dir(subdir2); 780 retval =do_for_each_entry_in_dirs( 781 subdir1, subdir2, fn, cb_data); 782 i1++; 783 i2++; 784}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 785/* Both are references; ignore the one from dir1. */ 786 retval =fn(e2, cb_data); 787 i1++; 788 i2++; 789}else{ 790die("conflict between reference and directory:%s", 791 e1->name); 792} 793}else{ 794struct ref_entry *e; 795if(cmp <0) { 796 e = e1; 797 i1++; 798}else{ 799 e = e2; 800 i2++; 801} 802if(e->flag & REF_DIR) { 803struct ref_dir *subdir =get_ref_dir(e); 804sort_ref_dir(subdir); 805 retval =do_for_each_entry_in_dir( 806 subdir,0, fn, cb_data); 807}else{ 808 retval =fn(e, cb_data); 809} 810} 811if(retval) 812return retval; 813} 814} 815 816/* 817 * Load all of the refs from the dir into our in-memory cache. The hard work 818 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 819 * through all of the sub-directories. We do not even need to care about 820 * sorting, as traversal order does not matter to us. 821 */ 822static voidprime_ref_dir(struct ref_dir *dir) 823{ 824int i; 825for(i =0; i < dir->nr; i++) { 826struct ref_entry *entry = dir->entries[i]; 827if(entry->flag & REF_DIR) 828prime_ref_dir(get_ref_dir(entry)); 829} 830} 831 832static intentry_matches(struct ref_entry *entry,const struct string_list *list) 833{ 834return list &&string_list_has_string(list, entry->name); 835} 836 837struct nonmatching_ref_data { 838const struct string_list *skip; 839struct ref_entry *found; 840}; 841 842static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 843{ 844struct nonmatching_ref_data *data = vdata; 845 846if(entry_matches(entry, data->skip)) 847return0; 848 849 data->found = entry; 850return1; 851} 852 853static voidreport_refname_conflict(struct ref_entry *entry, 854const char*refname) 855{ 856error("'%s' exists; cannot create '%s'", entry->name, refname); 857} 858 859/* 860 * Return true iff a reference named refname could be created without 861 * conflicting with the name of an existing reference in dir. If 862 * skip is non-NULL, ignore potential conflicts with refs in skip 863 * (e.g., because they are scheduled for deletion in the same 864 * operation). 865 * 866 * Two reference names conflict if one of them exactly matches the 867 * leading components of the other; e.g., "foo/bar" conflicts with 868 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 869 * "foo/barbados". 870 * 871 * skip must be sorted. 872 */ 873static intis_refname_available(const char*refname, 874const struct string_list *skip, 875struct ref_dir *dir) 876{ 877const char*slash; 878size_t len; 879int pos; 880char*dirname; 881 882for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 883/* 884 * We are still at a leading dir of the refname; we are 885 * looking for a conflict with a leaf entry. 886 * 887 * If we find one, we still must make sure it is 888 * not in "skip". 889 */ 890 pos =search_ref_dir(dir, refname, slash - refname); 891if(pos >=0) { 892struct ref_entry *entry = dir->entries[pos]; 893if(entry_matches(entry, skip)) 894return1; 895report_refname_conflict(entry, refname); 896return0; 897} 898 899 900/* 901 * Otherwise, we can try to continue our search with 902 * the next component; if we come up empty, we know 903 * there is nothing under this whole prefix. 904 */ 905 pos =search_ref_dir(dir, refname, slash +1- refname); 906if(pos <0) 907return1; 908 909 dir =get_ref_dir(dir->entries[pos]); 910} 911 912/* 913 * We are at the leaf of our refname; we want to 914 * make sure there are no directories which match it. 915 */ 916 len =strlen(refname); 917 dirname =xmallocz(len +1); 918sprintf(dirname,"%s/", refname); 919 pos =search_ref_dir(dir, dirname, len +1); 920free(dirname); 921 922if(pos >=0) { 923/* 924 * We found a directory named "refname". It is a 925 * problem iff it contains any ref that is not 926 * in "skip". 927 */ 928struct ref_entry *entry = dir->entries[pos]; 929struct ref_dir *dir =get_ref_dir(entry); 930struct nonmatching_ref_data data; 931 932 data.skip = skip; 933sort_ref_dir(dir); 934if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 935return1; 936 937report_refname_conflict(data.found, refname); 938return0; 939} 940 941/* 942 * There is no point in searching for another leaf 943 * node which matches it; such an entry would be the 944 * ref we are looking for, not a conflict. 945 */ 946return1; 947} 948 949struct packed_ref_cache { 950struct ref_entry *root; 951 952/* 953 * Count of references to the data structure in this instance, 954 * including the pointer from ref_cache::packed if any. The 955 * data will not be freed as long as the reference count is 956 * nonzero. 957 */ 958unsigned int referrers; 959 960/* 961 * Iff the packed-refs file associated with this instance is 962 * currently locked for writing, this points at the associated 963 * lock (which is owned by somebody else). The referrer count 964 * is also incremented when the file is locked and decremented 965 * when it is unlocked. 966 */ 967struct lock_file *lock; 968 969/* The metadata from when this packed-refs cache was read */ 970struct stat_validity validity; 971}; 972 973/* 974 * Future: need to be in "struct repository" 975 * when doing a full libification. 976 */ 977static struct ref_cache { 978struct ref_cache *next; 979struct ref_entry *loose; 980struct packed_ref_cache *packed; 981/* 982 * The submodule name, or "" for the main repo. We allocate 983 * length 1 rather than FLEX_ARRAY so that the main ref_cache 984 * is initialized correctly. 985 */ 986char name[1]; 987} ref_cache, *submodule_ref_caches; 988 989/* Lock used for the main packed-refs file: */ 990static struct lock_file packlock; 991 992/* 993 * Increment the reference count of *packed_refs. 994 */ 995static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 996{ 997 packed_refs->referrers++; 998} 9991000/*1001 * Decrease the reference count of *packed_refs. If it goes to zero,1002 * free *packed_refs and return true; otherwise return false.1003 */1004static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1005{1006if(!--packed_refs->referrers) {1007free_ref_entry(packed_refs->root);1008stat_validity_clear(&packed_refs->validity);1009free(packed_refs);1010return1;1011}else{1012return0;1013}1014}10151016static voidclear_packed_ref_cache(struct ref_cache *refs)1017{1018if(refs->packed) {1019struct packed_ref_cache *packed_refs = refs->packed;10201021if(packed_refs->lock)1022die("internal error: packed-ref cache cleared while locked");1023 refs->packed = NULL;1024release_packed_ref_cache(packed_refs);1025}1026}10271028static voidclear_loose_ref_cache(struct ref_cache *refs)1029{1030if(refs->loose) {1031free_ref_entry(refs->loose);1032 refs->loose = NULL;1033}1034}10351036static struct ref_cache *create_ref_cache(const char*submodule)1037{1038int len;1039struct ref_cache *refs;1040if(!submodule)1041 submodule ="";1042 len =strlen(submodule) +1;1043 refs =xcalloc(1,sizeof(struct ref_cache) + len);1044memcpy(refs->name, submodule, len);1045return refs;1046}10471048/*1049 * Return a pointer to a ref_cache for the specified submodule. For1050 * the main repository, use submodule==NULL. The returned structure1051 * will be allocated and initialized but not necessarily populated; it1052 * should not be freed.1053 */1054static struct ref_cache *get_ref_cache(const char*submodule)1055{1056struct ref_cache *refs;10571058if(!submodule || !*submodule)1059return&ref_cache;10601061for(refs = submodule_ref_caches; refs; refs = refs->next)1062if(!strcmp(submodule, refs->name))1063return refs;10641065 refs =create_ref_cache(submodule);1066 refs->next = submodule_ref_caches;1067 submodule_ref_caches = refs;1068return refs;1069}10701071/* The length of a peeled reference line in packed-refs, including EOL: */1072#define PEELED_LINE_LENGTH 4210731074/*1075 * The packed-refs header line that we write out. Perhaps other1076 * traits will be added later. The trailing space is required.1077 */1078static const char PACKED_REFS_HEADER[] =1079"# pack-refs with: peeled fully-peeled\n";10801081/*1082 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1083 * Return a pointer to the refname within the line (null-terminated),1084 * or NULL if there was a problem.1085 */1086static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1087{1088const char*ref;10891090/*1091 * 42: the answer to everything.1092 *1093 * In this case, it happens to be the answer to1094 * 40 (length of sha1 hex representation)1095 * +1 (space in between hex and name)1096 * +1 (newline at the end of the line)1097 */1098if(line->len <=42)1099return NULL;11001101if(get_sha1_hex(line->buf, sha1) <0)1102return NULL;1103if(!isspace(line->buf[40]))1104return NULL;11051106 ref = line->buf +41;1107if(isspace(*ref))1108return NULL;11091110if(line->buf[line->len -1] !='\n')1111return NULL;1112 line->buf[--line->len] =0;11131114return ref;1115}11161117/*1118 * Read f, which is a packed-refs file, into dir.1119 *1120 * A comment line of the form "# pack-refs with: " may contain zero or1121 * more traits. We interpret the traits as follows:1122 *1123 * No traits:1124 *1125 * Probably no references are peeled. But if the file contains a1126 * peeled value for a reference, we will use it.1127 *1128 * peeled:1129 *1130 * References under "refs/tags/", if they *can* be peeled, *are*1131 * peeled in this file. References outside of "refs/tags/" are1132 * probably not peeled even if they could have been, but if we find1133 * a peeled value for such a reference we will use it.1134 *1135 * fully-peeled:1136 *1137 * All references in the file that can be peeled are peeled.1138 * Inversely (and this is more important), any references in the1139 * file for which no peeled value is recorded is not peelable. This1140 * trait should typically be written alongside "peeled" for1141 * compatibility with older clients, but we do not require it1142 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1143 */1144static voidread_packed_refs(FILE*f,struct ref_dir *dir)1145{1146struct ref_entry *last = NULL;1147struct strbuf line = STRBUF_INIT;1148enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11491150while(strbuf_getwholeline(&line, f,'\n') != EOF) {1151unsigned char sha1[20];1152const char*refname;1153const char*traits;11541155if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1156if(strstr(traits," fully-peeled "))1157 peeled = PEELED_FULLY;1158else if(strstr(traits," peeled "))1159 peeled = PEELED_TAGS;1160/* perhaps other traits later as well */1161continue;1162}11631164 refname =parse_ref_line(&line, sha1);1165if(refname) {1166int flag = REF_ISPACKED;11671168if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1169hashclr(sha1);1170 flag |= REF_BAD_NAME | REF_ISBROKEN;1171}1172 last =create_ref_entry(refname, sha1, flag,0);1173if(peeled == PEELED_FULLY ||1174(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1175 last->flag |= REF_KNOWS_PEELED;1176add_ref(dir, last);1177continue;1178}1179if(last &&1180 line.buf[0] =='^'&&1181 line.len == PEELED_LINE_LENGTH &&1182 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1183!get_sha1_hex(line.buf +1, sha1)) {1184hashcpy(last->u.value.peeled, sha1);1185/*1186 * Regardless of what the file header said,1187 * we definitely know the value of *this*1188 * reference:1189 */1190 last->flag |= REF_KNOWS_PEELED;1191}1192}11931194strbuf_release(&line);1195}11961197/*1198 * Get the packed_ref_cache for the specified ref_cache, creating it1199 * if necessary.1200 */1201static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1202{1203const char*packed_refs_file;12041205if(*refs->name)1206 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1207else1208 packed_refs_file =git_path("packed-refs");12091210if(refs->packed &&1211!stat_validity_check(&refs->packed->validity, packed_refs_file))1212clear_packed_ref_cache(refs);12131214if(!refs->packed) {1215FILE*f;12161217 refs->packed =xcalloc(1,sizeof(*refs->packed));1218acquire_packed_ref_cache(refs->packed);1219 refs->packed->root =create_dir_entry(refs,"",0,0);1220 f =fopen(packed_refs_file,"r");1221if(f) {1222stat_validity_update(&refs->packed->validity,fileno(f));1223read_packed_refs(f,get_ref_dir(refs->packed->root));1224fclose(f);1225}1226}1227return refs->packed;1228}12291230static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1231{1232returnget_ref_dir(packed_ref_cache->root);1233}12341235static struct ref_dir *get_packed_refs(struct ref_cache *refs)1236{1237returnget_packed_ref_dir(get_packed_ref_cache(refs));1238}12391240voidadd_packed_ref(const char*refname,const unsigned char*sha1)1241{1242struct packed_ref_cache *packed_ref_cache =1243get_packed_ref_cache(&ref_cache);12441245if(!packed_ref_cache->lock)1246die("internal error: packed refs not locked");1247add_ref(get_packed_ref_dir(packed_ref_cache),1248create_ref_entry(refname, sha1, REF_ISPACKED,1));1249}12501251/*1252 * Read the loose references from the namespace dirname into dir1253 * (without recursing). dirname must end with '/'. dir must be the1254 * directory entry corresponding to dirname.1255 */1256static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1257{1258struct ref_cache *refs = dir->ref_cache;1259DIR*d;1260const char*path;1261struct dirent *de;1262int dirnamelen =strlen(dirname);1263struct strbuf refname;12641265if(*refs->name)1266 path =git_path_submodule(refs->name,"%s", dirname);1267else1268 path =git_path("%s", dirname);12691270 d =opendir(path);1271if(!d)1272return;12731274strbuf_init(&refname, dirnamelen +257);1275strbuf_add(&refname, dirname, dirnamelen);12761277while((de =readdir(d)) != NULL) {1278unsigned char sha1[20];1279struct stat st;1280int flag;1281const char*refdir;12821283if(de->d_name[0] =='.')1284continue;1285if(ends_with(de->d_name,".lock"))1286continue;1287strbuf_addstr(&refname, de->d_name);1288 refdir = *refs->name1289?git_path_submodule(refs->name,"%s", refname.buf)1290:git_path("%s", refname.buf);1291if(stat(refdir, &st) <0) {1292;/* silently ignore */1293}else if(S_ISDIR(st.st_mode)) {1294strbuf_addch(&refname,'/');1295add_entry_to_dir(dir,1296create_dir_entry(refs, refname.buf,1297 refname.len,1));1298}else{1299if(*refs->name) {1300hashclr(sha1);1301 flag =0;1302if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1303hashclr(sha1);1304 flag |= REF_ISBROKEN;1305}1306}else if(read_ref_full(refname.buf,1307 RESOLVE_REF_READING,1308 sha1, &flag)) {1309hashclr(sha1);1310 flag |= REF_ISBROKEN;1311}1312if(check_refname_format(refname.buf,1313 REFNAME_ALLOW_ONELEVEL)) {1314hashclr(sha1);1315 flag |= REF_BAD_NAME | REF_ISBROKEN;1316}1317add_entry_to_dir(dir,1318create_ref_entry(refname.buf, sha1, flag,0));1319}1320strbuf_setlen(&refname, dirnamelen);1321}1322strbuf_release(&refname);1323closedir(d);1324}13251326static struct ref_dir *get_loose_refs(struct ref_cache *refs)1327{1328if(!refs->loose) {1329/*1330 * Mark the top-level directory complete because we1331 * are about to read the only subdirectory that can1332 * hold references:1333 */1334 refs->loose =create_dir_entry(refs,"",0,0);1335/*1336 * Create an incomplete entry for "refs/":1337 */1338add_entry_to_dir(get_ref_dir(refs->loose),1339create_dir_entry(refs,"refs/",5,1));1340}1341returnget_ref_dir(refs->loose);1342}13431344/* We allow "recursive" symbolic refs. Only within reason, though */1345#define MAXDEPTH 51346#define MAXREFLEN (1024)13471348/*1349 * Called by resolve_gitlink_ref_recursive() after it failed to read1350 * from the loose refs in ref_cache refs. Find <refname> in the1351 * packed-refs file for the submodule.1352 */1353static intresolve_gitlink_packed_ref(struct ref_cache *refs,1354const char*refname,unsigned char*sha1)1355{1356struct ref_entry *ref;1357struct ref_dir *dir =get_packed_refs(refs);13581359 ref =find_ref(dir, refname);1360if(ref == NULL)1361return-1;13621363hashcpy(sha1, ref->u.value.sha1);1364return0;1365}13661367static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1368const char*refname,unsigned char*sha1,1369int recursion)1370{1371int fd, len;1372char buffer[128], *p;1373char*path;13741375if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1376return-1;1377 path = *refs->name1378?git_path_submodule(refs->name,"%s", refname)1379:git_path("%s", refname);1380 fd =open(path, O_RDONLY);1381if(fd <0)1382returnresolve_gitlink_packed_ref(refs, refname, sha1);13831384 len =read(fd, buffer,sizeof(buffer)-1);1385close(fd);1386if(len <0)1387return-1;1388while(len &&isspace(buffer[len-1]))1389 len--;1390 buffer[len] =0;13911392/* Was it a detached head or an old-fashioned symlink? */1393if(!get_sha1_hex(buffer, sha1))1394return0;13951396/* Symref? */1397if(strncmp(buffer,"ref:",4))1398return-1;1399 p = buffer +4;1400while(isspace(*p))1401 p++;14021403returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1404}14051406intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1407{1408int len =strlen(path), retval;1409char*submodule;1410struct ref_cache *refs;14111412while(len && path[len-1] =='/')1413 len--;1414if(!len)1415return-1;1416 submodule =xstrndup(path, len);1417 refs =get_ref_cache(submodule);1418free(submodule);14191420 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1421return retval;1422}14231424/*1425 * Return the ref_entry for the given refname from the packed1426 * references. If it does not exist, return NULL.1427 */1428static struct ref_entry *get_packed_ref(const char*refname)1429{1430returnfind_ref(get_packed_refs(&ref_cache), refname);1431}14321433/*1434 * A loose ref file doesn't exist; check for a packed ref. The1435 * options are forwarded from resolve_safe_unsafe().1436 */1437static intresolve_missing_loose_ref(const char*refname,1438int resolve_flags,1439unsigned char*sha1,1440int*flags)1441{1442struct ref_entry *entry;14431444/*1445 * The loose reference file does not exist; check for a packed1446 * reference.1447 */1448 entry =get_packed_ref(refname);1449if(entry) {1450hashcpy(sha1, entry->u.value.sha1);1451if(flags)1452*flags |= REF_ISPACKED;1453return0;1454}1455/* The reference is not a packed reference, either. */1456if(resolve_flags & RESOLVE_REF_READING) {1457 errno = ENOENT;1458return-1;1459}else{1460hashclr(sha1);1461return0;1462}1463}14641465/* This function needs to return a meaningful errno on failure */1466const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1467{1468int depth = MAXDEPTH;1469 ssize_t len;1470char buffer[256];1471static char refname_buffer[256];1472int bad_name =0;14731474if(flags)1475*flags =0;14761477if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1478if(flags)1479*flags |= REF_BAD_NAME;14801481if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1482!refname_is_safe(refname)) {1483 errno = EINVAL;1484return NULL;1485}1486/*1487 * dwim_ref() uses REF_ISBROKEN to distinguish between1488 * missing refs and refs that were present but invalid,1489 * to complain about the latter to stderr.1490 *1491 * We don't know whether the ref exists, so don't set1492 * REF_ISBROKEN yet.1493 */1494 bad_name =1;1495}1496for(;;) {1497char path[PATH_MAX];1498struct stat st;1499char*buf;1500int fd;15011502if(--depth <0) {1503 errno = ELOOP;1504return NULL;1505}15061507git_snpath(path,sizeof(path),"%s", refname);15081509/*1510 * We might have to loop back here to avoid a race1511 * condition: first we lstat() the file, then we try1512 * to read it as a link or as a file. But if somebody1513 * changes the type of the file (file <-> directory1514 * <-> symlink) between the lstat() and reading, then1515 * we don't want to report that as an error but rather1516 * try again starting with the lstat().1517 */1518 stat_ref:1519if(lstat(path, &st) <0) {1520if(errno != ENOENT)1521return NULL;1522if(resolve_missing_loose_ref(refname, resolve_flags,1523 sha1, flags))1524return NULL;1525if(bad_name) {1526hashclr(sha1);1527if(flags)1528*flags |= REF_ISBROKEN;1529}1530return refname;1531}15321533/* Follow "normalized" - ie "refs/.." symlinks by hand */1534if(S_ISLNK(st.st_mode)) {1535 len =readlink(path, buffer,sizeof(buffer)-1);1536if(len <0) {1537if(errno == ENOENT || errno == EINVAL)1538/* inconsistent with lstat; retry */1539goto stat_ref;1540else1541return NULL;1542}1543 buffer[len] =0;1544if(starts_with(buffer,"refs/") &&1545!check_refname_format(buffer,0)) {1546strcpy(refname_buffer, buffer);1547 refname = refname_buffer;1548if(flags)1549*flags |= REF_ISSYMREF;1550if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1551hashclr(sha1);1552return refname;1553}1554continue;1555}1556}15571558/* Is it a directory? */1559if(S_ISDIR(st.st_mode)) {1560 errno = EISDIR;1561return NULL;1562}15631564/*1565 * Anything else, just open it and try to use it as1566 * a ref1567 */1568 fd =open(path, O_RDONLY);1569if(fd <0) {1570if(errno == ENOENT)1571/* inconsistent with lstat; retry */1572goto stat_ref;1573else1574return NULL;1575}1576 len =read_in_full(fd, buffer,sizeof(buffer)-1);1577if(len <0) {1578int save_errno = errno;1579close(fd);1580 errno = save_errno;1581return NULL;1582}1583close(fd);1584while(len &&isspace(buffer[len-1]))1585 len--;1586 buffer[len] ='\0';15871588/*1589 * Is it a symbolic ref?1590 */1591if(!starts_with(buffer,"ref:")) {1592/*1593 * Please note that FETCH_HEAD has a second1594 * line containing other data.1595 */1596if(get_sha1_hex(buffer, sha1) ||1597(buffer[40] !='\0'&& !isspace(buffer[40]))) {1598if(flags)1599*flags |= REF_ISBROKEN;1600 errno = EINVAL;1601return NULL;1602}1603if(bad_name) {1604hashclr(sha1);1605if(flags)1606*flags |= REF_ISBROKEN;1607}1608return refname;1609}1610if(flags)1611*flags |= REF_ISSYMREF;1612 buf = buffer +4;1613while(isspace(*buf))1614 buf++;1615 refname =strcpy(refname_buffer, buf);1616if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1617hashclr(sha1);1618return refname;1619}1620if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1621if(flags)1622*flags |= REF_ISBROKEN;16231624if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1625!refname_is_safe(buf)) {1626 errno = EINVAL;1627return NULL;1628}1629 bad_name =1;1630}1631}1632}16331634char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1635{1636returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1637}16381639/* The argument to filter_refs */1640struct ref_filter {1641const char*pattern;1642 each_ref_fn *fn;1643void*cb_data;1644};16451646intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1647{1648if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1649return0;1650return-1;1651}16521653intread_ref(const char*refname,unsigned char*sha1)1654{1655returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1656}16571658intref_exists(const char*refname)1659{1660unsigned char sha1[20];1661return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1662}16631664static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1665void*data)1666{1667struct ref_filter *filter = (struct ref_filter *)data;1668if(wildmatch(filter->pattern, refname,0, NULL))1669return0;1670return filter->fn(refname, sha1, flags, filter->cb_data);1671}16721673enum peel_status {1674/* object was peeled successfully: */1675 PEEL_PEELED =0,16761677/*1678 * object cannot be peeled because the named object (or an1679 * object referred to by a tag in the peel chain), does not1680 * exist.1681 */1682 PEEL_INVALID = -1,16831684/* object cannot be peeled because it is not a tag: */1685 PEEL_NON_TAG = -2,16861687/* ref_entry contains no peeled value because it is a symref: */1688 PEEL_IS_SYMREF = -3,16891690/*1691 * ref_entry cannot be peeled because it is broken (i.e., the1692 * symbolic reference cannot even be resolved to an object1693 * name):1694 */1695 PEEL_BROKEN = -41696};16971698/*1699 * Peel the named object; i.e., if the object is a tag, resolve the1700 * tag recursively until a non-tag is found. If successful, store the1701 * result to sha1 and return PEEL_PEELED. If the object is not a tag1702 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1703 * and leave sha1 unchanged.1704 */1705static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1706{1707struct object *o =lookup_unknown_object(name);17081709if(o->type == OBJ_NONE) {1710int type =sha1_object_info(name, NULL);1711if(type <0|| !object_as_type(o, type,0))1712return PEEL_INVALID;1713}17141715if(o->type != OBJ_TAG)1716return PEEL_NON_TAG;17171718 o =deref_tag_noverify(o);1719if(!o)1720return PEEL_INVALID;17211722hashcpy(sha1, o->sha1);1723return PEEL_PEELED;1724}17251726/*1727 * Peel the entry (if possible) and return its new peel_status. If1728 * repeel is true, re-peel the entry even if there is an old peeled1729 * value that is already stored in it.1730 *1731 * It is OK to call this function with a packed reference entry that1732 * might be stale and might even refer to an object that has since1733 * been garbage-collected. In such a case, if the entry has1734 * REF_KNOWS_PEELED then leave the status unchanged and return1735 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1736 */1737static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1738{1739enum peel_status status;17401741if(entry->flag & REF_KNOWS_PEELED) {1742if(repeel) {1743 entry->flag &= ~REF_KNOWS_PEELED;1744hashclr(entry->u.value.peeled);1745}else{1746returnis_null_sha1(entry->u.value.peeled) ?1747 PEEL_NON_TAG : PEEL_PEELED;1748}1749}1750if(entry->flag & REF_ISBROKEN)1751return PEEL_BROKEN;1752if(entry->flag & REF_ISSYMREF)1753return PEEL_IS_SYMREF;17541755 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1756if(status == PEEL_PEELED || status == PEEL_NON_TAG)1757 entry->flag |= REF_KNOWS_PEELED;1758return status;1759}17601761intpeel_ref(const char*refname,unsigned char*sha1)1762{1763int flag;1764unsigned char base[20];17651766if(current_ref && (current_ref->name == refname1767|| !strcmp(current_ref->name, refname))) {1768if(peel_entry(current_ref,0))1769return-1;1770hashcpy(sha1, current_ref->u.value.peeled);1771return0;1772}17731774if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1775return-1;17761777/*1778 * If the reference is packed, read its ref_entry from the1779 * cache in the hope that we already know its peeled value.1780 * We only try this optimization on packed references because1781 * (a) forcing the filling of the loose reference cache could1782 * be expensive and (b) loose references anyway usually do not1783 * have REF_KNOWS_PEELED.1784 */1785if(flag & REF_ISPACKED) {1786struct ref_entry *r =get_packed_ref(refname);1787if(r) {1788if(peel_entry(r,0))1789return-1;1790hashcpy(sha1, r->u.value.peeled);1791return0;1792}1793}17941795returnpeel_object(base, sha1);1796}17971798struct warn_if_dangling_data {1799FILE*fp;1800const char*refname;1801const struct string_list *refnames;1802const char*msg_fmt;1803};18041805static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1806int flags,void*cb_data)1807{1808struct warn_if_dangling_data *d = cb_data;1809const char*resolves_to;1810unsigned char junk[20];18111812if(!(flags & REF_ISSYMREF))1813return0;18141815 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1816if(!resolves_to1817|| (d->refname1818?strcmp(resolves_to, d->refname)1819: !string_list_has_string(d->refnames, resolves_to))) {1820return0;1821}18221823fprintf(d->fp, d->msg_fmt, refname);1824fputc('\n', d->fp);1825return0;1826}18271828voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1829{1830struct warn_if_dangling_data data;18311832 data.fp = fp;1833 data.refname = refname;1834 data.refnames = NULL;1835 data.msg_fmt = msg_fmt;1836for_each_rawref(warn_if_dangling_symref, &data);1837}18381839voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1840{1841struct warn_if_dangling_data data;18421843 data.fp = fp;1844 data.refname = NULL;1845 data.refnames = refnames;1846 data.msg_fmt = msg_fmt;1847for_each_rawref(warn_if_dangling_symref, &data);1848}18491850/*1851 * Call fn for each reference in the specified ref_cache, omitting1852 * references not in the containing_dir of base. fn is called for all1853 * references, including broken ones. If fn ever returns a non-zero1854 * value, stop the iteration and return that value; otherwise, return1855 * 0.1856 */1857static intdo_for_each_entry(struct ref_cache *refs,const char*base,1858 each_ref_entry_fn fn,void*cb_data)1859{1860struct packed_ref_cache *packed_ref_cache;1861struct ref_dir *loose_dir;1862struct ref_dir *packed_dir;1863int retval =0;18641865/*1866 * We must make sure that all loose refs are read before accessing the1867 * packed-refs file; this avoids a race condition in which loose refs1868 * are migrated to the packed-refs file by a simultaneous process, but1869 * our in-memory view is from before the migration. get_packed_ref_cache()1870 * takes care of making sure our view is up to date with what is on1871 * disk.1872 */1873 loose_dir =get_loose_refs(refs);1874if(base && *base) {1875 loose_dir =find_containing_dir(loose_dir, base,0);1876}1877if(loose_dir)1878prime_ref_dir(loose_dir);18791880 packed_ref_cache =get_packed_ref_cache(refs);1881acquire_packed_ref_cache(packed_ref_cache);1882 packed_dir =get_packed_ref_dir(packed_ref_cache);1883if(base && *base) {1884 packed_dir =find_containing_dir(packed_dir, base,0);1885}18861887if(packed_dir && loose_dir) {1888sort_ref_dir(packed_dir);1889sort_ref_dir(loose_dir);1890 retval =do_for_each_entry_in_dirs(1891 packed_dir, loose_dir, fn, cb_data);1892}else if(packed_dir) {1893sort_ref_dir(packed_dir);1894 retval =do_for_each_entry_in_dir(1895 packed_dir,0, fn, cb_data);1896}else if(loose_dir) {1897sort_ref_dir(loose_dir);1898 retval =do_for_each_entry_in_dir(1899 loose_dir,0, fn, cb_data);1900}19011902release_packed_ref_cache(packed_ref_cache);1903return retval;1904}19051906/*1907 * Call fn for each reference in the specified ref_cache for which the1908 * refname begins with base. If trim is non-zero, then trim that many1909 * characters off the beginning of each refname before passing the1910 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1911 * broken references in the iteration. If fn ever returns a non-zero1912 * value, stop the iteration and return that value; otherwise, return1913 * 0.1914 */1915static intdo_for_each_ref(struct ref_cache *refs,const char*base,1916 each_ref_fn fn,int trim,int flags,void*cb_data)1917{1918struct ref_entry_cb data;1919 data.base = base;1920 data.trim = trim;1921 data.flags = flags;1922 data.fn = fn;1923 data.cb_data = cb_data;19241925returndo_for_each_entry(refs, base, do_one_ref, &data);1926}19271928static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1929{1930unsigned char sha1[20];1931int flag;19321933if(submodule) {1934if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1935returnfn("HEAD", sha1,0, cb_data);19361937return0;1938}19391940if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1941returnfn("HEAD", sha1, flag, cb_data);19421943return0;1944}19451946inthead_ref(each_ref_fn fn,void*cb_data)1947{1948returndo_head_ref(NULL, fn, cb_data);1949}19501951inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1952{1953returndo_head_ref(submodule, fn, cb_data);1954}19551956intfor_each_ref(each_ref_fn fn,void*cb_data)1957{1958returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1959}19601961intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1962{1963returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1964}19651966intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1967{1968returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1969}19701971intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1972 each_ref_fn fn,void*cb_data)1973{1974returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1975}19761977intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1978{1979returnfor_each_ref_in("refs/tags/", fn, cb_data);1980}19811982intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1983{1984returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1985}19861987intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1988{1989returnfor_each_ref_in("refs/heads/", fn, cb_data);1990}19911992intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1993{1994returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1995}19961997intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1998{1999returnfor_each_ref_in("refs/remotes/", fn, cb_data);2000}20012002intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2003{2004returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2005}20062007intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2008{2009returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2010}20112012inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2013{2014struct strbuf buf = STRBUF_INIT;2015int ret =0;2016unsigned char sha1[20];2017int flag;20182019strbuf_addf(&buf,"%sHEAD",get_git_namespace());2020if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2021 ret =fn(buf.buf, sha1, flag, cb_data);2022strbuf_release(&buf);20232024return ret;2025}20262027intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2028{2029struct strbuf buf = STRBUF_INIT;2030int ret;2031strbuf_addf(&buf,"%srefs/",get_git_namespace());2032 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2033strbuf_release(&buf);2034return ret;2035}20362037intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2038const char*prefix,void*cb_data)2039{2040struct strbuf real_pattern = STRBUF_INIT;2041struct ref_filter filter;2042int ret;20432044if(!prefix && !starts_with(pattern,"refs/"))2045strbuf_addstr(&real_pattern,"refs/");2046else if(prefix)2047strbuf_addstr(&real_pattern, prefix);2048strbuf_addstr(&real_pattern, pattern);20492050if(!has_glob_specials(pattern)) {2051/* Append implied '/' '*' if not present. */2052if(real_pattern.buf[real_pattern.len -1] !='/')2053strbuf_addch(&real_pattern,'/');2054/* No need to check for '*', there is none. */2055strbuf_addch(&real_pattern,'*');2056}20572058 filter.pattern = real_pattern.buf;2059 filter.fn = fn;2060 filter.cb_data = cb_data;2061 ret =for_each_ref(filter_refs, &filter);20622063strbuf_release(&real_pattern);2064return ret;2065}20662067intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2068{2069returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2070}20712072intfor_each_rawref(each_ref_fn fn,void*cb_data)2073{2074returndo_for_each_ref(&ref_cache,"", fn,0,2075 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2076}20772078const char*prettify_refname(const char*name)2079{2080return name + (2081starts_with(name,"refs/heads/") ?11:2082starts_with(name,"refs/tags/") ?10:2083starts_with(name,"refs/remotes/") ?13:20840);2085}20862087static const char*ref_rev_parse_rules[] = {2088"%.*s",2089"refs/%.*s",2090"refs/tags/%.*s",2091"refs/heads/%.*s",2092"refs/remotes/%.*s",2093"refs/remotes/%.*s/HEAD",2094 NULL2095};20962097intrefname_match(const char*abbrev_name,const char*full_name)2098{2099const char**p;2100const int abbrev_name_len =strlen(abbrev_name);21012102for(p = ref_rev_parse_rules; *p; p++) {2103if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2104return1;2105}2106}21072108return0;2109}21102111static voidunlock_ref(struct ref_lock *lock)2112{2113/* Do not free lock->lk -- atexit() still looks at them */2114if(lock->lk)2115rollback_lock_file(lock->lk);2116free(lock->ref_name);2117free(lock->orig_ref_name);2118free(lock);2119}21202121/* This function should make sure errno is meaningful on error */2122static struct ref_lock *verify_lock(struct ref_lock *lock,2123const unsigned char*old_sha1,int mustexist)2124{2125if(read_ref_full(lock->ref_name,2126 mustexist ? RESOLVE_REF_READING :0,2127 lock->old_sha1, NULL)) {2128int save_errno = errno;2129error("Can't verify ref%s", lock->ref_name);2130unlock_ref(lock);2131 errno = save_errno;2132return NULL;2133}2134if(hashcmp(lock->old_sha1, old_sha1)) {2135error("Ref%sis at%sbut expected%s", lock->ref_name,2136sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2137unlock_ref(lock);2138 errno = EBUSY;2139return NULL;2140}2141return lock;2142}21432144static intremove_empty_directories(const char*file)2145{2146/* we want to create a file but there is a directory there;2147 * if that is an empty directory (or a directory that contains2148 * only empty directories), remove them.2149 */2150struct strbuf path;2151int result, save_errno;21522153strbuf_init(&path,20);2154strbuf_addstr(&path, file);21552156 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2157 save_errno = errno;21582159strbuf_release(&path);2160 errno = save_errno;21612162return result;2163}21642165/*2166 * *string and *len will only be substituted, and *string returned (for2167 * later free()ing) if the string passed in is a magic short-hand form2168 * to name a branch.2169 */2170static char*substitute_branch_name(const char**string,int*len)2171{2172struct strbuf buf = STRBUF_INIT;2173int ret =interpret_branch_name(*string, *len, &buf);21742175if(ret == *len) {2176size_t size;2177*string =strbuf_detach(&buf, &size);2178*len = size;2179return(char*)*string;2180}21812182return NULL;2183}21842185intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2186{2187char*last_branch =substitute_branch_name(&str, &len);2188const char**p, *r;2189int refs_found =0;21902191*ref = NULL;2192for(p = ref_rev_parse_rules; *p; p++) {2193char fullref[PATH_MAX];2194unsigned char sha1_from_ref[20];2195unsigned char*this_result;2196int flag;21972198 this_result = refs_found ? sha1_from_ref : sha1;2199mksnpath(fullref,sizeof(fullref), *p, len, str);2200 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2201 this_result, &flag);2202if(r) {2203if(!refs_found++)2204*ref =xstrdup(r);2205if(!warn_ambiguous_refs)2206break;2207}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2208warning("ignoring dangling symref%s.", fullref);2209}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2210warning("ignoring broken ref%s.", fullref);2211}2212}2213free(last_branch);2214return refs_found;2215}22162217intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2218{2219char*last_branch =substitute_branch_name(&str, &len);2220const char**p;2221int logs_found =0;22222223*log = NULL;2224for(p = ref_rev_parse_rules; *p; p++) {2225unsigned char hash[20];2226char path[PATH_MAX];2227const char*ref, *it;22282229mksnpath(path,sizeof(path), *p, len, str);2230 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2231 hash, NULL);2232if(!ref)2233continue;2234if(reflog_exists(path))2235 it = path;2236else if(strcmp(ref, path) &&reflog_exists(ref))2237 it = ref;2238else2239continue;2240if(!logs_found++) {2241*log =xstrdup(it);2242hashcpy(sha1, hash);2243}2244if(!warn_ambiguous_refs)2245break;2246}2247free(last_branch);2248return logs_found;2249}22502251/*2252 * Locks a ref returning the lock on success and NULL on failure.2253 * On failure errno is set to something meaningful.2254 */2255static struct ref_lock *lock_ref_sha1_basic(const char*refname,2256const unsigned char*old_sha1,2257const struct string_list *skip,2258int flags,int*type_p)2259{2260char*ref_file;2261const char*orig_refname = refname;2262struct ref_lock *lock;2263int last_errno =0;2264int type, lflags;2265int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2266int resolve_flags =0;2267int missing =0;2268int attempts_remaining =3;22692270 lock =xcalloc(1,sizeof(struct ref_lock));2271 lock->lock_fd = -1;22722273if(mustexist)2274 resolve_flags |= RESOLVE_REF_READING;2275if(flags & REF_DELETING) {2276 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2277if(flags & REF_NODEREF)2278 resolve_flags |= RESOLVE_REF_NO_RECURSE;2279}22802281 refname =resolve_ref_unsafe(refname, resolve_flags,2282 lock->old_sha1, &type);2283if(!refname && errno == EISDIR) {2284/* we are trying to lock foo but we used to2285 * have foo/bar which now does not exist;2286 * it is normal for the empty directory 'foo'2287 * to remain.2288 */2289 ref_file =git_path("%s", orig_refname);2290if(remove_empty_directories(ref_file)) {2291 last_errno = errno;2292error("there are still refs under '%s'", orig_refname);2293goto error_return;2294}2295 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2296 lock->old_sha1, &type);2297}2298if(type_p)2299*type_p = type;2300if(!refname) {2301 last_errno = errno;2302error("unable to resolve reference%s:%s",2303 orig_refname,strerror(errno));2304goto error_return;2305}2306 missing =is_null_sha1(lock->old_sha1);2307/* When the ref did not exist and we are creating it,2308 * make sure there is no existing ref that is packed2309 * whose name begins with our refname, nor a ref whose2310 * name is a proper prefix of our refname.2311 */2312if(missing &&2313!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2314 last_errno = ENOTDIR;2315goto error_return;2316}23172318 lock->lk =xcalloc(1,sizeof(struct lock_file));23192320 lflags =0;2321if(flags & REF_NODEREF) {2322 refname = orig_refname;2323 lflags |= LOCK_NO_DEREF;2324}2325 lock->ref_name =xstrdup(refname);2326 lock->orig_ref_name =xstrdup(orig_refname);2327 ref_file =git_path("%s", refname);2328if(missing)2329 lock->force_write =1;2330if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2331 lock->force_write =1;23322333 retry:2334switch(safe_create_leading_directories(ref_file)) {2335case SCLD_OK:2336break;/* success */2337case SCLD_VANISHED:2338if(--attempts_remaining >0)2339goto retry;2340/* fall through */2341default:2342 last_errno = errno;2343error("unable to create directory for%s", ref_file);2344goto error_return;2345}23462347 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2348if(lock->lock_fd <0) {2349 last_errno = errno;2350if(errno == ENOENT && --attempts_remaining >0)2351/*2352 * Maybe somebody just deleted one of the2353 * directories leading to ref_file. Try2354 * again:2355 */2356goto retry;2357else{2358struct strbuf err = STRBUF_INIT;2359unable_to_lock_message(ref_file, errno, &err);2360error("%s", err.buf);2361strbuf_release(&err);2362goto error_return;2363}2364}2365return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23662367 error_return:2368unlock_ref(lock);2369 errno = last_errno;2370return NULL;2371}23722373/*2374 * Write an entry to the packed-refs file for the specified refname.2375 * If peeled is non-NULL, write it as the entry's peeled value.2376 */2377static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2378unsigned char*peeled)2379{2380fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2381if(peeled)2382fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2383}23842385/*2386 * An each_ref_entry_fn that writes the entry to a packed-refs file.2387 */2388static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2389{2390enum peel_status peel_status =peel_entry(entry,0);23912392if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2393error("internal error:%sis not a valid packed reference!",2394 entry->name);2395write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2396 peel_status == PEEL_PEELED ?2397 entry->u.value.peeled : NULL);2398return0;2399}24002401/* This should return a meaningful errno on failure */2402intlock_packed_refs(int flags)2403{2404struct packed_ref_cache *packed_ref_cache;24052406if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2407return-1;2408/*2409 * Get the current packed-refs while holding the lock. If the2410 * packed-refs file has been modified since we last read it,2411 * this will automatically invalidate the cache and re-read2412 * the packed-refs file.2413 */2414 packed_ref_cache =get_packed_ref_cache(&ref_cache);2415 packed_ref_cache->lock = &packlock;2416/* Increment the reference count to prevent it from being freed: */2417acquire_packed_ref_cache(packed_ref_cache);2418return0;2419}24202421/*2422 * Commit the packed refs changes.2423 * On error we must make sure that errno contains a meaningful value.2424 */2425intcommit_packed_refs(void)2426{2427struct packed_ref_cache *packed_ref_cache =2428get_packed_ref_cache(&ref_cache);2429int error =0;2430int save_errno =0;2431FILE*out;24322433if(!packed_ref_cache->lock)2434die("internal error: packed-refs not locked");24352436 out =fdopen_lock_file(packed_ref_cache->lock,"w");2437if(!out)2438die_errno("unable to fdopen packed-refs descriptor");24392440fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2441do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24420, write_packed_entry_fn, out);24432444if(commit_lock_file(packed_ref_cache->lock)) {2445 save_errno = errno;2446 error = -1;2447}2448 packed_ref_cache->lock = NULL;2449release_packed_ref_cache(packed_ref_cache);2450 errno = save_errno;2451return error;2452}24532454voidrollback_packed_refs(void)2455{2456struct packed_ref_cache *packed_ref_cache =2457get_packed_ref_cache(&ref_cache);24582459if(!packed_ref_cache->lock)2460die("internal error: packed-refs not locked");2461rollback_lock_file(packed_ref_cache->lock);2462 packed_ref_cache->lock = NULL;2463release_packed_ref_cache(packed_ref_cache);2464clear_packed_ref_cache(&ref_cache);2465}24662467struct ref_to_prune {2468struct ref_to_prune *next;2469unsigned char sha1[20];2470char name[FLEX_ARRAY];2471};24722473struct pack_refs_cb_data {2474unsigned int flags;2475struct ref_dir *packed_refs;2476struct ref_to_prune *ref_to_prune;2477};24782479/*2480 * An each_ref_entry_fn that is run over loose references only. If2481 * the loose reference can be packed, add an entry in the packed ref2482 * cache. If the reference should be pruned, also add it to2483 * ref_to_prune in the pack_refs_cb_data.2484 */2485static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2486{2487struct pack_refs_cb_data *cb = cb_data;2488enum peel_status peel_status;2489struct ref_entry *packed_entry;2490int is_tag_ref =starts_with(entry->name,"refs/tags/");24912492/* ALWAYS pack tags */2493if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2494return0;24952496/* Do not pack symbolic or broken refs: */2497if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2498return0;24992500/* Add a packed ref cache entry equivalent to the loose entry. */2501 peel_status =peel_entry(entry,1);2502if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2503die("internal error peeling reference%s(%s)",2504 entry->name,sha1_to_hex(entry->u.value.sha1));2505 packed_entry =find_ref(cb->packed_refs, entry->name);2506if(packed_entry) {2507/* Overwrite existing packed entry with info from loose entry */2508 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2509hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2510}else{2511 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2512 REF_ISPACKED | REF_KNOWS_PEELED,0);2513add_ref(cb->packed_refs, packed_entry);2514}2515hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25162517/* Schedule the loose reference for pruning if requested. */2518if((cb->flags & PACK_REFS_PRUNE)) {2519int namelen =strlen(entry->name) +1;2520struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2521hashcpy(n->sha1, entry->u.value.sha1);2522strcpy(n->name, entry->name);2523 n->next = cb->ref_to_prune;2524 cb->ref_to_prune = n;2525}2526return0;2527}25282529/*2530 * Remove empty parents, but spare refs/ and immediate subdirs.2531 * Note: munges *name.2532 */2533static voidtry_remove_empty_parents(char*name)2534{2535char*p, *q;2536int i;2537 p = name;2538for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2539while(*p && *p !='/')2540 p++;2541/* tolerate duplicate slashes; see check_refname_format() */2542while(*p =='/')2543 p++;2544}2545for(q = p; *q; q++)2546;2547while(1) {2548while(q > p && *q !='/')2549 q--;2550while(q > p && *(q-1) =='/')2551 q--;2552if(q == p)2553break;2554*q ='\0';2555if(rmdir(git_path("%s", name)))2556break;2557}2558}25592560/* make sure nobody touched the ref, and unlink */2561static voidprune_ref(struct ref_to_prune *r)2562{2563struct ref_transaction *transaction;2564struct strbuf err = STRBUF_INIT;25652566if(check_refname_format(r->name,0))2567return;25682569 transaction =ref_transaction_begin(&err);2570if(!transaction ||2571ref_transaction_delete(transaction, r->name, r->sha1,2572 REF_ISPRUNING,1, NULL, &err) ||2573ref_transaction_commit(transaction, &err)) {2574ref_transaction_free(transaction);2575error("%s", err.buf);2576strbuf_release(&err);2577return;2578}2579ref_transaction_free(transaction);2580strbuf_release(&err);2581try_remove_empty_parents(r->name);2582}25832584static voidprune_refs(struct ref_to_prune *r)2585{2586while(r) {2587prune_ref(r);2588 r = r->next;2589}2590}25912592intpack_refs(unsigned int flags)2593{2594struct pack_refs_cb_data cbdata;25952596memset(&cbdata,0,sizeof(cbdata));2597 cbdata.flags = flags;25982599lock_packed_refs(LOCK_DIE_ON_ERROR);2600 cbdata.packed_refs =get_packed_refs(&ref_cache);26012602do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2603 pack_if_possible_fn, &cbdata);26042605if(commit_packed_refs())2606die_errno("unable to overwrite old ref-pack file");26072608prune_refs(cbdata.ref_to_prune);2609return0;2610}26112612/*2613 * If entry is no longer needed in packed-refs, add it to the string2614 * list pointed to by cb_data. Reasons for deleting entries:2615 *2616 * - Entry is broken.2617 * - Entry is overridden by a loose ref.2618 * - Entry does not point at a valid object.2619 *2620 * In the first and third cases, also emit an error message because these2621 * are indications of repository corruption.2622 */2623static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2624{2625struct string_list *refs_to_delete = cb_data;26262627if(entry->flag & REF_ISBROKEN) {2628/* This shouldn't happen to packed refs. */2629error("%sis broken!", entry->name);2630string_list_append(refs_to_delete, entry->name);2631return0;2632}2633if(!has_sha1_file(entry->u.value.sha1)) {2634unsigned char sha1[20];2635int flags;26362637if(read_ref_full(entry->name,0, sha1, &flags))2638/* We should at least have found the packed ref. */2639die("Internal error");2640if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2641/*2642 * This packed reference is overridden by a2643 * loose reference, so it is OK that its value2644 * is no longer valid; for example, it might2645 * refer to an object that has been garbage2646 * collected. For this purpose we don't even2647 * care whether the loose reference itself is2648 * invalid, broken, symbolic, etc. Silently2649 * remove the packed reference.2650 */2651string_list_append(refs_to_delete, entry->name);2652return0;2653}2654/*2655 * There is no overriding loose reference, so the fact2656 * that this reference doesn't refer to a valid object2657 * indicates some kind of repository corruption.2658 * Report the problem, then omit the reference from2659 * the output.2660 */2661error("%sdoes not point to a valid object!", entry->name);2662string_list_append(refs_to_delete, entry->name);2663return0;2664}26652666return0;2667}26682669intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2670{2671struct ref_dir *packed;2672struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2673struct string_list_item *refname, *ref_to_delete;2674int ret, needs_repacking =0, removed =0;26752676assert(err);26772678/* Look for a packed ref */2679for_each_string_list_item(refname, refnames) {2680if(get_packed_ref(refname->string)) {2681 needs_repacking =1;2682break;2683}2684}26852686/* Avoid locking if we have nothing to do */2687if(!needs_repacking)2688return0;/* no refname exists in packed refs */26892690if(lock_packed_refs(0)) {2691unable_to_lock_message(git_path("packed-refs"), errno, err);2692return-1;2693}2694 packed =get_packed_refs(&ref_cache);26952696/* Remove refnames from the cache */2697for_each_string_list_item(refname, refnames)2698if(remove_entry(packed, refname->string) != -1)2699 removed =1;2700if(!removed) {2701/*2702 * All packed entries disappeared while we were2703 * acquiring the lock.2704 */2705rollback_packed_refs();2706return0;2707}27082709/* Remove any other accumulated cruft */2710do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2711for_each_string_list_item(ref_to_delete, &refs_to_delete) {2712if(remove_entry(packed, ref_to_delete->string) == -1)2713die("internal error");2714}27152716/* Write what remains */2717 ret =commit_packed_refs();2718if(ret)2719strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2720strerror(errno));2721return ret;2722}27232724static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2725{2726assert(err);27272728if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2729/*2730 * loose. The loose file name is the same as the2731 * lockfile name, minus ".lock":2732 */2733char*loose_filename =get_locked_file_path(lock->lk);2734int res =unlink_or_msg(loose_filename, err);2735free(loose_filename);2736if(res)2737return1;2738}2739return0;2740}27412742intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2743{2744struct ref_transaction *transaction;2745struct strbuf err = STRBUF_INIT;27462747 transaction =ref_transaction_begin(&err);2748if(!transaction ||2749ref_transaction_delete(transaction, refname, sha1, delopt,2750 sha1 && !is_null_sha1(sha1), NULL, &err) ||2751ref_transaction_commit(transaction, &err)) {2752error("%s", err.buf);2753ref_transaction_free(transaction);2754strbuf_release(&err);2755return1;2756}2757ref_transaction_free(transaction);2758strbuf_release(&err);2759return0;2760}27612762/*2763 * People using contrib's git-new-workdir have .git/logs/refs ->2764 * /some/other/path/.git/logs/refs, and that may live on another device.2765 *2766 * IOW, to avoid cross device rename errors, the temporary renamed log must2767 * live into logs/refs.2768 */2769#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27702771static intrename_tmp_log(const char*newrefname)2772{2773int attempts_remaining =4;27742775 retry:2776switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2777case SCLD_OK:2778break;/* success */2779case SCLD_VANISHED:2780if(--attempts_remaining >0)2781goto retry;2782/* fall through */2783default:2784error("unable to create directory for%s", newrefname);2785return-1;2786}27872788if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2789if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2790/*2791 * rename(a, b) when b is an existing2792 * directory ought to result in ISDIR, but2793 * Solaris 5.8 gives ENOTDIR. Sheesh.2794 */2795if(remove_empty_directories(git_path("logs/%s", newrefname))) {2796error("Directory not empty: logs/%s", newrefname);2797return-1;2798}2799goto retry;2800}else if(errno == ENOENT && --attempts_remaining >0) {2801/*2802 * Maybe another process just deleted one of2803 * the directories in the path to newrefname.2804 * Try again from the beginning.2805 */2806goto retry;2807}else{2808error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2809 newrefname,strerror(errno));2810return-1;2811}2812}2813return0;2814}28152816static intrename_ref_available(const char*oldname,const char*newname)2817{2818struct string_list skip = STRING_LIST_INIT_NODUP;2819int ret;28202821string_list_insert(&skip, oldname);2822 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2823&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2824string_list_clear(&skip,0);2825return ret;2826}28272828static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2829const char*logmsg);28302831intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2832{2833unsigned char sha1[20], orig_sha1[20];2834int flag =0, logmoved =0;2835struct ref_lock *lock;2836struct stat loginfo;2837int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2838const char*symref = NULL;28392840if(log &&S_ISLNK(loginfo.st_mode))2841returnerror("reflog for%sis a symlink", oldrefname);28422843 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2844 orig_sha1, &flag);2845if(flag & REF_ISSYMREF)2846returnerror("refname%sis a symbolic ref, renaming it is not supported",2847 oldrefname);2848if(!symref)2849returnerror("refname%snot found", oldrefname);28502851if(!rename_ref_available(oldrefname, newrefname))2852return1;28532854if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2855returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2856 oldrefname,strerror(errno));28572858if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2859error("unable to delete old%s", oldrefname);2860goto rollback;2861}28622863if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2864delete_ref(newrefname, sha1, REF_NODEREF)) {2865if(errno==EISDIR) {2866if(remove_empty_directories(git_path("%s", newrefname))) {2867error("Directory not empty:%s", newrefname);2868goto rollback;2869}2870}else{2871error("unable to delete existing%s", newrefname);2872goto rollback;2873}2874}28752876if(log &&rename_tmp_log(newrefname))2877goto rollback;28782879 logmoved = log;28802881 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2882if(!lock) {2883error("unable to lock%sfor update", newrefname);2884goto rollback;2885}2886 lock->force_write =1;2887hashcpy(lock->old_sha1, orig_sha1);2888if(write_ref_sha1(lock, orig_sha1, logmsg)) {2889error("unable to write current sha1 into%s", newrefname);2890goto rollback;2891}28922893return0;28942895 rollback:2896 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2897if(!lock) {2898error("unable to lock%sfor rollback", oldrefname);2899goto rollbacklog;2900}29012902 lock->force_write =1;2903 flag = log_all_ref_updates;2904 log_all_ref_updates =0;2905if(write_ref_sha1(lock, orig_sha1, NULL))2906error("unable to write current sha1 into%s", oldrefname);2907 log_all_ref_updates = flag;29082909 rollbacklog:2910if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2911error("unable to restore logfile%sfrom%s:%s",2912 oldrefname, newrefname,strerror(errno));2913if(!logmoved && log &&2914rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2915error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2916 oldrefname,strerror(errno));29172918return1;2919}29202921static intclose_ref(struct ref_lock *lock)2922{2923if(close_lock_file(lock->lk))2924return-1;2925 lock->lock_fd = -1;2926return0;2927}29282929static intcommit_ref(struct ref_lock *lock)2930{2931if(commit_lock_file(lock->lk))2932return-1;2933 lock->lock_fd = -1;2934return0;2935}29362937/*2938 * copy the reflog message msg to buf, which has been allocated sufficiently2939 * large, while cleaning up the whitespaces. Especially, convert LF to space,2940 * because reflog file is one line per entry.2941 */2942static intcopy_msg(char*buf,const char*msg)2943{2944char*cp = buf;2945char c;2946int wasspace =1;29472948*cp++ ='\t';2949while((c = *msg++)) {2950if(wasspace &&isspace(c))2951continue;2952 wasspace =isspace(c);2953if(wasspace)2954 c =' ';2955*cp++ = c;2956}2957while(buf < cp &&isspace(cp[-1]))2958 cp--;2959*cp++ ='\n';2960return cp - buf;2961}29622963/* This function must set a meaningful errno on failure */2964intlog_ref_setup(const char*refname,char*logfile,int bufsize)2965{2966int logfd, oflags = O_APPEND | O_WRONLY;29672968git_snpath(logfile, bufsize,"logs/%s", refname);2969if(log_all_ref_updates &&2970(starts_with(refname,"refs/heads/") ||2971starts_with(refname,"refs/remotes/") ||2972starts_with(refname,"refs/notes/") ||2973!strcmp(refname,"HEAD"))) {2974if(safe_create_leading_directories(logfile) <0) {2975int save_errno = errno;2976error("unable to create directory for%s", logfile);2977 errno = save_errno;2978return-1;2979}2980 oflags |= O_CREAT;2981}29822983 logfd =open(logfile, oflags,0666);2984if(logfd <0) {2985if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2986return0;29872988if(errno == EISDIR) {2989if(remove_empty_directories(logfile)) {2990int save_errno = errno;2991error("There are still logs under '%s'",2992 logfile);2993 errno = save_errno;2994return-1;2995}2996 logfd =open(logfile, oflags,0666);2997}29982999if(logfd <0) {3000int save_errno = errno;3001error("Unable to append to%s:%s", logfile,3002strerror(errno));3003 errno = save_errno;3004return-1;3005}3006}30073008adjust_shared_perm(logfile);3009close(logfd);3010return0;3011}30123013static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3014const unsigned char*new_sha1,3015const char*committer,const char*msg)3016{3017int msglen, written;3018unsigned maxlen, len;3019char*logrec;30203021 msglen = msg ?strlen(msg) :0;3022 maxlen =strlen(committer) + msglen +100;3023 logrec =xmalloc(maxlen);3024 len =sprintf(logrec,"%s %s %s\n",3025sha1_to_hex(old_sha1),3026sha1_to_hex(new_sha1),3027 committer);3028if(msglen)3029 len +=copy_msg(logrec + len -1, msg) -1;30303031 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3032free(logrec);3033if(written != len)3034return-1;30353036return0;3037}30383039static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3040const unsigned char*new_sha1,const char*msg)3041{3042int logfd, result, oflags = O_APPEND | O_WRONLY;3043char log_file[PATH_MAX];30443045if(log_all_ref_updates <0)3046 log_all_ref_updates = !is_bare_repository();30473048 result =log_ref_setup(refname, log_file,sizeof(log_file));3049if(result)3050return result;30513052 logfd =open(log_file, oflags);3053if(logfd <0)3054return0;3055 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3056git_committer_info(0), msg);3057if(result) {3058int save_errno = errno;3059close(logfd);3060error("Unable to append to%s", log_file);3061 errno = save_errno;3062return-1;3063}3064if(close(logfd)) {3065int save_errno = errno;3066error("Unable to append to%s", log_file);3067 errno = save_errno;3068return-1;3069}3070return0;3071}30723073intis_branch(const char*refname)3074{3075return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3076}30773078/*3079 * Write sha1 into the ref specified by the lock. Make sure that errno3080 * is sane on error.3081 */3082static intwrite_ref_sha1(struct ref_lock *lock,3083const unsigned char*sha1,const char*logmsg)3084{3085static char term ='\n';3086struct object *o;30873088if(!lock) {3089 errno = EINVAL;3090return-1;3091}3092if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3093unlock_ref(lock);3094return0;3095}3096 o =parse_object(sha1);3097if(!o) {3098error("Trying to write ref%swith nonexistent object%s",3099 lock->ref_name,sha1_to_hex(sha1));3100unlock_ref(lock);3101 errno = EINVAL;3102return-1;3103}3104if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3105error("Trying to write non-commit object%sto branch%s",3106sha1_to_hex(sha1), lock->ref_name);3107unlock_ref(lock);3108 errno = EINVAL;3109return-1;3110}3111if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3112write_in_full(lock->lock_fd, &term,1) !=1||3113close_ref(lock) <0) {3114int save_errno = errno;3115error("Couldn't write%s", lock->lk->filename.buf);3116unlock_ref(lock);3117 errno = save_errno;3118return-1;3119}3120clear_loose_ref_cache(&ref_cache);3121if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3122(strcmp(lock->ref_name, lock->orig_ref_name) &&3123log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3124unlock_ref(lock);3125return-1;3126}3127if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3128/*3129 * Special hack: If a branch is updated directly and HEAD3130 * points to it (may happen on the remote side of a push3131 * for example) then logically the HEAD reflog should be3132 * updated too.3133 * A generic solution implies reverse symref information,3134 * but finding all symrefs pointing to the given branch3135 * would be rather costly for this rare event (the direct3136 * update of a branch) to be worth it. So let's cheat and3137 * check with HEAD only which should cover 99% of all usage3138 * scenarios (even 100% of the default ones).3139 */3140unsigned char head_sha1[20];3141int head_flag;3142const char*head_ref;3143 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3144 head_sha1, &head_flag);3145if(head_ref && (head_flag & REF_ISSYMREF) &&3146!strcmp(head_ref, lock->ref_name))3147log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3148}3149if(commit_ref(lock)) {3150error("Couldn't set%s", lock->ref_name);3151unlock_ref(lock);3152return-1;3153}3154unlock_ref(lock);3155return0;3156}31573158intcreate_symref(const char*ref_target,const char*refs_heads_master,3159const char*logmsg)3160{3161const char*lockpath;3162char ref[1000];3163int fd, len, written;3164char*git_HEAD =git_pathdup("%s", ref_target);3165unsigned char old_sha1[20], new_sha1[20];31663167if(logmsg &&read_ref(ref_target, old_sha1))3168hashclr(old_sha1);31693170if(safe_create_leading_directories(git_HEAD) <0)3171returnerror("unable to create directory for%s", git_HEAD);31723173#ifndef NO_SYMLINK_HEAD3174if(prefer_symlink_refs) {3175unlink(git_HEAD);3176if(!symlink(refs_heads_master, git_HEAD))3177goto done;3178fprintf(stderr,"no symlink - falling back to symbolic ref\n");3179}3180#endif31813182 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3183if(sizeof(ref) <= len) {3184error("refname too long:%s", refs_heads_master);3185goto error_free_return;3186}3187 lockpath =mkpath("%s.lock", git_HEAD);3188 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3189if(fd <0) {3190error("Unable to open%sfor writing", lockpath);3191goto error_free_return;3192}3193 written =write_in_full(fd, ref, len);3194if(close(fd) !=0|| written != len) {3195error("Unable to write to%s", lockpath);3196goto error_unlink_return;3197}3198if(rename(lockpath, git_HEAD) <0) {3199error("Unable to create%s", git_HEAD);3200goto error_unlink_return;3201}3202if(adjust_shared_perm(git_HEAD)) {3203error("Unable to fix permissions on%s", lockpath);3204 error_unlink_return:3205unlink_or_warn(lockpath);3206 error_free_return:3207free(git_HEAD);3208return-1;3209}32103211#ifndef NO_SYMLINK_HEAD3212 done:3213#endif3214if(logmsg && !read_ref(refs_heads_master, new_sha1))3215log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32163217free(git_HEAD);3218return0;3219}32203221struct read_ref_at_cb {3222const char*refname;3223unsigned long at_time;3224int cnt;3225int reccnt;3226unsigned char*sha1;3227int found_it;32283229unsigned char osha1[20];3230unsigned char nsha1[20];3231int tz;3232unsigned long date;3233char**msg;3234unsigned long*cutoff_time;3235int*cutoff_tz;3236int*cutoff_cnt;3237};32383239static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3240const char*email,unsigned long timestamp,int tz,3241const char*message,void*cb_data)3242{3243struct read_ref_at_cb *cb = cb_data;32443245 cb->reccnt++;3246 cb->tz = tz;3247 cb->date = timestamp;32483249if(timestamp <= cb->at_time || cb->cnt ==0) {3250if(cb->msg)3251*cb->msg =xstrdup(message);3252if(cb->cutoff_time)3253*cb->cutoff_time = timestamp;3254if(cb->cutoff_tz)3255*cb->cutoff_tz = tz;3256if(cb->cutoff_cnt)3257*cb->cutoff_cnt = cb->reccnt -1;3258/*3259 * we have not yet updated cb->[n|o]sha1 so they still3260 * hold the values for the previous record.3261 */3262if(!is_null_sha1(cb->osha1)) {3263hashcpy(cb->sha1, nsha1);3264if(hashcmp(cb->osha1, nsha1))3265warning("Log for ref%shas gap after%s.",3266 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3267}3268else if(cb->date == cb->at_time)3269hashcpy(cb->sha1, nsha1);3270else if(hashcmp(nsha1, cb->sha1))3271warning("Log for ref%sunexpectedly ended on%s.",3272 cb->refname,show_date(cb->date, cb->tz,3273 DATE_RFC2822));3274hashcpy(cb->osha1, osha1);3275hashcpy(cb->nsha1, nsha1);3276 cb->found_it =1;3277return1;3278}3279hashcpy(cb->osha1, osha1);3280hashcpy(cb->nsha1, nsha1);3281if(cb->cnt >0)3282 cb->cnt--;3283return0;3284}32853286static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3287const char*email,unsigned long timestamp,3288int tz,const char*message,void*cb_data)3289{3290struct read_ref_at_cb *cb = cb_data;32913292if(cb->msg)3293*cb->msg =xstrdup(message);3294if(cb->cutoff_time)3295*cb->cutoff_time = timestamp;3296if(cb->cutoff_tz)3297*cb->cutoff_tz = tz;3298if(cb->cutoff_cnt)3299*cb->cutoff_cnt = cb->reccnt;3300hashcpy(cb->sha1, osha1);3301if(is_null_sha1(cb->sha1))3302hashcpy(cb->sha1, nsha1);3303/* We just want the first entry */3304return1;3305}33063307intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3308unsigned char*sha1,char**msg,3309unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3310{3311struct read_ref_at_cb cb;33123313memset(&cb,0,sizeof(cb));3314 cb.refname = refname;3315 cb.at_time = at_time;3316 cb.cnt = cnt;3317 cb.msg = msg;3318 cb.cutoff_time = cutoff_time;3319 cb.cutoff_tz = cutoff_tz;3320 cb.cutoff_cnt = cutoff_cnt;3321 cb.sha1 = sha1;33223323for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33243325if(!cb.reccnt) {3326if(flags & GET_SHA1_QUIETLY)3327exit(128);3328else3329die("Log for%sis empty.", refname);3330}3331if(cb.found_it)3332return0;33333334for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33353336return1;3337}33383339intreflog_exists(const char*refname)3340{3341struct stat st;33423343return!lstat(git_path("logs/%s", refname), &st) &&3344S_ISREG(st.st_mode);3345}33463347intdelete_reflog(const char*refname)3348{3349returnremove_path(git_path("logs/%s", refname));3350}33513352static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3353{3354unsigned char osha1[20], nsha1[20];3355char*email_end, *message;3356unsigned long timestamp;3357int tz;33583359/* old SP new SP name <email> SP time TAB msg LF */3360if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3361get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3362get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3363!(email_end =strchr(sb->buf +82,'>')) ||3364 email_end[1] !=' '||3365!(timestamp =strtoul(email_end +2, &message,10)) ||3366!message || message[0] !=' '||3367(message[1] !='+'&& message[1] !='-') ||3368!isdigit(message[2]) || !isdigit(message[3]) ||3369!isdigit(message[4]) || !isdigit(message[5]))3370return0;/* corrupt? */3371 email_end[1] ='\0';3372 tz =strtol(message +1, NULL,10);3373if(message[6] !='\t')3374 message +=6;3375else3376 message +=7;3377returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3378}33793380static char*find_beginning_of_line(char*bob,char*scan)3381{3382while(bob < scan && *(--scan) !='\n')3383;/* keep scanning backwards */3384/*3385 * Return either beginning of the buffer, or LF at the end of3386 * the previous line.3387 */3388return scan;3389}33903391intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3392{3393struct strbuf sb = STRBUF_INIT;3394FILE*logfp;3395long pos;3396int ret =0, at_tail =1;33973398 logfp =fopen(git_path("logs/%s", refname),"r");3399if(!logfp)3400return-1;34013402/* Jump to the end */3403if(fseek(logfp,0, SEEK_END) <0)3404returnerror("cannot seek back reflog for%s:%s",3405 refname,strerror(errno));3406 pos =ftell(logfp);3407while(!ret &&0< pos) {3408int cnt;3409size_t nread;3410char buf[BUFSIZ];3411char*endp, *scanp;34123413/* Fill next block from the end */3414 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3415if(fseek(logfp, pos - cnt, SEEK_SET))3416returnerror("cannot seek back reflog for%s:%s",3417 refname,strerror(errno));3418 nread =fread(buf, cnt,1, logfp);3419if(nread !=1)3420returnerror("cannot read%dbytes from reflog for%s:%s",3421 cnt, refname,strerror(errno));3422 pos -= cnt;34233424 scanp = endp = buf + cnt;3425if(at_tail && scanp[-1] =='\n')3426/* Looking at the final LF at the end of the file */3427 scanp--;3428 at_tail =0;34293430while(buf < scanp) {3431/*3432 * terminating LF of the previous line, or the beginning3433 * of the buffer.3434 */3435char*bp;34363437 bp =find_beginning_of_line(buf, scanp);34383439if(*bp =='\n') {3440/*3441 * The newline is the end of the previous line,3442 * so we know we have complete line starting3443 * at (bp + 1). Prefix it onto any prior data3444 * we collected for the line and process it.3445 */3446strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3447 scanp = bp;3448 endp = bp +1;3449 ret =show_one_reflog_ent(&sb, fn, cb_data);3450strbuf_reset(&sb);3451if(ret)3452break;3453}else if(!pos) {3454/*3455 * We are at the start of the buffer, and the3456 * start of the file; there is no previous3457 * line, and we have everything for this one.3458 * Process it, and we can end the loop.3459 */3460strbuf_splice(&sb,0,0, buf, endp - buf);3461 ret =show_one_reflog_ent(&sb, fn, cb_data);3462strbuf_reset(&sb);3463break;3464}34653466if(bp == buf) {3467/*3468 * We are at the start of the buffer, and there3469 * is more file to read backwards. Which means3470 * we are in the middle of a line. Note that we3471 * may get here even if *bp was a newline; that3472 * just means we are at the exact end of the3473 * previous line, rather than some spot in the3474 * middle.3475 *3476 * Save away what we have to be combined with3477 * the data from the next read.3478 */3479strbuf_splice(&sb,0,0, buf, endp - buf);3480break;3481}3482}34833484}3485if(!ret && sb.len)3486die("BUG: reverse reflog parser had leftover data");34873488fclose(logfp);3489strbuf_release(&sb);3490return ret;3491}34923493intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3494{3495FILE*logfp;3496struct strbuf sb = STRBUF_INIT;3497int ret =0;34983499 logfp =fopen(git_path("logs/%s", refname),"r");3500if(!logfp)3501return-1;35023503while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3504 ret =show_one_reflog_ent(&sb, fn, cb_data);3505fclose(logfp);3506strbuf_release(&sb);3507return ret;3508}3509/*3510 * Call fn for each reflog in the namespace indicated by name. name3511 * must be empty or end with '/'. Name will be used as a scratch3512 * space, but its contents will be restored before return.3513 */3514static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3515{3516DIR*d =opendir(git_path("logs/%s", name->buf));3517int retval =0;3518struct dirent *de;3519int oldlen = name->len;35203521if(!d)3522return name->len ? errno :0;35233524while((de =readdir(d)) != NULL) {3525struct stat st;35263527if(de->d_name[0] =='.')3528continue;3529if(ends_with(de->d_name,".lock"))3530continue;3531strbuf_addstr(name, de->d_name);3532if(stat(git_path("logs/%s", name->buf), &st) <0) {3533;/* silently ignore */3534}else{3535if(S_ISDIR(st.st_mode)) {3536strbuf_addch(name,'/');3537 retval =do_for_each_reflog(name, fn, cb_data);3538}else{3539unsigned char sha1[20];3540if(read_ref_full(name->buf,0, sha1, NULL))3541 retval =error("bad ref for%s", name->buf);3542else3543 retval =fn(name->buf, sha1,0, cb_data);3544}3545if(retval)3546break;3547}3548strbuf_setlen(name, oldlen);3549}3550closedir(d);3551return retval;3552}35533554intfor_each_reflog(each_ref_fn fn,void*cb_data)3555{3556int retval;3557struct strbuf name;3558strbuf_init(&name, PATH_MAX);3559 retval =do_for_each_reflog(&name, fn, cb_data);3560strbuf_release(&name);3561return retval;3562}35633564/**3565 * Information needed for a single ref update. Set new_sha1 to the3566 * new value or to zero to delete the ref. To check the old value3567 * while locking the ref, set have_old to 1 and set old_sha1 to the3568 * value or to zero to ensure the ref does not exist before update.3569 */3570struct ref_update {3571unsigned char new_sha1[20];3572unsigned char old_sha1[20];3573int flags;/* REF_NODEREF? */3574int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3575struct ref_lock *lock;3576int type;3577char*msg;3578const char refname[FLEX_ARRAY];3579};35803581/*3582 * Transaction states.3583 * OPEN: The transaction is in a valid state and can accept new updates.3584 * An OPEN transaction can be committed.3585 * CLOSED: A closed transaction is no longer active and no other operations3586 * than free can be used on it in this state.3587 * A transaction can either become closed by successfully committing3588 * an active transaction or if there is a failure while building3589 * the transaction thus rendering it failed/inactive.3590 */3591enum ref_transaction_state {3592 REF_TRANSACTION_OPEN =0,3593 REF_TRANSACTION_CLOSED =13594};35953596/*3597 * Data structure for holding a reference transaction, which can3598 * consist of checks and updates to multiple references, carried out3599 * as atomically as possible. This structure is opaque to callers.3600 */3601struct ref_transaction {3602struct ref_update **updates;3603size_t alloc;3604size_t nr;3605enum ref_transaction_state state;3606};36073608struct ref_transaction *ref_transaction_begin(struct strbuf *err)3609{3610assert(err);36113612returnxcalloc(1,sizeof(struct ref_transaction));3613}36143615voidref_transaction_free(struct ref_transaction *transaction)3616{3617int i;36183619if(!transaction)3620return;36213622for(i =0; i < transaction->nr; i++) {3623free(transaction->updates[i]->msg);3624free(transaction->updates[i]);3625}3626free(transaction->updates);3627free(transaction);3628}36293630static struct ref_update *add_update(struct ref_transaction *transaction,3631const char*refname)3632{3633size_t len =strlen(refname);3634struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36353636strcpy((char*)update->refname, refname);3637ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3638 transaction->updates[transaction->nr++] = update;3639return update;3640}36413642intref_transaction_update(struct ref_transaction *transaction,3643const char*refname,3644const unsigned char*new_sha1,3645const unsigned char*old_sha1,3646int flags,int have_old,const char*msg,3647struct strbuf *err)3648{3649struct ref_update *update;36503651assert(err);36523653if(transaction->state != REF_TRANSACTION_OPEN)3654die("BUG: update called for transaction that is not open");36553656if(have_old && !old_sha1)3657die("BUG: have_old is true but old_sha1 is NULL");36583659if(!is_null_sha1(new_sha1) &&3660check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3661strbuf_addf(err,"refusing to update ref with bad name%s",3662 refname);3663return-1;3664}36653666 update =add_update(transaction, refname);3667hashcpy(update->new_sha1, new_sha1);3668 update->flags = flags;3669 update->have_old = have_old;3670if(have_old)3671hashcpy(update->old_sha1, old_sha1);3672if(msg)3673 update->msg =xstrdup(msg);3674return0;3675}36763677intref_transaction_create(struct ref_transaction *transaction,3678const char*refname,3679const unsigned char*new_sha1,3680int flags,const char*msg,3681struct strbuf *err)3682{3683returnref_transaction_update(transaction, refname, new_sha1,3684 null_sha1, flags,1, msg, err);3685}36863687intref_transaction_delete(struct ref_transaction *transaction,3688const char*refname,3689const unsigned char*old_sha1,3690int flags,int have_old,const char*msg,3691struct strbuf *err)3692{3693returnref_transaction_update(transaction, refname, null_sha1,3694 old_sha1, flags, have_old, msg, err);3695}36963697intupdate_ref(const char*action,const char*refname,3698const unsigned char*sha1,const unsigned char*oldval,3699int flags,enum action_on_err onerr)3700{3701struct ref_transaction *t;3702struct strbuf err = STRBUF_INIT;37033704 t =ref_transaction_begin(&err);3705if(!t ||3706ref_transaction_update(t, refname, sha1, oldval, flags,3707!!oldval, action, &err) ||3708ref_transaction_commit(t, &err)) {3709const char*str ="update_ref failed for ref '%s':%s";37103711ref_transaction_free(t);3712switch(onerr) {3713case UPDATE_REFS_MSG_ON_ERR:3714error(str, refname, err.buf);3715break;3716case UPDATE_REFS_DIE_ON_ERR:3717die(str, refname, err.buf);3718break;3719case UPDATE_REFS_QUIET_ON_ERR:3720break;3721}3722strbuf_release(&err);3723return1;3724}3725strbuf_release(&err);3726ref_transaction_free(t);3727return0;3728}37293730static intref_update_compare(const void*r1,const void*r2)3731{3732const struct ref_update *const*u1 = r1;3733const struct ref_update *const*u2 = r2;3734returnstrcmp((*u1)->refname, (*u2)->refname);3735}37363737static intref_update_reject_duplicates(struct ref_update **updates,int n,3738struct strbuf *err)3739{3740int i;37413742assert(err);37433744for(i =1; i < n; i++)3745if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3746strbuf_addf(err,3747"Multiple updates for ref '%s' not allowed.",3748 updates[i]->refname);3749return1;3750}3751return0;3752}37533754intref_transaction_commit(struct ref_transaction *transaction,3755struct strbuf *err)3756{3757int ret =0, i;3758int n = transaction->nr;3759struct ref_update **updates = transaction->updates;3760struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3761struct string_list_item *ref_to_delete;37623763assert(err);37643765if(transaction->state != REF_TRANSACTION_OPEN)3766die("BUG: commit called for transaction that is not open");37673768if(!n) {3769 transaction->state = REF_TRANSACTION_CLOSED;3770return0;3771}37723773/* Copy, sort, and reject duplicate refs */3774qsort(updates, n,sizeof(*updates), ref_update_compare);3775if(ref_update_reject_duplicates(updates, n, err)) {3776 ret = TRANSACTION_GENERIC_ERROR;3777goto cleanup;3778}37793780/* Acquire all locks while verifying old values */3781for(i =0; i < n; i++) {3782struct ref_update *update = updates[i];3783int flags = update->flags;37843785if(is_null_sha1(update->new_sha1))3786 flags |= REF_DELETING;3787 update->lock =lock_ref_sha1_basic(update->refname,3788(update->have_old ?3789 update->old_sha1 :3790 NULL),3791 NULL,3792 flags,3793&update->type);3794if(!update->lock) {3795 ret = (errno == ENOTDIR)3796? TRANSACTION_NAME_CONFLICT3797: TRANSACTION_GENERIC_ERROR;3798strbuf_addf(err,"Cannot lock the ref '%s'.",3799 update->refname);3800goto cleanup;3801}3802}38033804/* Perform updates first so live commits remain referenced */3805for(i =0; i < n; i++) {3806struct ref_update *update = updates[i];38073808if(!is_null_sha1(update->new_sha1)) {3809if(write_ref_sha1(update->lock, update->new_sha1,3810 update->msg)) {3811 update->lock = NULL;/* freed by write_ref_sha1 */3812strbuf_addf(err,"Cannot update the ref '%s'.",3813 update->refname);3814 ret = TRANSACTION_GENERIC_ERROR;3815goto cleanup;3816}3817 update->lock = NULL;/* freed by write_ref_sha1 */3818}3819}38203821/* Perform deletes now that updates are safely completed */3822for(i =0; i < n; i++) {3823struct ref_update *update = updates[i];38243825if(update->lock) {3826if(delete_ref_loose(update->lock, update->type, err)) {3827 ret = TRANSACTION_GENERIC_ERROR;3828goto cleanup;3829}38303831if(!(update->flags & REF_ISPRUNING))3832string_list_append(&refs_to_delete,3833 update->lock->ref_name);3834}3835}38363837if(repack_without_refs(&refs_to_delete, err)) {3838 ret = TRANSACTION_GENERIC_ERROR;3839goto cleanup;3840}3841for_each_string_list_item(ref_to_delete, &refs_to_delete)3842unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3843clear_loose_ref_cache(&ref_cache);38443845cleanup:3846 transaction->state = REF_TRANSACTION_CLOSED;38473848for(i =0; i < n; i++)3849if(updates[i]->lock)3850unlock_ref(updates[i]->lock);3851string_list_clear(&refs_to_delete,0);3852return ret;3853}38543855char*shorten_unambiguous_ref(const char*refname,int strict)3856{3857int i;3858static char**scanf_fmts;3859static int nr_rules;3860char*short_name;38613862if(!nr_rules) {3863/*3864 * Pre-generate scanf formats from ref_rev_parse_rules[].3865 * Generate a format suitable for scanf from a3866 * ref_rev_parse_rules rule by interpolating "%s" at the3867 * location of the "%.*s".3868 */3869size_t total_len =0;3870size_t offset =0;38713872/* the rule list is NULL terminated, count them first */3873for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3874/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3875 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38763877 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38783879 offset =0;3880for(i =0; i < nr_rules; i++) {3881assert(offset < total_len);3882 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3883 offset +=snprintf(scanf_fmts[i], total_len - offset,3884 ref_rev_parse_rules[i],2,"%s") +1;3885}3886}38873888/* bail out if there are no rules */3889if(!nr_rules)3890returnxstrdup(refname);38913892/* buffer for scanf result, at most refname must fit */3893 short_name =xstrdup(refname);38943895/* skip first rule, it will always match */3896for(i = nr_rules -1; i >0; --i) {3897int j;3898int rules_to_fail = i;3899int short_name_len;39003901if(1!=sscanf(refname, scanf_fmts[i], short_name))3902continue;39033904 short_name_len =strlen(short_name);39053906/*3907 * in strict mode, all (except the matched one) rules3908 * must fail to resolve to a valid non-ambiguous ref3909 */3910if(strict)3911 rules_to_fail = nr_rules;39123913/*3914 * check if the short name resolves to a valid ref,3915 * but use only rules prior to the matched one3916 */3917for(j =0; j < rules_to_fail; j++) {3918const char*rule = ref_rev_parse_rules[j];3919char refname[PATH_MAX];39203921/* skip matched rule */3922if(i == j)3923continue;39243925/*3926 * the short name is ambiguous, if it resolves3927 * (with this previous rule) to a valid ref3928 * read_ref() returns 0 on success3929 */3930mksnpath(refname,sizeof(refname),3931 rule, short_name_len, short_name);3932if(ref_exists(refname))3933break;3934}39353936/*3937 * short name is non-ambiguous if all previous rules3938 * haven't resolved to a valid ref3939 */3940if(j == rules_to_fail)3941return short_name;3942}39433944free(short_name);3945returnxstrdup(refname);3946}39473948static struct string_list *hide_refs;39493950intparse_hide_refs_config(const char*var,const char*value,const char*section)3951{3952if(!strcmp("transfer.hiderefs", var) ||3953/* NEEDSWORK: use parse_config_key() once both are merged */3954(starts_with(var, section) && var[strlen(section)] =='.'&&3955!strcmp(var +strlen(section),".hiderefs"))) {3956char*ref;3957int len;39583959if(!value)3960returnconfig_error_nonbool(var);3961 ref =xstrdup(value);3962 len =strlen(ref);3963while(len && ref[len -1] =='/')3964 ref[--len] ='\0';3965if(!hide_refs) {3966 hide_refs =xcalloc(1,sizeof(*hide_refs));3967 hide_refs->strdup_strings =1;3968}3969string_list_append(hide_refs, ref);3970}3971return0;3972}39733974intref_is_hidden(const char*refname)3975{3976struct string_list_item *item;39773978if(!hide_refs)3979return0;3980for_each_string_list_item(item, hide_refs) {3981int len;3982if(!starts_with(refname, item->string))3983continue;3984 len =strlen(item->string);3985if(!refname[len] || refname[len] =='/')3986return1;3987}3988return0;3989}39903991struct expire_reflog_cb {3992unsigned int flags;3993 reflog_expiry_should_prune_fn *should_prune_fn;3994void*policy_cb;3995FILE*newlog;3996unsigned char last_kept_sha1[20];3997};39983999static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4000const char*email,unsigned long timestamp,int tz,4001const char*message,void*cb_data)4002{4003struct expire_reflog_cb *cb = cb_data;4004struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;40054006if(cb->flags & EXPIRE_REFLOGS_REWRITE)4007 osha1 = cb->last_kept_sha1;40084009if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4010 message, policy_cb)) {4011if(!cb->newlog)4012printf("would prune%s", message);4013else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4014printf("prune%s", message);4015}else{4016if(cb->newlog) {4017fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4018sha1_to_hex(osha1),sha1_to_hex(nsha1),4019 email, timestamp, tz, message);4020hashcpy(cb->last_kept_sha1, nsha1);4021}4022if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4023printf("keep%s", message);4024}4025return0;4026}40274028intreflog_expire(const char*refname,const unsigned char*sha1,4029unsigned int flags,4030 reflog_expiry_prepare_fn prepare_fn,4031 reflog_expiry_should_prune_fn should_prune_fn,4032 reflog_expiry_cleanup_fn cleanup_fn,4033void*policy_cb_data)4034{4035static struct lock_file reflog_lock;4036struct expire_reflog_cb cb;4037struct ref_lock *lock;4038char*log_file;4039int status =0;40404041memset(&cb,0,sizeof(cb));4042 cb.flags = flags;4043 cb.policy_cb = policy_cb_data;4044 cb.should_prune_fn = should_prune_fn;40454046/*4047 * The reflog file is locked by holding the lock on the4048 * reference itself, plus we might need to update the4049 * reference if --updateref was specified:4050 */4051 lock =lock_ref_sha1_basic(refname, sha1, NULL,0, NULL);4052if(!lock)4053returnerror("cannot lock ref '%s'", refname);4054if(!reflog_exists(refname)) {4055unlock_ref(lock);4056return0;4057}40584059 log_file =git_pathdup("logs/%s", refname);4060if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4061/*4062 * Even though holding $GIT_DIR/logs/$reflog.lock has4063 * no locking implications, we use the lock_file4064 * machinery here anyway because it does a lot of the4065 * work we need, including cleaning up if the program4066 * exits unexpectedly.4067 */4068if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4069struct strbuf err = STRBUF_INIT;4070unable_to_lock_message(log_file, errno, &err);4071error("%s", err.buf);4072strbuf_release(&err);4073goto failure;4074}4075 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4076if(!cb.newlog) {4077error("cannot fdopen%s(%s)",4078 reflog_lock.filename.buf,strerror(errno));4079goto failure;4080}4081}40824083(*prepare_fn)(refname, sha1, cb.policy_cb);4084for_each_reflog_ent(refname, expire_reflog_ent, &cb);4085(*cleanup_fn)(cb.policy_cb);40864087if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4088if(close_lock_file(&reflog_lock)) {4089 status |=error("couldn't write%s:%s", log_file,4090strerror(errno));4091}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&4092(write_in_full(lock->lock_fd,4093sha1_to_hex(cb.last_kept_sha1),40) !=40||4094write_str_in_full(lock->lock_fd,"\n") !=1||4095close_ref(lock) <0)) {4096 status |=error("couldn't write%s",4097 lock->lk->filename.buf);4098rollback_lock_file(&reflog_lock);4099}else if(commit_lock_file(&reflog_lock)) {4100 status |=error("unable to commit reflog '%s' (%s)",4101 log_file,strerror(errno));4102}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&commit_ref(lock)) {4103 status |=error("couldn't set%s", lock->ref_name);4104}4105}4106free(log_file);4107unlock_ref(lock);4108return status;41094110 failure:4111rollback_lock_file(&reflog_lock);4112free(log_file);4113unlock_ref(lock);4114return-1;4115}