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; 15}; 16 17/* 18 * How to handle various characters in refnames: 19 * 0: An acceptable character for refs 20 * 1: End-of-component 21 * 2: ., look for a preceding . to reject .. in refs 22 * 3: {, look for a preceding @ to reject @{ in refs 23 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 24 */ 25static unsigned char refname_disposition[256] = { 261,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 274,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 290,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 300,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 310,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 320,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 330,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 34}; 35 36/* 37 * Used as a flag to ref_transaction_delete when a loose ref is being 38 * pruned. 39 */ 40#define REF_ISPRUNING 0x0100 41/* 42 * Try to read one refname component from the front of refname. 43 * Return the length of the component found, or -1 if the component is 44 * not legal. It is legal if it is something reasonable to have under 45 * ".git/refs/"; We do not like it if: 46 * 47 * - any path component of it begins with ".", or 48 * - it has double dots "..", or 49 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 50 * - it ends with a "/". 51 * - it ends with ".lock" 52 * - it contains a "\" (backslash) 53 */ 54static intcheck_refname_component(const char*refname,int flags) 55{ 56const char*cp; 57char last ='\0'; 58 59for(cp = refname; ; cp++) { 60int ch = *cp &255; 61unsigned char disp = refname_disposition[ch]; 62switch(disp) { 63case1: 64goto out; 65case2: 66if(last =='.') 67return-1;/* Refname contains "..". */ 68break; 69case3: 70if(last =='@') 71return-1;/* Refname contains "@{". */ 72break; 73case4: 74return-1; 75} 76 last = ch; 77} 78out: 79if(cp == refname) 80return0;/* Component has zero length. */ 81if(refname[0] =='.') 82return-1;/* Component starts with '.'. */ 83if(cp - refname >= LOCK_SUFFIX_LEN && 84!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 85return-1;/* Refname ends with ".lock". */ 86return cp - refname; 87} 88 89intcheck_refname_format(const char*refname,int flags) 90{ 91int component_len, component_count =0; 92 93if(!strcmp(refname,"@")) 94/* Refname is a single character '@'. */ 95return-1; 96 97while(1) { 98/* We are at the start of a path component. */ 99 component_len =check_refname_component(refname, flags); 100if(component_len <=0) { 101if((flags & REFNAME_REFSPEC_PATTERN) && 102 refname[0] =='*'&& 103(refname[1] =='\0'|| refname[1] =='/')) { 104/* Accept one wildcard as a full refname component. */ 105 flags &= ~REFNAME_REFSPEC_PATTERN; 106 component_len =1; 107}else{ 108return-1; 109} 110} 111 component_count++; 112if(refname[component_len] =='\0') 113break; 114/* Skip to next component. */ 115 refname += component_len +1; 116} 117 118if(refname[component_len -1] =='.') 119return-1;/* Refname ends with '.'. */ 120if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 121return-1;/* Refname has only one component. */ 122return0; 123} 124 125struct ref_entry; 126 127/* 128 * Information used (along with the information in ref_entry) to 129 * describe a single cached reference. This data structure only 130 * occurs embedded in a union in struct ref_entry, and only when 131 * (ref_entry->flag & REF_DIR) is zero. 132 */ 133struct ref_value { 134/* 135 * The name of the object to which this reference resolves 136 * (which may be a tag object). If REF_ISBROKEN, this is 137 * null. If REF_ISSYMREF, then this is the name of the object 138 * referred to by the last reference in the symlink chain. 139 */ 140unsigned char sha1[20]; 141 142/* 143 * If REF_KNOWS_PEELED, then this field holds the peeled value 144 * of this reference, or null if the reference is known not to 145 * be peelable. See the documentation for peel_ref() for an 146 * exact definition of "peelable". 147 */ 148unsigned char peeled[20]; 149}; 150 151struct ref_cache; 152 153/* 154 * Information used (along with the information in ref_entry) to 155 * describe a level in the hierarchy of references. This data 156 * structure only occurs embedded in a union in struct ref_entry, and 157 * only when (ref_entry.flag & REF_DIR) is set. In that case, 158 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 159 * in the directory have already been read: 160 * 161 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 162 * or packed references, already read. 163 * 164 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 165 * references that hasn't been read yet (nor has any of its 166 * subdirectories). 167 * 168 * Entries within a directory are stored within a growable array of 169 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 170 * sorted are sorted by their component name in strcmp() order and the 171 * remaining entries are unsorted. 172 * 173 * Loose references are read lazily, one directory at a time. When a 174 * directory of loose references is read, then all of the references 175 * in that directory are stored, and REF_INCOMPLETE stubs are created 176 * for any subdirectories, but the subdirectories themselves are not 177 * read. The reading is triggered by get_ref_dir(). 178 */ 179struct ref_dir { 180int nr, alloc; 181 182/* 183 * Entries with index 0 <= i < sorted are sorted by name. New 184 * entries are appended to the list unsorted, and are sorted 185 * only when required; thus we avoid the need to sort the list 186 * after the addition of every reference. 187 */ 188int sorted; 189 190/* A pointer to the ref_cache that contains this ref_dir. */ 191struct ref_cache *ref_cache; 192 193struct ref_entry **entries; 194}; 195 196/* 197 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 198 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 199 * public values; see refs.h. 200 */ 201 202/* 203 * The field ref_entry->u.value.peeled of this value entry contains 204 * the correct peeled value for the reference, which might be 205 * null_sha1 if the reference is not a tag or if it is broken. 206 */ 207#define REF_KNOWS_PEELED 0x10 208 209/* ref_entry represents a directory of references */ 210#define REF_DIR 0x20 211 212/* 213 * Entry has not yet been read from disk (used only for REF_DIR 214 * entries representing loose references) 215 */ 216#define REF_INCOMPLETE 0x40 217 218/* 219 * A ref_entry represents either a reference or a "subdirectory" of 220 * references. 221 * 222 * Each directory in the reference namespace is represented by a 223 * ref_entry with (flags & REF_DIR) set and containing a subdir member 224 * that holds the entries in that directory that have been read so 225 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 226 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 227 * used for loose reference directories. 228 * 229 * References are represented by a ref_entry with (flags & REF_DIR) 230 * unset and a value member that describes the reference's value. The 231 * flag member is at the ref_entry level, but it is also needed to 232 * interpret the contents of the value field (in other words, a 233 * ref_value object is not very much use without the enclosing 234 * ref_entry). 235 * 236 * Reference names cannot end with slash and directories' names are 237 * always stored with a trailing slash (except for the top-level 238 * directory, which is always denoted by ""). This has two nice 239 * consequences: (1) when the entries in each subdir are sorted 240 * lexicographically by name (as they usually are), the references in 241 * a whole tree can be generated in lexicographic order by traversing 242 * the tree in left-to-right, depth-first order; (2) the names of 243 * references and subdirectories cannot conflict, and therefore the 244 * presence of an empty subdirectory does not block the creation of a 245 * similarly-named reference. (The fact that reference names with the 246 * same leading components can conflict *with each other* is a 247 * separate issue that is regulated by is_refname_available().) 248 * 249 * Please note that the name field contains the fully-qualified 250 * reference (or subdirectory) name. Space could be saved by only 251 * storing the relative names. But that would require the full names 252 * to be generated on the fly when iterating in do_for_each_ref(), and 253 * would break callback functions, who have always been able to assume 254 * that the name strings that they are passed will not be freed during 255 * the iteration. 256 */ 257struct ref_entry { 258unsigned char flag;/* ISSYMREF? ISPACKED? */ 259union{ 260struct ref_value value;/* if not (flags&REF_DIR) */ 261struct ref_dir subdir;/* if (flags&REF_DIR) */ 262} u; 263/* 264 * The full name of the reference (e.g., "refs/heads/master") 265 * or the full name of the directory with a trailing slash 266 * (e.g., "refs/heads/"): 267 */ 268char name[FLEX_ARRAY]; 269}; 270 271static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 272 273static struct ref_dir *get_ref_dir(struct ref_entry *entry) 274{ 275struct ref_dir *dir; 276assert(entry->flag & REF_DIR); 277 dir = &entry->u.subdir; 278if(entry->flag & REF_INCOMPLETE) { 279read_loose_refs(entry->name, dir); 280 entry->flag &= ~REF_INCOMPLETE; 281} 282return dir; 283} 284 285/* 286 * Check if a refname is safe. 287 * For refs that start with "refs/" we consider it safe as long they do 288 * not try to resolve to outside of refs/. 289 * 290 * For all other refs we only consider them safe iff they only contain 291 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 292 * "config"). 293 */ 294static intrefname_is_safe(const char*refname) 295{ 296if(starts_with(refname,"refs/")) { 297char*buf; 298int result; 299 300 buf =xmalloc(strlen(refname) +1); 301/* 302 * Does the refname try to escape refs/? 303 * For example: refs/foo/../bar is safe but refs/foo/../../bar 304 * is not. 305 */ 306 result = !normalize_path_copy(buf, refname +strlen("refs/")); 307free(buf); 308return result; 309} 310while(*refname) { 311if(!isupper(*refname) && *refname !='_') 312return0; 313 refname++; 314} 315return1; 316} 317 318static struct ref_entry *create_ref_entry(const char*refname, 319const unsigned char*sha1,int flag, 320int check_name) 321{ 322int len; 323struct ref_entry *ref; 324 325if(check_name && 326check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 327die("Reference has invalid format: '%s'", refname); 328if(!check_name && !refname_is_safe(refname)) 329die("Reference has invalid name: '%s'", refname); 330 len =strlen(refname) +1; 331 ref =xmalloc(sizeof(struct ref_entry) + len); 332hashcpy(ref->u.value.sha1, sha1); 333hashclr(ref->u.value.peeled); 334memcpy(ref->name, refname, len); 335 ref->flag = flag; 336return ref; 337} 338 339static voidclear_ref_dir(struct ref_dir *dir); 340 341static voidfree_ref_entry(struct ref_entry *entry) 342{ 343if(entry->flag & REF_DIR) { 344/* 345 * Do not use get_ref_dir() here, as that might 346 * trigger the reading of loose refs. 347 */ 348clear_ref_dir(&entry->u.subdir); 349} 350free(entry); 351} 352 353/* 354 * Add a ref_entry to the end of dir (unsorted). Entry is always 355 * stored directly in dir; no recursion into subdirectories is 356 * done. 357 */ 358static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 359{ 360ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 361 dir->entries[dir->nr++] = entry; 362/* optimize for the case that entries are added in order */ 363if(dir->nr ==1|| 364(dir->nr == dir->sorted +1&& 365strcmp(dir->entries[dir->nr -2]->name, 366 dir->entries[dir->nr -1]->name) <0)) 367 dir->sorted = dir->nr; 368} 369 370/* 371 * Clear and free all entries in dir, recursively. 372 */ 373static voidclear_ref_dir(struct ref_dir *dir) 374{ 375int i; 376for(i =0; i < dir->nr; i++) 377free_ref_entry(dir->entries[i]); 378free(dir->entries); 379 dir->sorted = dir->nr = dir->alloc =0; 380 dir->entries = NULL; 381} 382 383/* 384 * Create a struct ref_entry object for the specified dirname. 385 * dirname is the name of the directory with a trailing slash (e.g., 386 * "refs/heads/") or "" for the top-level directory. 387 */ 388static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 389const char*dirname,size_t len, 390int incomplete) 391{ 392struct ref_entry *direntry; 393 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 394memcpy(direntry->name, dirname, len); 395 direntry->name[len] ='\0'; 396 direntry->u.subdir.ref_cache = ref_cache; 397 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 398return direntry; 399} 400 401static intref_entry_cmp(const void*a,const void*b) 402{ 403struct ref_entry *one = *(struct ref_entry **)a; 404struct ref_entry *two = *(struct ref_entry **)b; 405returnstrcmp(one->name, two->name); 406} 407 408static voidsort_ref_dir(struct ref_dir *dir); 409 410struct string_slice { 411size_t len; 412const char*str; 413}; 414 415static intref_entry_cmp_sslice(const void*key_,const void*ent_) 416{ 417const struct string_slice *key = key_; 418const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 419int cmp =strncmp(key->str, ent->name, key->len); 420if(cmp) 421return cmp; 422return'\0'- (unsigned char)ent->name[key->len]; 423} 424 425/* 426 * Return the index of the entry with the given refname from the 427 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 428 * no such entry is found. dir must already be complete. 429 */ 430static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 431{ 432struct ref_entry **r; 433struct string_slice key; 434 435if(refname == NULL || !dir->nr) 436return-1; 437 438sort_ref_dir(dir); 439 key.len = len; 440 key.str = refname; 441 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 442 ref_entry_cmp_sslice); 443 444if(r == NULL) 445return-1; 446 447return r - dir->entries; 448} 449 450/* 451 * Search for a directory entry directly within dir (without 452 * recursing). Sort dir if necessary. subdirname must be a directory 453 * name (i.e., end in '/'). If mkdir is set, then create the 454 * directory if it is missing; otherwise, return NULL if the desired 455 * directory cannot be found. dir must already be complete. 456 */ 457static struct ref_dir *search_for_subdir(struct ref_dir *dir, 458const char*subdirname,size_t len, 459int mkdir) 460{ 461int entry_index =search_ref_dir(dir, subdirname, len); 462struct ref_entry *entry; 463if(entry_index == -1) { 464if(!mkdir) 465return NULL; 466/* 467 * Since dir is complete, the absence of a subdir 468 * means that the subdir really doesn't exist; 469 * therefore, create an empty record for it but mark 470 * the record complete. 471 */ 472 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 473add_entry_to_dir(dir, entry); 474}else{ 475 entry = dir->entries[entry_index]; 476} 477returnget_ref_dir(entry); 478} 479 480/* 481 * If refname is a reference name, find the ref_dir within the dir 482 * tree that should hold refname. If refname is a directory name 483 * (i.e., ends in '/'), then return that ref_dir itself. dir must 484 * represent the top-level directory and must already be complete. 485 * Sort ref_dirs and recurse into subdirectories as necessary. If 486 * mkdir is set, then create any missing directories; otherwise, 487 * return NULL if the desired directory cannot be found. 488 */ 489static struct ref_dir *find_containing_dir(struct ref_dir *dir, 490const char*refname,int mkdir) 491{ 492const char*slash; 493for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 494size_t dirnamelen = slash - refname +1; 495struct ref_dir *subdir; 496 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 497if(!subdir) { 498 dir = NULL; 499break; 500} 501 dir = subdir; 502} 503 504return dir; 505} 506 507/* 508 * Find the value entry with the given name in dir, sorting ref_dirs 509 * and recursing into subdirectories as necessary. If the name is not 510 * found or it corresponds to a directory entry, return NULL. 511 */ 512static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 513{ 514int entry_index; 515struct ref_entry *entry; 516 dir =find_containing_dir(dir, refname,0); 517if(!dir) 518return NULL; 519 entry_index =search_ref_dir(dir, refname,strlen(refname)); 520if(entry_index == -1) 521return NULL; 522 entry = dir->entries[entry_index]; 523return(entry->flag & REF_DIR) ? NULL : entry; 524} 525 526/* 527 * Remove the entry with the given name from dir, recursing into 528 * subdirectories as necessary. If refname is the name of a directory 529 * (i.e., ends with '/'), then remove the directory and its contents. 530 * If the removal was successful, return the number of entries 531 * remaining in the directory entry that contained the deleted entry. 532 * If the name was not found, return -1. Please note that this 533 * function only deletes the entry from the cache; it does not delete 534 * it from the filesystem or ensure that other cache entries (which 535 * might be symbolic references to the removed entry) are updated. 536 * Nor does it remove any containing dir entries that might be made 537 * empty by the removal. dir must represent the top-level directory 538 * and must already be complete. 539 */ 540static intremove_entry(struct ref_dir *dir,const char*refname) 541{ 542int refname_len =strlen(refname); 543int entry_index; 544struct ref_entry *entry; 545int is_dir = refname[refname_len -1] =='/'; 546if(is_dir) { 547/* 548 * refname represents a reference directory. Remove 549 * the trailing slash; otherwise we will get the 550 * directory *representing* refname rather than the 551 * one *containing* it. 552 */ 553char*dirname =xmemdupz(refname, refname_len -1); 554 dir =find_containing_dir(dir, dirname,0); 555free(dirname); 556}else{ 557 dir =find_containing_dir(dir, refname,0); 558} 559if(!dir) 560return-1; 561 entry_index =search_ref_dir(dir, refname, refname_len); 562if(entry_index == -1) 563return-1; 564 entry = dir->entries[entry_index]; 565 566memmove(&dir->entries[entry_index], 567&dir->entries[entry_index +1], 568(dir->nr - entry_index -1) *sizeof(*dir->entries) 569); 570 dir->nr--; 571if(dir->sorted > entry_index) 572 dir->sorted--; 573free_ref_entry(entry); 574return dir->nr; 575} 576 577/* 578 * Add a ref_entry to the ref_dir (unsorted), recursing into 579 * subdirectories as necessary. dir must represent the top-level 580 * directory. Return 0 on success. 581 */ 582static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 583{ 584 dir =find_containing_dir(dir, ref->name,1); 585if(!dir) 586return-1; 587add_entry_to_dir(dir, ref); 588return0; 589} 590 591/* 592 * Emit a warning and return true iff ref1 and ref2 have the same name 593 * and the same sha1. Die if they have the same name but different 594 * sha1s. 595 */ 596static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 597{ 598if(strcmp(ref1->name, ref2->name)) 599return0; 600 601/* Duplicate name; make sure that they don't conflict: */ 602 603if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 604/* This is impossible by construction */ 605die("Reference directory conflict:%s", ref1->name); 606 607if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 608die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 609 610warning("Duplicated ref:%s", ref1->name); 611return1; 612} 613 614/* 615 * Sort the entries in dir non-recursively (if they are not already 616 * sorted) and remove any duplicate entries. 617 */ 618static voidsort_ref_dir(struct ref_dir *dir) 619{ 620int i, j; 621struct ref_entry *last = NULL; 622 623/* 624 * This check also prevents passing a zero-length array to qsort(), 625 * which is a problem on some platforms. 626 */ 627if(dir->sorted == dir->nr) 628return; 629 630qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 631 632/* Remove any duplicates: */ 633for(i =0, j =0; j < dir->nr; j++) { 634struct ref_entry *entry = dir->entries[j]; 635if(last &&is_dup_ref(last, entry)) 636free_ref_entry(entry); 637else 638 last = dir->entries[i++] = entry; 639} 640 dir->sorted = dir->nr = i; 641} 642 643/* Include broken references in a do_for_each_ref*() iteration: */ 644#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 645 646/* 647 * Return true iff the reference described by entry can be resolved to 648 * an object in the database. Emit a warning if the referred-to 649 * object does not exist. 650 */ 651static intref_resolves_to_object(struct ref_entry *entry) 652{ 653if(entry->flag & REF_ISBROKEN) 654return0; 655if(!has_sha1_file(entry->u.value.sha1)) { 656error("%sdoes not point to a valid object!", entry->name); 657return0; 658} 659return1; 660} 661 662/* 663 * current_ref is a performance hack: when iterating over references 664 * using the for_each_ref*() functions, current_ref is set to the 665 * current reference's entry before calling the callback function. If 666 * the callback function calls peel_ref(), then peel_ref() first 667 * checks whether the reference to be peeled is the current reference 668 * (it usually is) and if so, returns that reference's peeled version 669 * if it is available. This avoids a refname lookup in a common case. 670 */ 671static struct ref_entry *current_ref; 672 673typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 674 675struct ref_entry_cb { 676const char*base; 677int trim; 678int flags; 679 each_ref_fn *fn; 680void*cb_data; 681}; 682 683/* 684 * Handle one reference in a do_for_each_ref*()-style iteration, 685 * calling an each_ref_fn for each entry. 686 */ 687static intdo_one_ref(struct ref_entry *entry,void*cb_data) 688{ 689struct ref_entry_cb *data = cb_data; 690struct ref_entry *old_current_ref; 691int retval; 692 693if(!starts_with(entry->name, data->base)) 694return0; 695 696if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 697!ref_resolves_to_object(entry)) 698return0; 699 700/* Store the old value, in case this is a recursive call: */ 701 old_current_ref = current_ref; 702 current_ref = entry; 703 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 704 entry->flag, data->cb_data); 705 current_ref = old_current_ref; 706return retval; 707} 708 709/* 710 * Call fn for each reference in dir that has index in the range 711 * offset <= index < dir->nr. Recurse into subdirectories that are in 712 * that index range, sorting them before iterating. This function 713 * does not sort dir itself; it should be sorted beforehand. fn is 714 * called for all references, including broken ones. 715 */ 716static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 717 each_ref_entry_fn fn,void*cb_data) 718{ 719int i; 720assert(dir->sorted == dir->nr); 721for(i = offset; i < dir->nr; i++) { 722struct ref_entry *entry = dir->entries[i]; 723int retval; 724if(entry->flag & REF_DIR) { 725struct ref_dir *subdir =get_ref_dir(entry); 726sort_ref_dir(subdir); 727 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 728}else{ 729 retval =fn(entry, cb_data); 730} 731if(retval) 732return retval; 733} 734return0; 735} 736 737/* 738 * Call fn for each reference in the union of dir1 and dir2, in order 739 * by refname. Recurse into subdirectories. If a value entry appears 740 * in both dir1 and dir2, then only process the version that is in 741 * dir2. The input dirs must already be sorted, but subdirs will be 742 * sorted as needed. fn is called for all references, including 743 * broken ones. 744 */ 745static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 746struct ref_dir *dir2, 747 each_ref_entry_fn fn,void*cb_data) 748{ 749int retval; 750int i1 =0, i2 =0; 751 752assert(dir1->sorted == dir1->nr); 753assert(dir2->sorted == dir2->nr); 754while(1) { 755struct ref_entry *e1, *e2; 756int cmp; 757if(i1 == dir1->nr) { 758returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 759} 760if(i2 == dir2->nr) { 761returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 762} 763 e1 = dir1->entries[i1]; 764 e2 = dir2->entries[i2]; 765 cmp =strcmp(e1->name, e2->name); 766if(cmp ==0) { 767if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 768/* Both are directories; descend them in parallel. */ 769struct ref_dir *subdir1 =get_ref_dir(e1); 770struct ref_dir *subdir2 =get_ref_dir(e2); 771sort_ref_dir(subdir1); 772sort_ref_dir(subdir2); 773 retval =do_for_each_entry_in_dirs( 774 subdir1, subdir2, fn, cb_data); 775 i1++; 776 i2++; 777}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 778/* Both are references; ignore the one from dir1. */ 779 retval =fn(e2, cb_data); 780 i1++; 781 i2++; 782}else{ 783die("conflict between reference and directory:%s", 784 e1->name); 785} 786}else{ 787struct ref_entry *e; 788if(cmp <0) { 789 e = e1; 790 i1++; 791}else{ 792 e = e2; 793 i2++; 794} 795if(e->flag & REF_DIR) { 796struct ref_dir *subdir =get_ref_dir(e); 797sort_ref_dir(subdir); 798 retval =do_for_each_entry_in_dir( 799 subdir,0, fn, cb_data); 800}else{ 801 retval =fn(e, cb_data); 802} 803} 804if(retval) 805return retval; 806} 807} 808 809/* 810 * Load all of the refs from the dir into our in-memory cache. The hard work 811 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 812 * through all of the sub-directories. We do not even need to care about 813 * sorting, as traversal order does not matter to us. 814 */ 815static voidprime_ref_dir(struct ref_dir *dir) 816{ 817int i; 818for(i =0; i < dir->nr; i++) { 819struct ref_entry *entry = dir->entries[i]; 820if(entry->flag & REF_DIR) 821prime_ref_dir(get_ref_dir(entry)); 822} 823} 824 825static intentry_matches(struct ref_entry *entry,const struct string_list *list) 826{ 827return list &&string_list_has_string(list, entry->name); 828} 829 830struct nonmatching_ref_data { 831const struct string_list *skip; 832struct ref_entry *found; 833}; 834 835static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 836{ 837struct nonmatching_ref_data *data = vdata; 838 839if(entry_matches(entry, data->skip)) 840return0; 841 842 data->found = entry; 843return1; 844} 845 846static voidreport_refname_conflict(struct ref_entry *entry, 847const char*refname) 848{ 849error("'%s' exists; cannot create '%s'", entry->name, refname); 850} 851 852/* 853 * Return true iff a reference named refname could be created without 854 * conflicting with the name of an existing reference in dir. If 855 * skip is non-NULL, ignore potential conflicts with refs in skip 856 * (e.g., because they are scheduled for deletion in the same 857 * operation). 858 * 859 * Two reference names conflict if one of them exactly matches the 860 * leading components of the other; e.g., "foo/bar" conflicts with 861 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 862 * "foo/barbados". 863 * 864 * skip must be sorted. 865 */ 866static intis_refname_available(const char*refname, 867const struct string_list *skip, 868struct ref_dir *dir) 869{ 870const char*slash; 871size_t len; 872int pos; 873char*dirname; 874 875for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 876/* 877 * We are still at a leading dir of the refname; we are 878 * looking for a conflict with a leaf entry. 879 * 880 * If we find one, we still must make sure it is 881 * not in "skip". 882 */ 883 pos =search_ref_dir(dir, refname, slash - refname); 884if(pos >=0) { 885struct ref_entry *entry = dir->entries[pos]; 886if(entry_matches(entry, skip)) 887return1; 888report_refname_conflict(entry, refname); 889return0; 890} 891 892 893/* 894 * Otherwise, we can try to continue our search with 895 * the next component; if we come up empty, we know 896 * there is nothing under this whole prefix. 897 */ 898 pos =search_ref_dir(dir, refname, slash +1- refname); 899if(pos <0) 900return1; 901 902 dir =get_ref_dir(dir->entries[pos]); 903} 904 905/* 906 * We are at the leaf of our refname; we want to 907 * make sure there are no directories which match it. 908 */ 909 len =strlen(refname); 910 dirname =xmallocz(len +1); 911sprintf(dirname,"%s/", refname); 912 pos =search_ref_dir(dir, dirname, len +1); 913free(dirname); 914 915if(pos >=0) { 916/* 917 * We found a directory named "refname". It is a 918 * problem iff it contains any ref that is not 919 * in "skip". 920 */ 921struct ref_entry *entry = dir->entries[pos]; 922struct ref_dir *dir =get_ref_dir(entry); 923struct nonmatching_ref_data data; 924 925 data.skip = skip; 926sort_ref_dir(dir); 927if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 928return1; 929 930report_refname_conflict(data.found, refname); 931return0; 932} 933 934/* 935 * There is no point in searching for another leaf 936 * node which matches it; such an entry would be the 937 * ref we are looking for, not a conflict. 938 */ 939return1; 940} 941 942struct packed_ref_cache { 943struct ref_entry *root; 944 945/* 946 * Count of references to the data structure in this instance, 947 * including the pointer from ref_cache::packed if any. The 948 * data will not be freed as long as the reference count is 949 * nonzero. 950 */ 951unsigned int referrers; 952 953/* 954 * Iff the packed-refs file associated with this instance is 955 * currently locked for writing, this points at the associated 956 * lock (which is owned by somebody else). The referrer count 957 * is also incremented when the file is locked and decremented 958 * when it is unlocked. 959 */ 960struct lock_file *lock; 961 962/* The metadata from when this packed-refs cache was read */ 963struct stat_validity validity; 964}; 965 966/* 967 * Future: need to be in "struct repository" 968 * when doing a full libification. 969 */ 970static struct ref_cache { 971struct ref_cache *next; 972struct ref_entry *loose; 973struct packed_ref_cache *packed; 974/* 975 * The submodule name, or "" for the main repo. We allocate 976 * length 1 rather than FLEX_ARRAY so that the main ref_cache 977 * is initialized correctly. 978 */ 979char name[1]; 980} ref_cache, *submodule_ref_caches; 981 982/* Lock used for the main packed-refs file: */ 983static struct lock_file packlock; 984 985/* 986 * Increment the reference count of *packed_refs. 987 */ 988static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 989{ 990 packed_refs->referrers++; 991} 992 993/* 994 * Decrease the reference count of *packed_refs. If it goes to zero, 995 * free *packed_refs and return true; otherwise return false. 996 */ 997static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 998{ 999if(!--packed_refs->referrers) {1000free_ref_entry(packed_refs->root);1001stat_validity_clear(&packed_refs->validity);1002free(packed_refs);1003return1;1004}else{1005return0;1006}1007}10081009static voidclear_packed_ref_cache(struct ref_cache *refs)1010{1011if(refs->packed) {1012struct packed_ref_cache *packed_refs = refs->packed;10131014if(packed_refs->lock)1015die("internal error: packed-ref cache cleared while locked");1016 refs->packed = NULL;1017release_packed_ref_cache(packed_refs);1018}1019}10201021static voidclear_loose_ref_cache(struct ref_cache *refs)1022{1023if(refs->loose) {1024free_ref_entry(refs->loose);1025 refs->loose = NULL;1026}1027}10281029static struct ref_cache *create_ref_cache(const char*submodule)1030{1031int len;1032struct ref_cache *refs;1033if(!submodule)1034 submodule ="";1035 len =strlen(submodule) +1;1036 refs =xcalloc(1,sizeof(struct ref_cache) + len);1037memcpy(refs->name, submodule, len);1038return refs;1039}10401041/*1042 * Return a pointer to a ref_cache for the specified submodule. For1043 * the main repository, use submodule==NULL. The returned structure1044 * will be allocated and initialized but not necessarily populated; it1045 * should not be freed.1046 */1047static struct ref_cache *get_ref_cache(const char*submodule)1048{1049struct ref_cache *refs;10501051if(!submodule || !*submodule)1052return&ref_cache;10531054for(refs = submodule_ref_caches; refs; refs = refs->next)1055if(!strcmp(submodule, refs->name))1056return refs;10571058 refs =create_ref_cache(submodule);1059 refs->next = submodule_ref_caches;1060 submodule_ref_caches = refs;1061return refs;1062}10631064/* The length of a peeled reference line in packed-refs, including EOL: */1065#define PEELED_LINE_LENGTH 4210661067/*1068 * The packed-refs header line that we write out. Perhaps other1069 * traits will be added later. The trailing space is required.1070 */1071static const char PACKED_REFS_HEADER[] =1072"# pack-refs with: peeled fully-peeled\n";10731074/*1075 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1076 * Return a pointer to the refname within the line (null-terminated),1077 * or NULL if there was a problem.1078 */1079static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1080{1081const char*ref;10821083/*1084 * 42: the answer to everything.1085 *1086 * In this case, it happens to be the answer to1087 * 40 (length of sha1 hex representation)1088 * +1 (space in between hex and name)1089 * +1 (newline at the end of the line)1090 */1091if(line->len <=42)1092return NULL;10931094if(get_sha1_hex(line->buf, sha1) <0)1095return NULL;1096if(!isspace(line->buf[40]))1097return NULL;10981099 ref = line->buf +41;1100if(isspace(*ref))1101return NULL;11021103if(line->buf[line->len -1] !='\n')1104return NULL;1105 line->buf[--line->len] =0;11061107return ref;1108}11091110/*1111 * Read f, which is a packed-refs file, into dir.1112 *1113 * A comment line of the form "# pack-refs with: " may contain zero or1114 * more traits. We interpret the traits as follows:1115 *1116 * No traits:1117 *1118 * Probably no references are peeled. But if the file contains a1119 * peeled value for a reference, we will use it.1120 *1121 * peeled:1122 *1123 * References under "refs/tags/", if they *can* be peeled, *are*1124 * peeled in this file. References outside of "refs/tags/" are1125 * probably not peeled even if they could have been, but if we find1126 * a peeled value for such a reference we will use it.1127 *1128 * fully-peeled:1129 *1130 * All references in the file that can be peeled are peeled.1131 * Inversely (and this is more important), any references in the1132 * file for which no peeled value is recorded is not peelable. This1133 * trait should typically be written alongside "peeled" for1134 * compatibility with older clients, but we do not require it1135 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1136 */1137static voidread_packed_refs(FILE*f,struct ref_dir *dir)1138{1139struct ref_entry *last = NULL;1140struct strbuf line = STRBUF_INIT;1141enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11421143while(strbuf_getwholeline(&line, f,'\n') != EOF) {1144unsigned char sha1[20];1145const char*refname;1146const char*traits;11471148if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1149if(strstr(traits," fully-peeled "))1150 peeled = PEELED_FULLY;1151else if(strstr(traits," peeled "))1152 peeled = PEELED_TAGS;1153/* perhaps other traits later as well */1154continue;1155}11561157 refname =parse_ref_line(&line, sha1);1158if(refname) {1159int flag = REF_ISPACKED;11601161if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1162hashclr(sha1);1163 flag |= REF_BAD_NAME | REF_ISBROKEN;1164}1165 last =create_ref_entry(refname, sha1, flag,0);1166if(peeled == PEELED_FULLY ||1167(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1168 last->flag |= REF_KNOWS_PEELED;1169add_ref(dir, last);1170continue;1171}1172if(last &&1173 line.buf[0] =='^'&&1174 line.len == PEELED_LINE_LENGTH &&1175 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1176!get_sha1_hex(line.buf +1, sha1)) {1177hashcpy(last->u.value.peeled, sha1);1178/*1179 * Regardless of what the file header said,1180 * we definitely know the value of *this*1181 * reference:1182 */1183 last->flag |= REF_KNOWS_PEELED;1184}1185}11861187strbuf_release(&line);1188}11891190/*1191 * Get the packed_ref_cache for the specified ref_cache, creating it1192 * if necessary.1193 */1194static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1195{1196const char*packed_refs_file;11971198if(*refs->name)1199 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1200else1201 packed_refs_file =git_path("packed-refs");12021203if(refs->packed &&1204!stat_validity_check(&refs->packed->validity, packed_refs_file))1205clear_packed_ref_cache(refs);12061207if(!refs->packed) {1208FILE*f;12091210 refs->packed =xcalloc(1,sizeof(*refs->packed));1211acquire_packed_ref_cache(refs->packed);1212 refs->packed->root =create_dir_entry(refs,"",0,0);1213 f =fopen(packed_refs_file,"r");1214if(f) {1215stat_validity_update(&refs->packed->validity,fileno(f));1216read_packed_refs(f,get_ref_dir(refs->packed->root));1217fclose(f);1218}1219}1220return refs->packed;1221}12221223static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1224{1225returnget_ref_dir(packed_ref_cache->root);1226}12271228static struct ref_dir *get_packed_refs(struct ref_cache *refs)1229{1230returnget_packed_ref_dir(get_packed_ref_cache(refs));1231}12321233voidadd_packed_ref(const char*refname,const unsigned char*sha1)1234{1235struct packed_ref_cache *packed_ref_cache =1236get_packed_ref_cache(&ref_cache);12371238if(!packed_ref_cache->lock)1239die("internal error: packed refs not locked");1240add_ref(get_packed_ref_dir(packed_ref_cache),1241create_ref_entry(refname, sha1, REF_ISPACKED,1));1242}12431244/*1245 * Read the loose references from the namespace dirname into dir1246 * (without recursing). dirname must end with '/'. dir must be the1247 * directory entry corresponding to dirname.1248 */1249static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1250{1251struct ref_cache *refs = dir->ref_cache;1252DIR*d;1253const char*path;1254struct dirent *de;1255int dirnamelen =strlen(dirname);1256struct strbuf refname;12571258if(*refs->name)1259 path =git_path_submodule(refs->name,"%s", dirname);1260else1261 path =git_path("%s", dirname);12621263 d =opendir(path);1264if(!d)1265return;12661267strbuf_init(&refname, dirnamelen +257);1268strbuf_add(&refname, dirname, dirnamelen);12691270while((de =readdir(d)) != NULL) {1271unsigned char sha1[20];1272struct stat st;1273int flag;1274const char*refdir;12751276if(de->d_name[0] =='.')1277continue;1278if(ends_with(de->d_name,".lock"))1279continue;1280strbuf_addstr(&refname, de->d_name);1281 refdir = *refs->name1282?git_path_submodule(refs->name,"%s", refname.buf)1283:git_path("%s", refname.buf);1284if(stat(refdir, &st) <0) {1285;/* silently ignore */1286}else if(S_ISDIR(st.st_mode)) {1287strbuf_addch(&refname,'/');1288add_entry_to_dir(dir,1289create_dir_entry(refs, refname.buf,1290 refname.len,1));1291}else{1292if(*refs->name) {1293hashclr(sha1);1294 flag =0;1295if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1296hashclr(sha1);1297 flag |= REF_ISBROKEN;1298}1299}else if(read_ref_full(refname.buf,1300 RESOLVE_REF_READING,1301 sha1, &flag)) {1302hashclr(sha1);1303 flag |= REF_ISBROKEN;1304}1305if(check_refname_format(refname.buf,1306 REFNAME_ALLOW_ONELEVEL)) {1307hashclr(sha1);1308 flag |= REF_BAD_NAME | REF_ISBROKEN;1309}1310add_entry_to_dir(dir,1311create_ref_entry(refname.buf, sha1, flag,0));1312}1313strbuf_setlen(&refname, dirnamelen);1314}1315strbuf_release(&refname);1316closedir(d);1317}13181319static struct ref_dir *get_loose_refs(struct ref_cache *refs)1320{1321if(!refs->loose) {1322/*1323 * Mark the top-level directory complete because we1324 * are about to read the only subdirectory that can1325 * hold references:1326 */1327 refs->loose =create_dir_entry(refs,"",0,0);1328/*1329 * Create an incomplete entry for "refs/":1330 */1331add_entry_to_dir(get_ref_dir(refs->loose),1332create_dir_entry(refs,"refs/",5,1));1333}1334returnget_ref_dir(refs->loose);1335}13361337/* We allow "recursive" symbolic refs. Only within reason, though */1338#define MAXDEPTH 51339#define MAXREFLEN (1024)13401341/*1342 * Called by resolve_gitlink_ref_recursive() after it failed to read1343 * from the loose refs in ref_cache refs. Find <refname> in the1344 * packed-refs file for the submodule.1345 */1346static intresolve_gitlink_packed_ref(struct ref_cache *refs,1347const char*refname,unsigned char*sha1)1348{1349struct ref_entry *ref;1350struct ref_dir *dir =get_packed_refs(refs);13511352 ref =find_ref(dir, refname);1353if(ref == NULL)1354return-1;13551356hashcpy(sha1, ref->u.value.sha1);1357return0;1358}13591360static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1361const char*refname,unsigned char*sha1,1362int recursion)1363{1364int fd, len;1365char buffer[128], *p;1366char*path;13671368if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1369return-1;1370 path = *refs->name1371?git_path_submodule(refs->name,"%s", refname)1372:git_path("%s", refname);1373 fd =open(path, O_RDONLY);1374if(fd <0)1375returnresolve_gitlink_packed_ref(refs, refname, sha1);13761377 len =read(fd, buffer,sizeof(buffer)-1);1378close(fd);1379if(len <0)1380return-1;1381while(len &&isspace(buffer[len-1]))1382 len--;1383 buffer[len] =0;13841385/* Was it a detached head or an old-fashioned symlink? */1386if(!get_sha1_hex(buffer, sha1))1387return0;13881389/* Symref? */1390if(strncmp(buffer,"ref:",4))1391return-1;1392 p = buffer +4;1393while(isspace(*p))1394 p++;13951396returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1397}13981399intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1400{1401int len =strlen(path), retval;1402char*submodule;1403struct ref_cache *refs;14041405while(len && path[len-1] =='/')1406 len--;1407if(!len)1408return-1;1409 submodule =xstrndup(path, len);1410 refs =get_ref_cache(submodule);1411free(submodule);14121413 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1414return retval;1415}14161417/*1418 * Return the ref_entry for the given refname from the packed1419 * references. If it does not exist, return NULL.1420 */1421static struct ref_entry *get_packed_ref(const char*refname)1422{1423returnfind_ref(get_packed_refs(&ref_cache), refname);1424}14251426/*1427 * A loose ref file doesn't exist; check for a packed ref. The1428 * options are forwarded from resolve_safe_unsafe().1429 */1430static intresolve_missing_loose_ref(const char*refname,1431int resolve_flags,1432unsigned char*sha1,1433int*flags)1434{1435struct ref_entry *entry;14361437/*1438 * The loose reference file does not exist; check for a packed1439 * reference.1440 */1441 entry =get_packed_ref(refname);1442if(entry) {1443hashcpy(sha1, entry->u.value.sha1);1444if(flags)1445*flags |= REF_ISPACKED;1446return0;1447}1448/* The reference is not a packed reference, either. */1449if(resolve_flags & RESOLVE_REF_READING) {1450 errno = ENOENT;1451return-1;1452}else{1453hashclr(sha1);1454return0;1455}1456}14571458/* This function needs to return a meaningful errno on failure */1459const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1460{1461int depth = MAXDEPTH;1462 ssize_t len;1463char buffer[256];1464static char refname_buffer[256];1465int bad_name =0;14661467if(flags)1468*flags =0;14691470if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1471if(flags)1472*flags |= REF_BAD_NAME;14731474if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1475!refname_is_safe(refname)) {1476 errno = EINVAL;1477return NULL;1478}1479/*1480 * dwim_ref() uses REF_ISBROKEN to distinguish between1481 * missing refs and refs that were present but invalid,1482 * to complain about the latter to stderr.1483 *1484 * We don't know whether the ref exists, so don't set1485 * REF_ISBROKEN yet.1486 */1487 bad_name =1;1488}1489for(;;) {1490char path[PATH_MAX];1491struct stat st;1492char*buf;1493int fd;14941495if(--depth <0) {1496 errno = ELOOP;1497return NULL;1498}14991500git_snpath(path,sizeof(path),"%s", refname);15011502/*1503 * We might have to loop back here to avoid a race1504 * condition: first we lstat() the file, then we try1505 * to read it as a link or as a file. But if somebody1506 * changes the type of the file (file <-> directory1507 * <-> symlink) between the lstat() and reading, then1508 * we don't want to report that as an error but rather1509 * try again starting with the lstat().1510 */1511 stat_ref:1512if(lstat(path, &st) <0) {1513if(errno != ENOENT)1514return NULL;1515if(resolve_missing_loose_ref(refname, resolve_flags,1516 sha1, flags))1517return NULL;1518if(bad_name) {1519hashclr(sha1);1520if(flags)1521*flags |= REF_ISBROKEN;1522}1523return refname;1524}15251526/* Follow "normalized" - ie "refs/.." symlinks by hand */1527if(S_ISLNK(st.st_mode)) {1528 len =readlink(path, buffer,sizeof(buffer)-1);1529if(len <0) {1530if(errno == ENOENT || errno == EINVAL)1531/* inconsistent with lstat; retry */1532goto stat_ref;1533else1534return NULL;1535}1536 buffer[len] =0;1537if(starts_with(buffer,"refs/") &&1538!check_refname_format(buffer,0)) {1539strcpy(refname_buffer, buffer);1540 refname = refname_buffer;1541if(flags)1542*flags |= REF_ISSYMREF;1543if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1544hashclr(sha1);1545return refname;1546}1547continue;1548}1549}15501551/* Is it a directory? */1552if(S_ISDIR(st.st_mode)) {1553 errno = EISDIR;1554return NULL;1555}15561557/*1558 * Anything else, just open it and try to use it as1559 * a ref1560 */1561 fd =open(path, O_RDONLY);1562if(fd <0) {1563if(errno == ENOENT)1564/* inconsistent with lstat; retry */1565goto stat_ref;1566else1567return NULL;1568}1569 len =read_in_full(fd, buffer,sizeof(buffer)-1);1570if(len <0) {1571int save_errno = errno;1572close(fd);1573 errno = save_errno;1574return NULL;1575}1576close(fd);1577while(len &&isspace(buffer[len-1]))1578 len--;1579 buffer[len] ='\0';15801581/*1582 * Is it a symbolic ref?1583 */1584if(!starts_with(buffer,"ref:")) {1585/*1586 * Please note that FETCH_HEAD has a second1587 * line containing other data.1588 */1589if(get_sha1_hex(buffer, sha1) ||1590(buffer[40] !='\0'&& !isspace(buffer[40]))) {1591if(flags)1592*flags |= REF_ISBROKEN;1593 errno = EINVAL;1594return NULL;1595}1596if(bad_name) {1597hashclr(sha1);1598if(flags)1599*flags |= REF_ISBROKEN;1600}1601return refname;1602}1603if(flags)1604*flags |= REF_ISSYMREF;1605 buf = buffer +4;1606while(isspace(*buf))1607 buf++;1608 refname =strcpy(refname_buffer, buf);1609if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1610hashclr(sha1);1611return refname;1612}1613if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1614if(flags)1615*flags |= REF_ISBROKEN;16161617if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1618!refname_is_safe(buf)) {1619 errno = EINVAL;1620return NULL;1621}1622 bad_name =1;1623}1624}1625}16261627char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1628{1629const char*ret =resolve_ref_unsafe(ref, resolve_flags, sha1, flags);1630return ret ?xstrdup(ret) : NULL;1631}16321633/* The argument to filter_refs */1634struct ref_filter {1635const char*pattern;1636 each_ref_fn *fn;1637void*cb_data;1638};16391640intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1641{1642if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1643return0;1644return-1;1645}16461647intread_ref(const char*refname,unsigned char*sha1)1648{1649returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1650}16511652intref_exists(const char*refname)1653{1654unsigned char sha1[20];1655return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1656}16571658static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1659void*data)1660{1661struct ref_filter *filter = (struct ref_filter *)data;1662if(wildmatch(filter->pattern, refname,0, NULL))1663return0;1664return filter->fn(refname, sha1, flags, filter->cb_data);1665}16661667enum peel_status {1668/* object was peeled successfully: */1669 PEEL_PEELED =0,16701671/*1672 * object cannot be peeled because the named object (or an1673 * object referred to by a tag in the peel chain), does not1674 * exist.1675 */1676 PEEL_INVALID = -1,16771678/* object cannot be peeled because it is not a tag: */1679 PEEL_NON_TAG = -2,16801681/* ref_entry contains no peeled value because it is a symref: */1682 PEEL_IS_SYMREF = -3,16831684/*1685 * ref_entry cannot be peeled because it is broken (i.e., the1686 * symbolic reference cannot even be resolved to an object1687 * name):1688 */1689 PEEL_BROKEN = -41690};16911692/*1693 * Peel the named object; i.e., if the object is a tag, resolve the1694 * tag recursively until a non-tag is found. If successful, store the1695 * result to sha1 and return PEEL_PEELED. If the object is not a tag1696 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1697 * and leave sha1 unchanged.1698 */1699static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1700{1701struct object *o =lookup_unknown_object(name);17021703if(o->type == OBJ_NONE) {1704int type =sha1_object_info(name, NULL);1705if(type <0|| !object_as_type(o, type,0))1706return PEEL_INVALID;1707}17081709if(o->type != OBJ_TAG)1710return PEEL_NON_TAG;17111712 o =deref_tag_noverify(o);1713if(!o)1714return PEEL_INVALID;17151716hashcpy(sha1, o->sha1);1717return PEEL_PEELED;1718}17191720/*1721 * Peel the entry (if possible) and return its new peel_status. If1722 * repeel is true, re-peel the entry even if there is an old peeled1723 * value that is already stored in it.1724 *1725 * It is OK to call this function with a packed reference entry that1726 * might be stale and might even refer to an object that has since1727 * been garbage-collected. In such a case, if the entry has1728 * REF_KNOWS_PEELED then leave the status unchanged and return1729 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1730 */1731static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1732{1733enum peel_status status;17341735if(entry->flag & REF_KNOWS_PEELED) {1736if(repeel) {1737 entry->flag &= ~REF_KNOWS_PEELED;1738hashclr(entry->u.value.peeled);1739}else{1740returnis_null_sha1(entry->u.value.peeled) ?1741 PEEL_NON_TAG : PEEL_PEELED;1742}1743}1744if(entry->flag & REF_ISBROKEN)1745return PEEL_BROKEN;1746if(entry->flag & REF_ISSYMREF)1747return PEEL_IS_SYMREF;17481749 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1750if(status == PEEL_PEELED || status == PEEL_NON_TAG)1751 entry->flag |= REF_KNOWS_PEELED;1752return status;1753}17541755intpeel_ref(const char*refname,unsigned char*sha1)1756{1757int flag;1758unsigned char base[20];17591760if(current_ref && (current_ref->name == refname1761|| !strcmp(current_ref->name, refname))) {1762if(peel_entry(current_ref,0))1763return-1;1764hashcpy(sha1, current_ref->u.value.peeled);1765return0;1766}17671768if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1769return-1;17701771/*1772 * If the reference is packed, read its ref_entry from the1773 * cache in the hope that we already know its peeled value.1774 * We only try this optimization on packed references because1775 * (a) forcing the filling of the loose reference cache could1776 * be expensive and (b) loose references anyway usually do not1777 * have REF_KNOWS_PEELED.1778 */1779if(flag & REF_ISPACKED) {1780struct ref_entry *r =get_packed_ref(refname);1781if(r) {1782if(peel_entry(r,0))1783return-1;1784hashcpy(sha1, r->u.value.peeled);1785return0;1786}1787}17881789returnpeel_object(base, sha1);1790}17911792struct warn_if_dangling_data {1793FILE*fp;1794const char*refname;1795const struct string_list *refnames;1796const char*msg_fmt;1797};17981799static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1800int flags,void*cb_data)1801{1802struct warn_if_dangling_data *d = cb_data;1803const char*resolves_to;1804unsigned char junk[20];18051806if(!(flags & REF_ISSYMREF))1807return0;18081809 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1810if(!resolves_to1811|| (d->refname1812?strcmp(resolves_to, d->refname)1813: !string_list_has_string(d->refnames, resolves_to))) {1814return0;1815}18161817fprintf(d->fp, d->msg_fmt, refname);1818fputc('\n', d->fp);1819return0;1820}18211822voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1823{1824struct warn_if_dangling_data data;18251826 data.fp = fp;1827 data.refname = refname;1828 data.refnames = NULL;1829 data.msg_fmt = msg_fmt;1830for_each_rawref(warn_if_dangling_symref, &data);1831}18321833voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1834{1835struct warn_if_dangling_data data;18361837 data.fp = fp;1838 data.refname = NULL;1839 data.refnames = refnames;1840 data.msg_fmt = msg_fmt;1841for_each_rawref(warn_if_dangling_symref, &data);1842}18431844/*1845 * Call fn for each reference in the specified ref_cache, omitting1846 * references not in the containing_dir of base. fn is called for all1847 * references, including broken ones. If fn ever returns a non-zero1848 * value, stop the iteration and return that value; otherwise, return1849 * 0.1850 */1851static intdo_for_each_entry(struct ref_cache *refs,const char*base,1852 each_ref_entry_fn fn,void*cb_data)1853{1854struct packed_ref_cache *packed_ref_cache;1855struct ref_dir *loose_dir;1856struct ref_dir *packed_dir;1857int retval =0;18581859/*1860 * We must make sure that all loose refs are read before accessing the1861 * packed-refs file; this avoids a race condition in which loose refs1862 * are migrated to the packed-refs file by a simultaneous process, but1863 * our in-memory view is from before the migration. get_packed_ref_cache()1864 * takes care of making sure our view is up to date with what is on1865 * disk.1866 */1867 loose_dir =get_loose_refs(refs);1868if(base && *base) {1869 loose_dir =find_containing_dir(loose_dir, base,0);1870}1871if(loose_dir)1872prime_ref_dir(loose_dir);18731874 packed_ref_cache =get_packed_ref_cache(refs);1875acquire_packed_ref_cache(packed_ref_cache);1876 packed_dir =get_packed_ref_dir(packed_ref_cache);1877if(base && *base) {1878 packed_dir =find_containing_dir(packed_dir, base,0);1879}18801881if(packed_dir && loose_dir) {1882sort_ref_dir(packed_dir);1883sort_ref_dir(loose_dir);1884 retval =do_for_each_entry_in_dirs(1885 packed_dir, loose_dir, fn, cb_data);1886}else if(packed_dir) {1887sort_ref_dir(packed_dir);1888 retval =do_for_each_entry_in_dir(1889 packed_dir,0, fn, cb_data);1890}else if(loose_dir) {1891sort_ref_dir(loose_dir);1892 retval =do_for_each_entry_in_dir(1893 loose_dir,0, fn, cb_data);1894}18951896release_packed_ref_cache(packed_ref_cache);1897return retval;1898}18991900/*1901 * Call fn for each reference in the specified ref_cache for which the1902 * refname begins with base. If trim is non-zero, then trim that many1903 * characters off the beginning of each refname before passing the1904 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1905 * broken references in the iteration. If fn ever returns a non-zero1906 * value, stop the iteration and return that value; otherwise, return1907 * 0.1908 */1909static intdo_for_each_ref(struct ref_cache *refs,const char*base,1910 each_ref_fn fn,int trim,int flags,void*cb_data)1911{1912struct ref_entry_cb data;1913 data.base = base;1914 data.trim = trim;1915 data.flags = flags;1916 data.fn = fn;1917 data.cb_data = cb_data;19181919returndo_for_each_entry(refs, base, do_one_ref, &data);1920}19211922static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1923{1924unsigned char sha1[20];1925int flag;19261927if(submodule) {1928if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1929returnfn("HEAD", sha1,0, cb_data);19301931return0;1932}19331934if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1935returnfn("HEAD", sha1, flag, cb_data);19361937return0;1938}19391940inthead_ref(each_ref_fn fn,void*cb_data)1941{1942returndo_head_ref(NULL, fn, cb_data);1943}19441945inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1946{1947returndo_head_ref(submodule, fn, cb_data);1948}19491950intfor_each_ref(each_ref_fn fn,void*cb_data)1951{1952returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1953}19541955intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1956{1957returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1958}19591960intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1961{1962returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1963}19641965intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1966 each_ref_fn fn,void*cb_data)1967{1968returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1969}19701971intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1972{1973returnfor_each_ref_in("refs/tags/", fn, cb_data);1974}19751976intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1977{1978returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1979}19801981intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1982{1983returnfor_each_ref_in("refs/heads/", fn, cb_data);1984}19851986intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1987{1988returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1989}19901991intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1992{1993returnfor_each_ref_in("refs/remotes/", fn, cb_data);1994}19951996intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1997{1998returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1999}20002001intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2002{2003returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2004}20052006inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2007{2008struct strbuf buf = STRBUF_INIT;2009int ret =0;2010unsigned char sha1[20];2011int flag;20122013strbuf_addf(&buf,"%sHEAD",get_git_namespace());2014if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2015 ret =fn(buf.buf, sha1, flag, cb_data);2016strbuf_release(&buf);20172018return ret;2019}20202021intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2022{2023struct strbuf buf = STRBUF_INIT;2024int ret;2025strbuf_addf(&buf,"%srefs/",get_git_namespace());2026 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2027strbuf_release(&buf);2028return ret;2029}20302031intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2032const char*prefix,void*cb_data)2033{2034struct strbuf real_pattern = STRBUF_INIT;2035struct ref_filter filter;2036int ret;20372038if(!prefix && !starts_with(pattern,"refs/"))2039strbuf_addstr(&real_pattern,"refs/");2040else if(prefix)2041strbuf_addstr(&real_pattern, prefix);2042strbuf_addstr(&real_pattern, pattern);20432044if(!has_glob_specials(pattern)) {2045/* Append implied '/' '*' if not present. */2046if(real_pattern.buf[real_pattern.len -1] !='/')2047strbuf_addch(&real_pattern,'/');2048/* No need to check for '*', there is none. */2049strbuf_addch(&real_pattern,'*');2050}20512052 filter.pattern = real_pattern.buf;2053 filter.fn = fn;2054 filter.cb_data = cb_data;2055 ret =for_each_ref(filter_refs, &filter);20562057strbuf_release(&real_pattern);2058return ret;2059}20602061intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2062{2063returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2064}20652066intfor_each_rawref(each_ref_fn fn,void*cb_data)2067{2068returndo_for_each_ref(&ref_cache,"", fn,0,2069 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2070}20712072const char*prettify_refname(const char*name)2073{2074return name + (2075starts_with(name,"refs/heads/") ?11:2076starts_with(name,"refs/tags/") ?10:2077starts_with(name,"refs/remotes/") ?13:20780);2079}20802081static const char*ref_rev_parse_rules[] = {2082"%.*s",2083"refs/%.*s",2084"refs/tags/%.*s",2085"refs/heads/%.*s",2086"refs/remotes/%.*s",2087"refs/remotes/%.*s/HEAD",2088 NULL2089};20902091intrefname_match(const char*abbrev_name,const char*full_name)2092{2093const char**p;2094const int abbrev_name_len =strlen(abbrev_name);20952096for(p = ref_rev_parse_rules; *p; p++) {2097if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2098return1;2099}2100}21012102return0;2103}21042105static voidunlock_ref(struct ref_lock *lock)2106{2107/* Do not free lock->lk -- atexit() still looks at them */2108if(lock->lk)2109rollback_lock_file(lock->lk);2110free(lock->ref_name);2111free(lock->orig_ref_name);2112free(lock);2113}21142115/* This function should make sure errno is meaningful on error */2116static struct ref_lock *verify_lock(struct ref_lock *lock,2117const unsigned char*old_sha1,int mustexist)2118{2119if(read_ref_full(lock->ref_name,2120 mustexist ? RESOLVE_REF_READING :0,2121 lock->old_sha1, NULL)) {2122int save_errno = errno;2123error("Can't verify ref%s", lock->ref_name);2124unlock_ref(lock);2125 errno = save_errno;2126return NULL;2127}2128if(hashcmp(lock->old_sha1, old_sha1)) {2129error("Ref%sis at%sbut expected%s", lock->ref_name,2130sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2131unlock_ref(lock);2132 errno = EBUSY;2133return NULL;2134}2135return lock;2136}21372138static intremove_empty_directories(const char*file)2139{2140/* we want to create a file but there is a directory there;2141 * if that is an empty directory (or a directory that contains2142 * only empty directories), remove them.2143 */2144struct strbuf path;2145int result, save_errno;21462147strbuf_init(&path,20);2148strbuf_addstr(&path, file);21492150 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2151 save_errno = errno;21522153strbuf_release(&path);2154 errno = save_errno;21552156return result;2157}21582159/*2160 * *string and *len will only be substituted, and *string returned (for2161 * later free()ing) if the string passed in is a magic short-hand form2162 * to name a branch.2163 */2164static char*substitute_branch_name(const char**string,int*len)2165{2166struct strbuf buf = STRBUF_INIT;2167int ret =interpret_branch_name(*string, *len, &buf);21682169if(ret == *len) {2170size_t size;2171*string =strbuf_detach(&buf, &size);2172*len = size;2173return(char*)*string;2174}21752176return NULL;2177}21782179intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2180{2181char*last_branch =substitute_branch_name(&str, &len);2182const char**p, *r;2183int refs_found =0;21842185*ref = NULL;2186for(p = ref_rev_parse_rules; *p; p++) {2187char fullref[PATH_MAX];2188unsigned char sha1_from_ref[20];2189unsigned char*this_result;2190int flag;21912192 this_result = refs_found ? sha1_from_ref : sha1;2193mksnpath(fullref,sizeof(fullref), *p, len, str);2194 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2195 this_result, &flag);2196if(r) {2197if(!refs_found++)2198*ref =xstrdup(r);2199if(!warn_ambiguous_refs)2200break;2201}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2202warning("ignoring dangling symref%s.", fullref);2203}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2204warning("ignoring broken ref%s.", fullref);2205}2206}2207free(last_branch);2208return refs_found;2209}22102211intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2212{2213char*last_branch =substitute_branch_name(&str, &len);2214const char**p;2215int logs_found =0;22162217*log = NULL;2218for(p = ref_rev_parse_rules; *p; p++) {2219unsigned char hash[20];2220char path[PATH_MAX];2221const char*ref, *it;22222223mksnpath(path,sizeof(path), *p, len, str);2224 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2225 hash, NULL);2226if(!ref)2227continue;2228if(reflog_exists(path))2229 it = path;2230else if(strcmp(ref, path) &&reflog_exists(ref))2231 it = ref;2232else2233continue;2234if(!logs_found++) {2235*log =xstrdup(it);2236hashcpy(sha1, hash);2237}2238if(!warn_ambiguous_refs)2239break;2240}2241free(last_branch);2242return logs_found;2243}22442245/*2246 * Locks a ref returning the lock on success and NULL on failure.2247 * On failure errno is set to something meaningful.2248 */2249static struct ref_lock *lock_ref_sha1_basic(const char*refname,2250const unsigned char*old_sha1,2251const struct string_list *skip,2252int flags,int*type_p)2253{2254char*ref_file;2255const char*orig_refname = refname;2256struct ref_lock *lock;2257int last_errno =0;2258int type, lflags;2259int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2260int resolve_flags =0;2261int attempts_remaining =3;22622263 lock =xcalloc(1,sizeof(struct ref_lock));2264 lock->lock_fd = -1;22652266if(mustexist)2267 resolve_flags |= RESOLVE_REF_READING;2268if(flags & REF_DELETING) {2269 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2270if(flags & REF_NODEREF)2271 resolve_flags |= RESOLVE_REF_NO_RECURSE;2272}22732274 refname =resolve_ref_unsafe(refname, resolve_flags,2275 lock->old_sha1, &type);2276if(!refname && errno == EISDIR) {2277/* we are trying to lock foo but we used to2278 * have foo/bar which now does not exist;2279 * it is normal for the empty directory 'foo'2280 * to remain.2281 */2282 ref_file =git_path("%s", orig_refname);2283if(remove_empty_directories(ref_file)) {2284 last_errno = errno;2285error("there are still refs under '%s'", orig_refname);2286goto error_return;2287}2288 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2289 lock->old_sha1, &type);2290}2291if(type_p)2292*type_p = type;2293if(!refname) {2294 last_errno = errno;2295error("unable to resolve reference%s:%s",2296 orig_refname,strerror(errno));2297goto error_return;2298}2299/*2300 * If the ref did not exist and we are creating it, make sure2301 * there is no existing packed ref whose name begins with our2302 * refname, nor a packed ref whose name is a proper prefix of2303 * our refname.2304 */2305if(is_null_sha1(lock->old_sha1) &&2306!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2307 last_errno = ENOTDIR;2308goto error_return;2309}23102311 lock->lk =xcalloc(1,sizeof(struct lock_file));23122313 lflags =0;2314if(flags & REF_NODEREF) {2315 refname = orig_refname;2316 lflags |= LOCK_NO_DEREF;2317}2318 lock->ref_name =xstrdup(refname);2319 lock->orig_ref_name =xstrdup(orig_refname);2320 ref_file =git_path("%s", refname);23212322 retry:2323switch(safe_create_leading_directories(ref_file)) {2324case SCLD_OK:2325break;/* success */2326case SCLD_VANISHED:2327if(--attempts_remaining >0)2328goto retry;2329/* fall through */2330default:2331 last_errno = errno;2332error("unable to create directory for%s", ref_file);2333goto error_return;2334}23352336 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2337if(lock->lock_fd <0) {2338 last_errno = errno;2339if(errno == ENOENT && --attempts_remaining >0)2340/*2341 * Maybe somebody just deleted one of the2342 * directories leading to ref_file. Try2343 * again:2344 */2345goto retry;2346else{2347struct strbuf err = STRBUF_INIT;2348unable_to_lock_message(ref_file, errno, &err);2349error("%s", err.buf);2350strbuf_release(&err);2351goto error_return;2352}2353}2354return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23552356 error_return:2357unlock_ref(lock);2358 errno = last_errno;2359return NULL;2360}23612362/*2363 * Write an entry to the packed-refs file for the specified refname.2364 * If peeled is non-NULL, write it as the entry's peeled value.2365 */2366static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2367unsigned char*peeled)2368{2369fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2370if(peeled)2371fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2372}23732374/*2375 * An each_ref_entry_fn that writes the entry to a packed-refs file.2376 */2377static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2378{2379enum peel_status peel_status =peel_entry(entry,0);23802381if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2382error("internal error:%sis not a valid packed reference!",2383 entry->name);2384write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2385 peel_status == PEEL_PEELED ?2386 entry->u.value.peeled : NULL);2387return0;2388}23892390/* This should return a meaningful errno on failure */2391intlock_packed_refs(int flags)2392{2393struct packed_ref_cache *packed_ref_cache;23942395if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2396return-1;2397/*2398 * Get the current packed-refs while holding the lock. If the2399 * packed-refs file has been modified since we last read it,2400 * this will automatically invalidate the cache and re-read2401 * the packed-refs file.2402 */2403 packed_ref_cache =get_packed_ref_cache(&ref_cache);2404 packed_ref_cache->lock = &packlock;2405/* Increment the reference count to prevent it from being freed: */2406acquire_packed_ref_cache(packed_ref_cache);2407return0;2408}24092410/*2411 * Commit the packed refs changes.2412 * On error we must make sure that errno contains a meaningful value.2413 */2414intcommit_packed_refs(void)2415{2416struct packed_ref_cache *packed_ref_cache =2417get_packed_ref_cache(&ref_cache);2418int error =0;2419int save_errno =0;2420FILE*out;24212422if(!packed_ref_cache->lock)2423die("internal error: packed-refs not locked");24242425 out =fdopen_lock_file(packed_ref_cache->lock,"w");2426if(!out)2427die_errno("unable to fdopen packed-refs descriptor");24282429fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2430do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24310, write_packed_entry_fn, out);24322433if(commit_lock_file(packed_ref_cache->lock)) {2434 save_errno = errno;2435 error = -1;2436}2437 packed_ref_cache->lock = NULL;2438release_packed_ref_cache(packed_ref_cache);2439 errno = save_errno;2440return error;2441}24422443voidrollback_packed_refs(void)2444{2445struct packed_ref_cache *packed_ref_cache =2446get_packed_ref_cache(&ref_cache);24472448if(!packed_ref_cache->lock)2449die("internal error: packed-refs not locked");2450rollback_lock_file(packed_ref_cache->lock);2451 packed_ref_cache->lock = NULL;2452release_packed_ref_cache(packed_ref_cache);2453clear_packed_ref_cache(&ref_cache);2454}24552456struct ref_to_prune {2457struct ref_to_prune *next;2458unsigned char sha1[20];2459char name[FLEX_ARRAY];2460};24612462struct pack_refs_cb_data {2463unsigned int flags;2464struct ref_dir *packed_refs;2465struct ref_to_prune *ref_to_prune;2466};24672468/*2469 * An each_ref_entry_fn that is run over loose references only. If2470 * the loose reference can be packed, add an entry in the packed ref2471 * cache. If the reference should be pruned, also add it to2472 * ref_to_prune in the pack_refs_cb_data.2473 */2474static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2475{2476struct pack_refs_cb_data *cb = cb_data;2477enum peel_status peel_status;2478struct ref_entry *packed_entry;2479int is_tag_ref =starts_with(entry->name,"refs/tags/");24802481/* ALWAYS pack tags */2482if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2483return0;24842485/* Do not pack symbolic or broken refs: */2486if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2487return0;24882489/* Add a packed ref cache entry equivalent to the loose entry. */2490 peel_status =peel_entry(entry,1);2491if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2492die("internal error peeling reference%s(%s)",2493 entry->name,sha1_to_hex(entry->u.value.sha1));2494 packed_entry =find_ref(cb->packed_refs, entry->name);2495if(packed_entry) {2496/* Overwrite existing packed entry with info from loose entry */2497 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2498hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2499}else{2500 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2501 REF_ISPACKED | REF_KNOWS_PEELED,0);2502add_ref(cb->packed_refs, packed_entry);2503}2504hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25052506/* Schedule the loose reference for pruning if requested. */2507if((cb->flags & PACK_REFS_PRUNE)) {2508int namelen =strlen(entry->name) +1;2509struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2510hashcpy(n->sha1, entry->u.value.sha1);2511strcpy(n->name, entry->name);2512 n->next = cb->ref_to_prune;2513 cb->ref_to_prune = n;2514}2515return0;2516}25172518/*2519 * Remove empty parents, but spare refs/ and immediate subdirs.2520 * Note: munges *name.2521 */2522static voidtry_remove_empty_parents(char*name)2523{2524char*p, *q;2525int i;2526 p = name;2527for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2528while(*p && *p !='/')2529 p++;2530/* tolerate duplicate slashes; see check_refname_format() */2531while(*p =='/')2532 p++;2533}2534for(q = p; *q; q++)2535;2536while(1) {2537while(q > p && *q !='/')2538 q--;2539while(q > p && *(q-1) =='/')2540 q--;2541if(q == p)2542break;2543*q ='\0';2544if(rmdir(git_path("%s", name)))2545break;2546}2547}25482549/* make sure nobody touched the ref, and unlink */2550static voidprune_ref(struct ref_to_prune *r)2551{2552struct ref_transaction *transaction;2553struct strbuf err = STRBUF_INIT;25542555if(check_refname_format(r->name,0))2556return;25572558 transaction =ref_transaction_begin(&err);2559if(!transaction ||2560ref_transaction_delete(transaction, r->name, r->sha1,2561 REF_ISPRUNING,1, NULL, &err) ||2562ref_transaction_commit(transaction, &err)) {2563ref_transaction_free(transaction);2564error("%s", err.buf);2565strbuf_release(&err);2566return;2567}2568ref_transaction_free(transaction);2569strbuf_release(&err);2570try_remove_empty_parents(r->name);2571}25722573static voidprune_refs(struct ref_to_prune *r)2574{2575while(r) {2576prune_ref(r);2577 r = r->next;2578}2579}25802581intpack_refs(unsigned int flags)2582{2583struct pack_refs_cb_data cbdata;25842585memset(&cbdata,0,sizeof(cbdata));2586 cbdata.flags = flags;25872588lock_packed_refs(LOCK_DIE_ON_ERROR);2589 cbdata.packed_refs =get_packed_refs(&ref_cache);25902591do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2592 pack_if_possible_fn, &cbdata);25932594if(commit_packed_refs())2595die_errno("unable to overwrite old ref-pack file");25962597prune_refs(cbdata.ref_to_prune);2598return0;2599}26002601/*2602 * If entry is no longer needed in packed-refs, add it to the string2603 * list pointed to by cb_data. Reasons for deleting entries:2604 *2605 * - Entry is broken.2606 * - Entry is overridden by a loose ref.2607 * - Entry does not point at a valid object.2608 *2609 * In the first and third cases, also emit an error message because these2610 * are indications of repository corruption.2611 */2612static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2613{2614struct string_list *refs_to_delete = cb_data;26152616if(entry->flag & REF_ISBROKEN) {2617/* This shouldn't happen to packed refs. */2618error("%sis broken!", entry->name);2619string_list_append(refs_to_delete, entry->name);2620return0;2621}2622if(!has_sha1_file(entry->u.value.sha1)) {2623unsigned char sha1[20];2624int flags;26252626if(read_ref_full(entry->name,0, sha1, &flags))2627/* We should at least have found the packed ref. */2628die("Internal error");2629if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2630/*2631 * This packed reference is overridden by a2632 * loose reference, so it is OK that its value2633 * is no longer valid; for example, it might2634 * refer to an object that has been garbage2635 * collected. For this purpose we don't even2636 * care whether the loose reference itself is2637 * invalid, broken, symbolic, etc. Silently2638 * remove the packed reference.2639 */2640string_list_append(refs_to_delete, entry->name);2641return0;2642}2643/*2644 * There is no overriding loose reference, so the fact2645 * that this reference doesn't refer to a valid object2646 * indicates some kind of repository corruption.2647 * Report the problem, then omit the reference from2648 * the output.2649 */2650error("%sdoes not point to a valid object!", entry->name);2651string_list_append(refs_to_delete, entry->name);2652return0;2653}26542655return0;2656}26572658intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2659{2660struct ref_dir *packed;2661struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2662struct string_list_item *refname, *ref_to_delete;2663int ret, needs_repacking =0, removed =0;26642665assert(err);26662667/* Look for a packed ref */2668for_each_string_list_item(refname, refnames) {2669if(get_packed_ref(refname->string)) {2670 needs_repacking =1;2671break;2672}2673}26742675/* Avoid locking if we have nothing to do */2676if(!needs_repacking)2677return0;/* no refname exists in packed refs */26782679if(lock_packed_refs(0)) {2680unable_to_lock_message(git_path("packed-refs"), errno, err);2681return-1;2682}2683 packed =get_packed_refs(&ref_cache);26842685/* Remove refnames from the cache */2686for_each_string_list_item(refname, refnames)2687if(remove_entry(packed, refname->string) != -1)2688 removed =1;2689if(!removed) {2690/*2691 * All packed entries disappeared while we were2692 * acquiring the lock.2693 */2694rollback_packed_refs();2695return0;2696}26972698/* Remove any other accumulated cruft */2699do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2700for_each_string_list_item(ref_to_delete, &refs_to_delete) {2701if(remove_entry(packed, ref_to_delete->string) == -1)2702die("internal error");2703}27042705/* Write what remains */2706 ret =commit_packed_refs();2707if(ret)2708strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2709strerror(errno));2710return ret;2711}27122713static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2714{2715assert(err);27162717if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2718/*2719 * loose. The loose file name is the same as the2720 * lockfile name, minus ".lock":2721 */2722char*loose_filename =get_locked_file_path(lock->lk);2723int res =unlink_or_msg(loose_filename, err);2724free(loose_filename);2725if(res)2726return1;2727}2728return0;2729}27302731intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2732{2733struct ref_transaction *transaction;2734struct strbuf err = STRBUF_INIT;27352736 transaction =ref_transaction_begin(&err);2737if(!transaction ||2738ref_transaction_delete(transaction, refname, sha1, delopt,2739 sha1 && !is_null_sha1(sha1), NULL, &err) ||2740ref_transaction_commit(transaction, &err)) {2741error("%s", err.buf);2742ref_transaction_free(transaction);2743strbuf_release(&err);2744return1;2745}2746ref_transaction_free(transaction);2747strbuf_release(&err);2748return0;2749}27502751/*2752 * People using contrib's git-new-workdir have .git/logs/refs ->2753 * /some/other/path/.git/logs/refs, and that may live on another device.2754 *2755 * IOW, to avoid cross device rename errors, the temporary renamed log must2756 * live into logs/refs.2757 */2758#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27592760static intrename_tmp_log(const char*newrefname)2761{2762int attempts_remaining =4;27632764 retry:2765switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2766case SCLD_OK:2767break;/* success */2768case SCLD_VANISHED:2769if(--attempts_remaining >0)2770goto retry;2771/* fall through */2772default:2773error("unable to create directory for%s", newrefname);2774return-1;2775}27762777if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2778if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2779/*2780 * rename(a, b) when b is an existing2781 * directory ought to result in ISDIR, but2782 * Solaris 5.8 gives ENOTDIR. Sheesh.2783 */2784if(remove_empty_directories(git_path("logs/%s", newrefname))) {2785error("Directory not empty: logs/%s", newrefname);2786return-1;2787}2788goto retry;2789}else if(errno == ENOENT && --attempts_remaining >0) {2790/*2791 * Maybe another process just deleted one of2792 * the directories in the path to newrefname.2793 * Try again from the beginning.2794 */2795goto retry;2796}else{2797error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2798 newrefname,strerror(errno));2799return-1;2800}2801}2802return0;2803}28042805static intrename_ref_available(const char*oldname,const char*newname)2806{2807struct string_list skip = STRING_LIST_INIT_NODUP;2808int ret;28092810string_list_insert(&skip, oldname);2811 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2812&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2813string_list_clear(&skip,0);2814return ret;2815}28162817static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2818const char*logmsg);28192820intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2821{2822unsigned char sha1[20], orig_sha1[20];2823int flag =0, logmoved =0;2824struct ref_lock *lock;2825struct stat loginfo;2826int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2827const char*symref = NULL;28282829if(log &&S_ISLNK(loginfo.st_mode))2830returnerror("reflog for%sis a symlink", oldrefname);28312832 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2833 orig_sha1, &flag);2834if(flag & REF_ISSYMREF)2835returnerror("refname%sis a symbolic ref, renaming it is not supported",2836 oldrefname);2837if(!symref)2838returnerror("refname%snot found", oldrefname);28392840if(!rename_ref_available(oldrefname, newrefname))2841return1;28422843if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2844returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2845 oldrefname,strerror(errno));28462847if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2848error("unable to delete old%s", oldrefname);2849goto rollback;2850}28512852if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2853delete_ref(newrefname, sha1, REF_NODEREF)) {2854if(errno==EISDIR) {2855if(remove_empty_directories(git_path("%s", newrefname))) {2856error("Directory not empty:%s", newrefname);2857goto rollback;2858}2859}else{2860error("unable to delete existing%s", newrefname);2861goto rollback;2862}2863}28642865if(log &&rename_tmp_log(newrefname))2866goto rollback;28672868 logmoved = log;28692870 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2871if(!lock) {2872error("unable to lock%sfor update", newrefname);2873goto rollback;2874}2875hashcpy(lock->old_sha1, orig_sha1);2876if(write_ref_sha1(lock, orig_sha1, logmsg)) {2877error("unable to write current sha1 into%s", newrefname);2878goto rollback;2879}28802881return0;28822883 rollback:2884 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2885if(!lock) {2886error("unable to lock%sfor rollback", oldrefname);2887goto rollbacklog;2888}28892890 flag = log_all_ref_updates;2891 log_all_ref_updates =0;2892if(write_ref_sha1(lock, orig_sha1, NULL))2893error("unable to write current sha1 into%s", oldrefname);2894 log_all_ref_updates = flag;28952896 rollbacklog:2897if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2898error("unable to restore logfile%sfrom%s:%s",2899 oldrefname, newrefname,strerror(errno));2900if(!logmoved && log &&2901rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2902error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2903 oldrefname,strerror(errno));29042905return1;2906}29072908static intclose_ref(struct ref_lock *lock)2909{2910if(close_lock_file(lock->lk))2911return-1;2912 lock->lock_fd = -1;2913return0;2914}29152916static intcommit_ref(struct ref_lock *lock)2917{2918if(commit_lock_file(lock->lk))2919return-1;2920 lock->lock_fd = -1;2921return0;2922}29232924/*2925 * copy the reflog message msg to buf, which has been allocated sufficiently2926 * large, while cleaning up the whitespaces. Especially, convert LF to space,2927 * because reflog file is one line per entry.2928 */2929static intcopy_msg(char*buf,const char*msg)2930{2931char*cp = buf;2932char c;2933int wasspace =1;29342935*cp++ ='\t';2936while((c = *msg++)) {2937if(wasspace &&isspace(c))2938continue;2939 wasspace =isspace(c);2940if(wasspace)2941 c =' ';2942*cp++ = c;2943}2944while(buf < cp &&isspace(cp[-1]))2945 cp--;2946*cp++ ='\n';2947return cp - buf;2948}29492950/* This function must set a meaningful errno on failure */2951intlog_ref_setup(const char*refname,char*logfile,int bufsize)2952{2953int logfd, oflags = O_APPEND | O_WRONLY;29542955git_snpath(logfile, bufsize,"logs/%s", refname);2956if(log_all_ref_updates &&2957(starts_with(refname,"refs/heads/") ||2958starts_with(refname,"refs/remotes/") ||2959starts_with(refname,"refs/notes/") ||2960!strcmp(refname,"HEAD"))) {2961if(safe_create_leading_directories(logfile) <0) {2962int save_errno = errno;2963error("unable to create directory for%s", logfile);2964 errno = save_errno;2965return-1;2966}2967 oflags |= O_CREAT;2968}29692970 logfd =open(logfile, oflags,0666);2971if(logfd <0) {2972if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2973return0;29742975if(errno == EISDIR) {2976if(remove_empty_directories(logfile)) {2977int save_errno = errno;2978error("There are still logs under '%s'",2979 logfile);2980 errno = save_errno;2981return-1;2982}2983 logfd =open(logfile, oflags,0666);2984}29852986if(logfd <0) {2987int save_errno = errno;2988error("Unable to append to%s:%s", logfile,2989strerror(errno));2990 errno = save_errno;2991return-1;2992}2993}29942995adjust_shared_perm(logfile);2996close(logfd);2997return0;2998}29993000static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3001const unsigned char*new_sha1,3002const char*committer,const char*msg)3003{3004int msglen, written;3005unsigned maxlen, len;3006char*logrec;30073008 msglen = msg ?strlen(msg) :0;3009 maxlen =strlen(committer) + msglen +100;3010 logrec =xmalloc(maxlen);3011 len =sprintf(logrec,"%s %s %s\n",3012sha1_to_hex(old_sha1),3013sha1_to_hex(new_sha1),3014 committer);3015if(msglen)3016 len +=copy_msg(logrec + len -1, msg) -1;30173018 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3019free(logrec);3020if(written != len)3021return-1;30223023return0;3024}30253026static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3027const unsigned char*new_sha1,const char*msg)3028{3029int logfd, result, oflags = O_APPEND | O_WRONLY;3030char log_file[PATH_MAX];30313032if(log_all_ref_updates <0)3033 log_all_ref_updates = !is_bare_repository();30343035 result =log_ref_setup(refname, log_file,sizeof(log_file));3036if(result)3037return result;30383039 logfd =open(log_file, oflags);3040if(logfd <0)3041return0;3042 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3043git_committer_info(0), msg);3044if(result) {3045int save_errno = errno;3046close(logfd);3047error("Unable to append to%s", log_file);3048 errno = save_errno;3049return-1;3050}3051if(close(logfd)) {3052int save_errno = errno;3053error("Unable to append to%s", log_file);3054 errno = save_errno;3055return-1;3056}3057return0;3058}30593060intis_branch(const char*refname)3061{3062return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3063}30643065/*3066 * Write sha1 into the ref specified by the lock. Make sure that errno3067 * is sane on error.3068 */3069static intwrite_ref_sha1(struct ref_lock *lock,3070const unsigned char*sha1,const char*logmsg)3071{3072static char term ='\n';3073struct object *o;30743075 o =parse_object(sha1);3076if(!o) {3077error("Trying to write ref%swith nonexistent object%s",3078 lock->ref_name,sha1_to_hex(sha1));3079unlock_ref(lock);3080 errno = EINVAL;3081return-1;3082}3083if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3084error("Trying to write non-commit object%sto branch%s",3085sha1_to_hex(sha1), lock->ref_name);3086unlock_ref(lock);3087 errno = EINVAL;3088return-1;3089}3090if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3091write_in_full(lock->lock_fd, &term,1) !=1||3092close_ref(lock) <0) {3093int save_errno = errno;3094error("Couldn't write%s", lock->lk->filename.buf);3095unlock_ref(lock);3096 errno = save_errno;3097return-1;3098}3099clear_loose_ref_cache(&ref_cache);3100if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3101(strcmp(lock->ref_name, lock->orig_ref_name) &&3102log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3103unlock_ref(lock);3104return-1;3105}3106if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3107/*3108 * Special hack: If a branch is updated directly and HEAD3109 * points to it (may happen on the remote side of a push3110 * for example) then logically the HEAD reflog should be3111 * updated too.3112 * A generic solution implies reverse symref information,3113 * but finding all symrefs pointing to the given branch3114 * would be rather costly for this rare event (the direct3115 * update of a branch) to be worth it. So let's cheat and3116 * check with HEAD only which should cover 99% of all usage3117 * scenarios (even 100% of the default ones).3118 */3119unsigned char head_sha1[20];3120int head_flag;3121const char*head_ref;3122 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3123 head_sha1, &head_flag);3124if(head_ref && (head_flag & REF_ISSYMREF) &&3125!strcmp(head_ref, lock->ref_name))3126log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3127}3128if(commit_ref(lock)) {3129error("Couldn't set%s", lock->ref_name);3130unlock_ref(lock);3131return-1;3132}3133unlock_ref(lock);3134return0;3135}31363137intcreate_symref(const char*ref_target,const char*refs_heads_master,3138const char*logmsg)3139{3140const char*lockpath;3141char ref[1000];3142int fd, len, written;3143char*git_HEAD =git_pathdup("%s", ref_target);3144unsigned char old_sha1[20], new_sha1[20];31453146if(logmsg &&read_ref(ref_target, old_sha1))3147hashclr(old_sha1);31483149if(safe_create_leading_directories(git_HEAD) <0)3150returnerror("unable to create directory for%s", git_HEAD);31513152#ifndef NO_SYMLINK_HEAD3153if(prefer_symlink_refs) {3154unlink(git_HEAD);3155if(!symlink(refs_heads_master, git_HEAD))3156goto done;3157fprintf(stderr,"no symlink - falling back to symbolic ref\n");3158}3159#endif31603161 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3162if(sizeof(ref) <= len) {3163error("refname too long:%s", refs_heads_master);3164goto error_free_return;3165}3166 lockpath =mkpath("%s.lock", git_HEAD);3167 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3168if(fd <0) {3169error("Unable to open%sfor writing", lockpath);3170goto error_free_return;3171}3172 written =write_in_full(fd, ref, len);3173if(close(fd) !=0|| written != len) {3174error("Unable to write to%s", lockpath);3175goto error_unlink_return;3176}3177if(rename(lockpath, git_HEAD) <0) {3178error("Unable to create%s", git_HEAD);3179goto error_unlink_return;3180}3181if(adjust_shared_perm(git_HEAD)) {3182error("Unable to fix permissions on%s", lockpath);3183 error_unlink_return:3184unlink_or_warn(lockpath);3185 error_free_return:3186free(git_HEAD);3187return-1;3188}31893190#ifndef NO_SYMLINK_HEAD3191 done:3192#endif3193if(logmsg && !read_ref(refs_heads_master, new_sha1))3194log_ref_write(ref_target, old_sha1, new_sha1, logmsg);31953196free(git_HEAD);3197return0;3198}31993200struct read_ref_at_cb {3201const char*refname;3202unsigned long at_time;3203int cnt;3204int reccnt;3205unsigned char*sha1;3206int found_it;32073208unsigned char osha1[20];3209unsigned char nsha1[20];3210int tz;3211unsigned long date;3212char**msg;3213unsigned long*cutoff_time;3214int*cutoff_tz;3215int*cutoff_cnt;3216};32173218static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3219const char*email,unsigned long timestamp,int tz,3220const char*message,void*cb_data)3221{3222struct read_ref_at_cb *cb = cb_data;32233224 cb->reccnt++;3225 cb->tz = tz;3226 cb->date = timestamp;32273228if(timestamp <= cb->at_time || cb->cnt ==0) {3229if(cb->msg)3230*cb->msg =xstrdup(message);3231if(cb->cutoff_time)3232*cb->cutoff_time = timestamp;3233if(cb->cutoff_tz)3234*cb->cutoff_tz = tz;3235if(cb->cutoff_cnt)3236*cb->cutoff_cnt = cb->reccnt -1;3237/*3238 * we have not yet updated cb->[n|o]sha1 so they still3239 * hold the values for the previous record.3240 */3241if(!is_null_sha1(cb->osha1)) {3242hashcpy(cb->sha1, nsha1);3243if(hashcmp(cb->osha1, nsha1))3244warning("Log for ref%shas gap after%s.",3245 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3246}3247else if(cb->date == cb->at_time)3248hashcpy(cb->sha1, nsha1);3249else if(hashcmp(nsha1, cb->sha1))3250warning("Log for ref%sunexpectedly ended on%s.",3251 cb->refname,show_date(cb->date, cb->tz,3252 DATE_RFC2822));3253hashcpy(cb->osha1, osha1);3254hashcpy(cb->nsha1, nsha1);3255 cb->found_it =1;3256return1;3257}3258hashcpy(cb->osha1, osha1);3259hashcpy(cb->nsha1, nsha1);3260if(cb->cnt >0)3261 cb->cnt--;3262return0;3263}32643265static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3266const char*email,unsigned long timestamp,3267int tz,const char*message,void*cb_data)3268{3269struct read_ref_at_cb *cb = cb_data;32703271if(cb->msg)3272*cb->msg =xstrdup(message);3273if(cb->cutoff_time)3274*cb->cutoff_time = timestamp;3275if(cb->cutoff_tz)3276*cb->cutoff_tz = tz;3277if(cb->cutoff_cnt)3278*cb->cutoff_cnt = cb->reccnt;3279hashcpy(cb->sha1, osha1);3280if(is_null_sha1(cb->sha1))3281hashcpy(cb->sha1, nsha1);3282/* We just want the first entry */3283return1;3284}32853286intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3287unsigned char*sha1,char**msg,3288unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3289{3290struct read_ref_at_cb cb;32913292memset(&cb,0,sizeof(cb));3293 cb.refname = refname;3294 cb.at_time = at_time;3295 cb.cnt = cnt;3296 cb.msg = msg;3297 cb.cutoff_time = cutoff_time;3298 cb.cutoff_tz = cutoff_tz;3299 cb.cutoff_cnt = cutoff_cnt;3300 cb.sha1 = sha1;33013302for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33033304if(!cb.reccnt) {3305if(flags & GET_SHA1_QUIETLY)3306exit(128);3307else3308die("Log for%sis empty.", refname);3309}3310if(cb.found_it)3311return0;33123313for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33143315return1;3316}33173318intreflog_exists(const char*refname)3319{3320struct stat st;33213322return!lstat(git_path("logs/%s", refname), &st) &&3323S_ISREG(st.st_mode);3324}33253326intdelete_reflog(const char*refname)3327{3328returnremove_path(git_path("logs/%s", refname));3329}33303331static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3332{3333unsigned char osha1[20], nsha1[20];3334char*email_end, *message;3335unsigned long timestamp;3336int tz;33373338/* old SP new SP name <email> SP time TAB msg LF */3339if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3340get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3341get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3342!(email_end =strchr(sb->buf +82,'>')) ||3343 email_end[1] !=' '||3344!(timestamp =strtoul(email_end +2, &message,10)) ||3345!message || message[0] !=' '||3346(message[1] !='+'&& message[1] !='-') ||3347!isdigit(message[2]) || !isdigit(message[3]) ||3348!isdigit(message[4]) || !isdigit(message[5]))3349return0;/* corrupt? */3350 email_end[1] ='\0';3351 tz =strtol(message +1, NULL,10);3352if(message[6] !='\t')3353 message +=6;3354else3355 message +=7;3356returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3357}33583359static char*find_beginning_of_line(char*bob,char*scan)3360{3361while(bob < scan && *(--scan) !='\n')3362;/* keep scanning backwards */3363/*3364 * Return either beginning of the buffer, or LF at the end of3365 * the previous line.3366 */3367return scan;3368}33693370intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3371{3372struct strbuf sb = STRBUF_INIT;3373FILE*logfp;3374long pos;3375int ret =0, at_tail =1;33763377 logfp =fopen(git_path("logs/%s", refname),"r");3378if(!logfp)3379return-1;33803381/* Jump to the end */3382if(fseek(logfp,0, SEEK_END) <0)3383returnerror("cannot seek back reflog for%s:%s",3384 refname,strerror(errno));3385 pos =ftell(logfp);3386while(!ret &&0< pos) {3387int cnt;3388size_t nread;3389char buf[BUFSIZ];3390char*endp, *scanp;33913392/* Fill next block from the end */3393 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3394if(fseek(logfp, pos - cnt, SEEK_SET))3395returnerror("cannot seek back reflog for%s:%s",3396 refname,strerror(errno));3397 nread =fread(buf, cnt,1, logfp);3398if(nread !=1)3399returnerror("cannot read%dbytes from reflog for%s:%s",3400 cnt, refname,strerror(errno));3401 pos -= cnt;34023403 scanp = endp = buf + cnt;3404if(at_tail && scanp[-1] =='\n')3405/* Looking at the final LF at the end of the file */3406 scanp--;3407 at_tail =0;34083409while(buf < scanp) {3410/*3411 * terminating LF of the previous line, or the beginning3412 * of the buffer.3413 */3414char*bp;34153416 bp =find_beginning_of_line(buf, scanp);34173418if(*bp =='\n') {3419/*3420 * The newline is the end of the previous line,3421 * so we know we have complete line starting3422 * at (bp + 1). Prefix it onto any prior data3423 * we collected for the line and process it.3424 */3425strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3426 scanp = bp;3427 endp = bp +1;3428 ret =show_one_reflog_ent(&sb, fn, cb_data);3429strbuf_reset(&sb);3430if(ret)3431break;3432}else if(!pos) {3433/*3434 * We are at the start of the buffer, and the3435 * start of the file; there is no previous3436 * line, and we have everything for this one.3437 * Process it, and we can end the loop.3438 */3439strbuf_splice(&sb,0,0, buf, endp - buf);3440 ret =show_one_reflog_ent(&sb, fn, cb_data);3441strbuf_reset(&sb);3442break;3443}34443445if(bp == buf) {3446/*3447 * We are at the start of the buffer, and there3448 * is more file to read backwards. Which means3449 * we are in the middle of a line. Note that we3450 * may get here even if *bp was a newline; that3451 * just means we are at the exact end of the3452 * previous line, rather than some spot in the3453 * middle.3454 *3455 * Save away what we have to be combined with3456 * the data from the next read.3457 */3458strbuf_splice(&sb,0,0, buf, endp - buf);3459break;3460}3461}34623463}3464if(!ret && sb.len)3465die("BUG: reverse reflog parser had leftover data");34663467fclose(logfp);3468strbuf_release(&sb);3469return ret;3470}34713472intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3473{3474FILE*logfp;3475struct strbuf sb = STRBUF_INIT;3476int ret =0;34773478 logfp =fopen(git_path("logs/%s", refname),"r");3479if(!logfp)3480return-1;34813482while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3483 ret =show_one_reflog_ent(&sb, fn, cb_data);3484fclose(logfp);3485strbuf_release(&sb);3486return ret;3487}3488/*3489 * Call fn for each reflog in the namespace indicated by name. name3490 * must be empty or end with '/'. Name will be used as a scratch3491 * space, but its contents will be restored before return.3492 */3493static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3494{3495DIR*d =opendir(git_path("logs/%s", name->buf));3496int retval =0;3497struct dirent *de;3498int oldlen = name->len;34993500if(!d)3501return name->len ? errno :0;35023503while((de =readdir(d)) != NULL) {3504struct stat st;35053506if(de->d_name[0] =='.')3507continue;3508if(ends_with(de->d_name,".lock"))3509continue;3510strbuf_addstr(name, de->d_name);3511if(stat(git_path("logs/%s", name->buf), &st) <0) {3512;/* silently ignore */3513}else{3514if(S_ISDIR(st.st_mode)) {3515strbuf_addch(name,'/');3516 retval =do_for_each_reflog(name, fn, cb_data);3517}else{3518unsigned char sha1[20];3519if(read_ref_full(name->buf,0, sha1, NULL))3520 retval =error("bad ref for%s", name->buf);3521else3522 retval =fn(name->buf, sha1,0, cb_data);3523}3524if(retval)3525break;3526}3527strbuf_setlen(name, oldlen);3528}3529closedir(d);3530return retval;3531}35323533intfor_each_reflog(each_ref_fn fn,void*cb_data)3534{3535int retval;3536struct strbuf name;3537strbuf_init(&name, PATH_MAX);3538 retval =do_for_each_reflog(&name, fn, cb_data);3539strbuf_release(&name);3540return retval;3541}35423543/**3544 * Information needed for a single ref update. Set new_sha1 to the3545 * new value or to zero to delete the ref. To check the old value3546 * while locking the ref, set have_old to 1 and set old_sha1 to the3547 * value or to zero to ensure the ref does not exist before update.3548 */3549struct ref_update {3550unsigned char new_sha1[20];3551unsigned char old_sha1[20];3552int flags;/* REF_NODEREF? */3553int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3554struct ref_lock *lock;3555int type;3556char*msg;3557const char refname[FLEX_ARRAY];3558};35593560/*3561 * Transaction states.3562 * OPEN: The transaction is in a valid state and can accept new updates.3563 * An OPEN transaction can be committed.3564 * CLOSED: A closed transaction is no longer active and no other operations3565 * than free can be used on it in this state.3566 * A transaction can either become closed by successfully committing3567 * an active transaction or if there is a failure while building3568 * the transaction thus rendering it failed/inactive.3569 */3570enum ref_transaction_state {3571 REF_TRANSACTION_OPEN =0,3572 REF_TRANSACTION_CLOSED =13573};35743575/*3576 * Data structure for holding a reference transaction, which can3577 * consist of checks and updates to multiple references, carried out3578 * as atomically as possible. This structure is opaque to callers.3579 */3580struct ref_transaction {3581struct ref_update **updates;3582size_t alloc;3583size_t nr;3584enum ref_transaction_state state;3585};35863587struct ref_transaction *ref_transaction_begin(struct strbuf *err)3588{3589assert(err);35903591returnxcalloc(1,sizeof(struct ref_transaction));3592}35933594voidref_transaction_free(struct ref_transaction *transaction)3595{3596int i;35973598if(!transaction)3599return;36003601for(i =0; i < transaction->nr; i++) {3602free(transaction->updates[i]->msg);3603free(transaction->updates[i]);3604}3605free(transaction->updates);3606free(transaction);3607}36083609static struct ref_update *add_update(struct ref_transaction *transaction,3610const char*refname)3611{3612size_t len =strlen(refname);3613struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36143615strcpy((char*)update->refname, refname);3616ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3617 transaction->updates[transaction->nr++] = update;3618return update;3619}36203621intref_transaction_update(struct ref_transaction *transaction,3622const char*refname,3623const unsigned char*new_sha1,3624const unsigned char*old_sha1,3625int flags,int have_old,const char*msg,3626struct strbuf *err)3627{3628struct ref_update *update;36293630assert(err);36313632if(transaction->state != REF_TRANSACTION_OPEN)3633die("BUG: update called for transaction that is not open");36343635if(have_old && !old_sha1)3636die("BUG: have_old is true but old_sha1 is NULL");36373638if(!is_null_sha1(new_sha1) &&3639check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3640strbuf_addf(err,"refusing to update ref with bad name%s",3641 refname);3642return-1;3643}36443645 update =add_update(transaction, refname);3646hashcpy(update->new_sha1, new_sha1);3647 update->flags = flags;3648 update->have_old = have_old;3649if(have_old)3650hashcpy(update->old_sha1, old_sha1);3651if(msg)3652 update->msg =xstrdup(msg);3653return0;3654}36553656intref_transaction_create(struct ref_transaction *transaction,3657const char*refname,3658const unsigned char*new_sha1,3659int flags,const char*msg,3660struct strbuf *err)3661{3662returnref_transaction_update(transaction, refname, new_sha1,3663 null_sha1, flags,1, msg, err);3664}36653666intref_transaction_delete(struct ref_transaction *transaction,3667const char*refname,3668const unsigned char*old_sha1,3669int flags,int have_old,const char*msg,3670struct strbuf *err)3671{3672returnref_transaction_update(transaction, refname, null_sha1,3673 old_sha1, flags, have_old, msg, err);3674}36753676intupdate_ref(const char*action,const char*refname,3677const unsigned char*sha1,const unsigned char*oldval,3678int flags,enum action_on_err onerr)3679{3680struct ref_transaction *t;3681struct strbuf err = STRBUF_INIT;36823683 t =ref_transaction_begin(&err);3684if(!t ||3685ref_transaction_update(t, refname, sha1, oldval, flags,3686!!oldval, action, &err) ||3687ref_transaction_commit(t, &err)) {3688const char*str ="update_ref failed for ref '%s':%s";36893690ref_transaction_free(t);3691switch(onerr) {3692case UPDATE_REFS_MSG_ON_ERR:3693error(str, refname, err.buf);3694break;3695case UPDATE_REFS_DIE_ON_ERR:3696die(str, refname, err.buf);3697break;3698case UPDATE_REFS_QUIET_ON_ERR:3699break;3700}3701strbuf_release(&err);3702return1;3703}3704strbuf_release(&err);3705ref_transaction_free(t);3706return0;3707}37083709static intref_update_compare(const void*r1,const void*r2)3710{3711const struct ref_update *const*u1 = r1;3712const struct ref_update *const*u2 = r2;3713returnstrcmp((*u1)->refname, (*u2)->refname);3714}37153716static intref_update_reject_duplicates(struct ref_update **updates,int n,3717struct strbuf *err)3718{3719int i;37203721assert(err);37223723for(i =1; i < n; i++)3724if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3725strbuf_addf(err,3726"Multiple updates for ref '%s' not allowed.",3727 updates[i]->refname);3728return1;3729}3730return0;3731}37323733intref_transaction_commit(struct ref_transaction *transaction,3734struct strbuf *err)3735{3736int ret =0, i;3737int n = transaction->nr;3738struct ref_update **updates = transaction->updates;3739struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3740struct string_list_item *ref_to_delete;37413742assert(err);37433744if(transaction->state != REF_TRANSACTION_OPEN)3745die("BUG: commit called for transaction that is not open");37463747if(!n) {3748 transaction->state = REF_TRANSACTION_CLOSED;3749return0;3750}37513752/* Copy, sort, and reject duplicate refs */3753qsort(updates, n,sizeof(*updates), ref_update_compare);3754if(ref_update_reject_duplicates(updates, n, err)) {3755 ret = TRANSACTION_GENERIC_ERROR;3756goto cleanup;3757}37583759/* Acquire all locks while verifying old values */3760for(i =0; i < n; i++) {3761struct ref_update *update = updates[i];3762int flags = update->flags;37633764if(is_null_sha1(update->new_sha1))3765 flags |= REF_DELETING;3766 update->lock =lock_ref_sha1_basic(update->refname,3767(update->have_old ?3768 update->old_sha1 :3769 NULL),3770 NULL,3771 flags,3772&update->type);3773if(!update->lock) {3774 ret = (errno == ENOTDIR)3775? TRANSACTION_NAME_CONFLICT3776: TRANSACTION_GENERIC_ERROR;3777strbuf_addf(err,"Cannot lock the ref '%s'.",3778 update->refname);3779goto cleanup;3780}3781}37823783/* Perform updates first so live commits remain referenced */3784for(i =0; i < n; i++) {3785struct ref_update *update = updates[i];37863787if(!is_null_sha1(update->new_sha1)) {3788int overwriting_symref = ((update->type & REF_ISSYMREF) &&3789(update->flags & REF_NODEREF));37903791if(!overwriting_symref3792&& !hashcmp(update->lock->old_sha1, update->new_sha1)) {3793/*3794 * The reference already has the desired3795 * value, so we don't need to write it.3796 */3797unlock_ref(update->lock);3798 update->lock = NULL;3799}else if(write_ref_sha1(update->lock, update->new_sha1,3800 update->msg)) {3801 update->lock = NULL;/* freed by write_ref_sha1 */3802strbuf_addf(err,"Cannot update the ref '%s'.",3803 update->refname);3804 ret = TRANSACTION_GENERIC_ERROR;3805goto cleanup;3806}else{3807/* freed by write_ref_sha1(): */3808 update->lock = NULL;3809}3810}3811}38123813/* Perform deletes now that updates are safely completed */3814for(i =0; i < n; i++) {3815struct ref_update *update = updates[i];38163817if(update->lock) {3818if(delete_ref_loose(update->lock, update->type, err)) {3819 ret = TRANSACTION_GENERIC_ERROR;3820goto cleanup;3821}38223823if(!(update->flags & REF_ISPRUNING))3824string_list_append(&refs_to_delete,3825 update->lock->ref_name);3826}3827}38283829if(repack_without_refs(&refs_to_delete, err)) {3830 ret = TRANSACTION_GENERIC_ERROR;3831goto cleanup;3832}3833for_each_string_list_item(ref_to_delete, &refs_to_delete)3834unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3835clear_loose_ref_cache(&ref_cache);38363837cleanup:3838 transaction->state = REF_TRANSACTION_CLOSED;38393840for(i =0; i < n; i++)3841if(updates[i]->lock)3842unlock_ref(updates[i]->lock);3843string_list_clear(&refs_to_delete,0);3844return ret;3845}38463847char*shorten_unambiguous_ref(const char*refname,int strict)3848{3849int i;3850static char**scanf_fmts;3851static int nr_rules;3852char*short_name;38533854if(!nr_rules) {3855/*3856 * Pre-generate scanf formats from ref_rev_parse_rules[].3857 * Generate a format suitable for scanf from a3858 * ref_rev_parse_rules rule by interpolating "%s" at the3859 * location of the "%.*s".3860 */3861size_t total_len =0;3862size_t offset =0;38633864/* the rule list is NULL terminated, count them first */3865for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3866/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3867 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38683869 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38703871 offset =0;3872for(i =0; i < nr_rules; i++) {3873assert(offset < total_len);3874 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3875 offset +=snprintf(scanf_fmts[i], total_len - offset,3876 ref_rev_parse_rules[i],2,"%s") +1;3877}3878}38793880/* bail out if there are no rules */3881if(!nr_rules)3882returnxstrdup(refname);38833884/* buffer for scanf result, at most refname must fit */3885 short_name =xstrdup(refname);38863887/* skip first rule, it will always match */3888for(i = nr_rules -1; i >0; --i) {3889int j;3890int rules_to_fail = i;3891int short_name_len;38923893if(1!=sscanf(refname, scanf_fmts[i], short_name))3894continue;38953896 short_name_len =strlen(short_name);38973898/*3899 * in strict mode, all (except the matched one) rules3900 * must fail to resolve to a valid non-ambiguous ref3901 */3902if(strict)3903 rules_to_fail = nr_rules;39043905/*3906 * check if the short name resolves to a valid ref,3907 * but use only rules prior to the matched one3908 */3909for(j =0; j < rules_to_fail; j++) {3910const char*rule = ref_rev_parse_rules[j];3911char refname[PATH_MAX];39123913/* skip matched rule */3914if(i == j)3915continue;39163917/*3918 * the short name is ambiguous, if it resolves3919 * (with this previous rule) to a valid ref3920 * read_ref() returns 0 on success3921 */3922mksnpath(refname,sizeof(refname),3923 rule, short_name_len, short_name);3924if(ref_exists(refname))3925break;3926}39273928/*3929 * short name is non-ambiguous if all previous rules3930 * haven't resolved to a valid ref3931 */3932if(j == rules_to_fail)3933return short_name;3934}39353936free(short_name);3937returnxstrdup(refname);3938}39393940static struct string_list *hide_refs;39413942intparse_hide_refs_config(const char*var,const char*value,const char*section)3943{3944if(!strcmp("transfer.hiderefs", var) ||3945/* NEEDSWORK: use parse_config_key() once both are merged */3946(starts_with(var, section) && var[strlen(section)] =='.'&&3947!strcmp(var +strlen(section),".hiderefs"))) {3948char*ref;3949int len;39503951if(!value)3952returnconfig_error_nonbool(var);3953 ref =xstrdup(value);3954 len =strlen(ref);3955while(len && ref[len -1] =='/')3956 ref[--len] ='\0';3957if(!hide_refs) {3958 hide_refs =xcalloc(1,sizeof(*hide_refs));3959 hide_refs->strdup_strings =1;3960}3961string_list_append(hide_refs, ref);3962}3963return0;3964}39653966intref_is_hidden(const char*refname)3967{3968struct string_list_item *item;39693970if(!hide_refs)3971return0;3972for_each_string_list_item(item, hide_refs) {3973int len;3974if(!starts_with(refname, item->string))3975continue;3976 len =strlen(item->string);3977if(!refname[len] || refname[len] =='/')3978return1;3979}3980return0;3981}39823983struct expire_reflog_cb {3984unsigned int flags;3985 reflog_expiry_should_prune_fn *should_prune_fn;3986void*policy_cb;3987FILE*newlog;3988unsigned char last_kept_sha1[20];3989};39903991static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3992const char*email,unsigned long timestamp,int tz,3993const char*message,void*cb_data)3994{3995struct expire_reflog_cb *cb = cb_data;3996struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;39973998if(cb->flags & EXPIRE_REFLOGS_REWRITE)3999 osha1 = cb->last_kept_sha1;40004001if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4002 message, policy_cb)) {4003if(!cb->newlog)4004printf("would prune%s", message);4005else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4006printf("prune%s", message);4007}else{4008if(cb->newlog) {4009fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4010sha1_to_hex(osha1),sha1_to_hex(nsha1),4011 email, timestamp, tz, message);4012hashcpy(cb->last_kept_sha1, nsha1);4013}4014if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4015printf("keep%s", message);4016}4017return0;4018}40194020intreflog_expire(const char*refname,const unsigned char*sha1,4021unsigned int flags,4022 reflog_expiry_prepare_fn prepare_fn,4023 reflog_expiry_should_prune_fn should_prune_fn,4024 reflog_expiry_cleanup_fn cleanup_fn,4025void*policy_cb_data)4026{4027static struct lock_file reflog_lock;4028struct expire_reflog_cb cb;4029struct ref_lock *lock;4030char*log_file;4031int status =0;40324033memset(&cb,0,sizeof(cb));4034 cb.flags = flags;4035 cb.policy_cb = policy_cb_data;4036 cb.should_prune_fn = should_prune_fn;40374038/*4039 * The reflog file is locked by holding the lock on the4040 * reference itself, plus we might need to update the4041 * reference if --updateref was specified:4042 */4043 lock =lock_ref_sha1_basic(refname, sha1, NULL,0, NULL);4044if(!lock)4045returnerror("cannot lock ref '%s'", refname);4046if(!reflog_exists(refname)) {4047unlock_ref(lock);4048return0;4049}40504051 log_file =git_pathdup("logs/%s", refname);4052if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4053/*4054 * Even though holding $GIT_DIR/logs/$reflog.lock has4055 * no locking implications, we use the lock_file4056 * machinery here anyway because it does a lot of the4057 * work we need, including cleaning up if the program4058 * exits unexpectedly.4059 */4060if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4061struct strbuf err = STRBUF_INIT;4062unable_to_lock_message(log_file, errno, &err);4063error("%s", err.buf);4064strbuf_release(&err);4065goto failure;4066}4067 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4068if(!cb.newlog) {4069error("cannot fdopen%s(%s)",4070 reflog_lock.filename.buf,strerror(errno));4071goto failure;4072}4073}40744075(*prepare_fn)(refname, sha1, cb.policy_cb);4076for_each_reflog_ent(refname, expire_reflog_ent, &cb);4077(*cleanup_fn)(cb.policy_cb);40784079if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4080if(close_lock_file(&reflog_lock)) {4081 status |=error("couldn't write%s:%s", log_file,4082strerror(errno));4083}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&4084(write_in_full(lock->lock_fd,4085sha1_to_hex(cb.last_kept_sha1),40) !=40||4086write_str_in_full(lock->lock_fd,"\n") !=1||4087close_ref(lock) <0)) {4088 status |=error("couldn't write%s",4089 lock->lk->filename.buf);4090rollback_lock_file(&reflog_lock);4091}else if(commit_lock_file(&reflog_lock)) {4092 status |=error("unable to commit reflog '%s' (%s)",4093 log_file,strerror(errno));4094}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&commit_ref(lock)) {4095 status |=error("couldn't set%s", lock->ref_name);4096}4097}4098free(log_file);4099unlock_ref(lock);4100return status;41014102 failure:4103rollback_lock_file(&reflog_lock);4104free(log_file);4105unlock_ref(lock);4106return-1;4107}