1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9struct ref_lock { 10char*ref_name; 11char*orig_ref_name; 12struct lock_file *lk; 13unsigned char old_sha1[20]; 14int lock_fd; 15int force_write; 16}; 17 18/* 19 * How to handle various characters in refnames: 20 * 0: An acceptable character for refs 21 * 1: End-of-component 22 * 2: ., look for a preceding . to reject .. in refs 23 * 3: {, look for a preceding @ to reject @{ in refs 24 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Used as a flag to ref_transaction_delete when a loose ref is being 39 * pruned. 40 */ 41#define REF_ISPRUNING 0x0100 42/* 43 * Try to read one refname component from the front of refname. 44 * Return the length of the component found, or -1 if the component is 45 * not legal. It is legal if it is something reasonable to have under 46 * ".git/refs/"; We do not like it if: 47 * 48 * - any path component of it begins with ".", or 49 * - it has double dots "..", or 50 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 51 * - it ends with a "/". 52 * - it ends with ".lock" 53 * - it contains a "\" (backslash) 54 */ 55static intcheck_refname_component(const char*refname,int flags) 56{ 57const char*cp; 58char last ='\0'; 59 60for(cp = refname; ; cp++) { 61int ch = *cp &255; 62unsigned char disp = refname_disposition[ch]; 63switch(disp) { 64case1: 65goto out; 66case2: 67if(last =='.') 68return-1;/* Refname contains "..". */ 69break; 70case3: 71if(last =='@') 72return-1;/* Refname contains "@{". */ 73break; 74case4: 75return-1; 76} 77 last = ch; 78} 79out: 80if(cp == refname) 81return0;/* Component has zero length. */ 82if(refname[0] =='.') 83return-1;/* Component starts with '.'. */ 84if(cp - refname >= LOCK_SUFFIX_LEN && 85!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 86return-1;/* Refname ends with ".lock". */ 87return cp - refname; 88} 89 90intcheck_refname_format(const char*refname,int flags) 91{ 92int component_len, component_count =0; 93 94if(!strcmp(refname,"@")) 95/* Refname is a single character '@'. */ 96return-1; 97 98while(1) { 99/* We are at the start of a path component. */ 100 component_len =check_refname_component(refname, flags); 101if(component_len <=0) { 102if((flags & REFNAME_REFSPEC_PATTERN) && 103 refname[0] =='*'&& 104(refname[1] =='\0'|| refname[1] =='/')) { 105/* Accept one wildcard as a full refname component. */ 106 flags &= ~REFNAME_REFSPEC_PATTERN; 107 component_len =1; 108}else{ 109return-1; 110} 111} 112 component_count++; 113if(refname[component_len] =='\0') 114break; 115/* Skip to next component. */ 116 refname += component_len +1; 117} 118 119if(refname[component_len -1] =='.') 120return-1;/* Refname ends with '.'. */ 121if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 122return-1;/* Refname has only one component. */ 123return0; 124} 125 126struct ref_entry; 127 128/* 129 * Information used (along with the information in ref_entry) to 130 * describe a single cached reference. This data structure only 131 * occurs embedded in a union in struct ref_entry, and only when 132 * (ref_entry->flag & REF_DIR) is zero. 133 */ 134struct ref_value { 135/* 136 * The name of the object to which this reference resolves 137 * (which may be a tag object). If REF_ISBROKEN, this is 138 * null. If REF_ISSYMREF, then this is the name of the object 139 * referred to by the last reference in the symlink chain. 140 */ 141unsigned char sha1[20]; 142 143/* 144 * If REF_KNOWS_PEELED, then this field holds the peeled value 145 * of this reference, or null if the reference is known not to 146 * be peelable. See the documentation for peel_ref() for an 147 * exact definition of "peelable". 148 */ 149unsigned char peeled[20]; 150}; 151 152struct ref_cache; 153 154/* 155 * Information used (along with the information in ref_entry) to 156 * describe a level in the hierarchy of references. This data 157 * structure only occurs embedded in a union in struct ref_entry, and 158 * only when (ref_entry.flag & REF_DIR) is set. In that case, 159 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 160 * in the directory have already been read: 161 * 162 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 163 * or packed references, already read. 164 * 165 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 166 * references that hasn't been read yet (nor has any of its 167 * subdirectories). 168 * 169 * Entries within a directory are stored within a growable array of 170 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 171 * sorted are sorted by their component name in strcmp() order and the 172 * remaining entries are unsorted. 173 * 174 * Loose references are read lazily, one directory at a time. When a 175 * directory of loose references is read, then all of the references 176 * in that directory are stored, and REF_INCOMPLETE stubs are created 177 * for any subdirectories, but the subdirectories themselves are not 178 * read. The reading is triggered by get_ref_dir(). 179 */ 180struct ref_dir { 181int nr, alloc; 182 183/* 184 * Entries with index 0 <= i < sorted are sorted by name. New 185 * entries are appended to the list unsorted, and are sorted 186 * only when required; thus we avoid the need to sort the list 187 * after the addition of every reference. 188 */ 189int sorted; 190 191/* A pointer to the ref_cache that contains this ref_dir. */ 192struct ref_cache *ref_cache; 193 194struct ref_entry **entries; 195}; 196 197/* 198 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 199 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 200 * public values; see refs.h. 201 */ 202 203/* 204 * The field ref_entry->u.value.peeled of this value entry contains 205 * the correct peeled value for the reference, which might be 206 * null_sha1 if the reference is not a tag or if it is broken. 207 */ 208#define REF_KNOWS_PEELED 0x10 209 210/* ref_entry represents a directory of references */ 211#define REF_DIR 0x20 212 213/* 214 * Entry has not yet been read from disk (used only for REF_DIR 215 * entries representing loose references) 216 */ 217#define REF_INCOMPLETE 0x40 218 219/* 220 * A ref_entry represents either a reference or a "subdirectory" of 221 * references. 222 * 223 * Each directory in the reference namespace is represented by a 224 * ref_entry with (flags & REF_DIR) set and containing a subdir member 225 * that holds the entries in that directory that have been read so 226 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 227 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 228 * used for loose reference directories. 229 * 230 * References are represented by a ref_entry with (flags & REF_DIR) 231 * unset and a value member that describes the reference's value. The 232 * flag member is at the ref_entry level, but it is also needed to 233 * interpret the contents of the value field (in other words, a 234 * ref_value object is not very much use without the enclosing 235 * ref_entry). 236 * 237 * Reference names cannot end with slash and directories' names are 238 * always stored with a trailing slash (except for the top-level 239 * directory, which is always denoted by ""). This has two nice 240 * consequences: (1) when the entries in each subdir are sorted 241 * lexicographically by name (as they usually are), the references in 242 * a whole tree can be generated in lexicographic order by traversing 243 * the tree in left-to-right, depth-first order; (2) the names of 244 * references and subdirectories cannot conflict, and therefore the 245 * presence of an empty subdirectory does not block the creation of a 246 * similarly-named reference. (The fact that reference names with the 247 * same leading components can conflict *with each other* is a 248 * separate issue that is regulated by is_refname_available().) 249 * 250 * Please note that the name field contains the fully-qualified 251 * reference (or subdirectory) name. Space could be saved by only 252 * storing the relative names. But that would require the full names 253 * to be generated on the fly when iterating in do_for_each_ref(), and 254 * would break callback functions, who have always been able to assume 255 * that the name strings that they are passed will not be freed during 256 * the iteration. 257 */ 258struct ref_entry { 259unsigned char flag;/* ISSYMREF? ISPACKED? */ 260union{ 261struct ref_value value;/* if not (flags&REF_DIR) */ 262struct ref_dir subdir;/* if (flags&REF_DIR) */ 263} u; 264/* 265 * The full name of the reference (e.g., "refs/heads/master") 266 * or the full name of the directory with a trailing slash 267 * (e.g., "refs/heads/"): 268 */ 269char name[FLEX_ARRAY]; 270}; 271 272static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 273 274static struct ref_dir *get_ref_dir(struct ref_entry *entry) 275{ 276struct ref_dir *dir; 277assert(entry->flag & REF_DIR); 278 dir = &entry->u.subdir; 279if(entry->flag & REF_INCOMPLETE) { 280read_loose_refs(entry->name, dir); 281 entry->flag &= ~REF_INCOMPLETE; 282} 283return dir; 284} 285 286/* 287 * Check if a refname is safe. 288 * For refs that start with "refs/" we consider it safe as long they do 289 * not try to resolve to outside of refs/. 290 * 291 * For all other refs we only consider them safe iff they only contain 292 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 293 * "config"). 294 */ 295static intrefname_is_safe(const char*refname) 296{ 297if(starts_with(refname,"refs/")) { 298char*buf; 299int result; 300 301 buf =xmalloc(strlen(refname) +1); 302/* 303 * Does the refname try to escape refs/? 304 * For example: refs/foo/../bar is safe but refs/foo/../../bar 305 * is not. 306 */ 307 result = !normalize_path_copy(buf, refname +strlen("refs/")); 308free(buf); 309return result; 310} 311while(*refname) { 312if(!isupper(*refname) && *refname !='_') 313return0; 314 refname++; 315} 316return1; 317} 318 319static struct ref_entry *create_ref_entry(const char*refname, 320const unsigned char*sha1,int flag, 321int check_name) 322{ 323int len; 324struct ref_entry *ref; 325 326if(check_name && 327check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 328die("Reference has invalid format: '%s'", refname); 329if(!check_name && !refname_is_safe(refname)) 330die("Reference has invalid name: '%s'", refname); 331 len =strlen(refname) +1; 332 ref =xmalloc(sizeof(struct ref_entry) + len); 333hashcpy(ref->u.value.sha1, sha1); 334hashclr(ref->u.value.peeled); 335memcpy(ref->name, refname, len); 336 ref->flag = flag; 337return ref; 338} 339 340static voidclear_ref_dir(struct ref_dir *dir); 341 342static voidfree_ref_entry(struct ref_entry *entry) 343{ 344if(entry->flag & REF_DIR) { 345/* 346 * Do not use get_ref_dir() here, as that might 347 * trigger the reading of loose refs. 348 */ 349clear_ref_dir(&entry->u.subdir); 350} 351free(entry); 352} 353 354/* 355 * Add a ref_entry to the end of dir (unsorted). Entry is always 356 * stored directly in dir; no recursion into subdirectories is 357 * done. 358 */ 359static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 360{ 361ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 362 dir->entries[dir->nr++] = entry; 363/* optimize for the case that entries are added in order */ 364if(dir->nr ==1|| 365(dir->nr == dir->sorted +1&& 366strcmp(dir->entries[dir->nr -2]->name, 367 dir->entries[dir->nr -1]->name) <0)) 368 dir->sorted = dir->nr; 369} 370 371/* 372 * Clear and free all entries in dir, recursively. 373 */ 374static voidclear_ref_dir(struct ref_dir *dir) 375{ 376int i; 377for(i =0; i < dir->nr; i++) 378free_ref_entry(dir->entries[i]); 379free(dir->entries); 380 dir->sorted = dir->nr = dir->alloc =0; 381 dir->entries = NULL; 382} 383 384/* 385 * Create a struct ref_entry object for the specified dirname. 386 * dirname is the name of the directory with a trailing slash (e.g., 387 * "refs/heads/") or "" for the top-level directory. 388 */ 389static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 390const char*dirname,size_t len, 391int incomplete) 392{ 393struct ref_entry *direntry; 394 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 395memcpy(direntry->name, dirname, len); 396 direntry->name[len] ='\0'; 397 direntry->u.subdir.ref_cache = ref_cache; 398 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 399return direntry; 400} 401 402static intref_entry_cmp(const void*a,const void*b) 403{ 404struct ref_entry *one = *(struct ref_entry **)a; 405struct ref_entry *two = *(struct ref_entry **)b; 406returnstrcmp(one->name, two->name); 407} 408 409static voidsort_ref_dir(struct ref_dir *dir); 410 411struct string_slice { 412size_t len; 413const char*str; 414}; 415 416static intref_entry_cmp_sslice(const void*key_,const void*ent_) 417{ 418const struct string_slice *key = key_; 419const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 420int cmp =strncmp(key->str, ent->name, key->len); 421if(cmp) 422return cmp; 423return'\0'- (unsigned char)ent->name[key->len]; 424} 425 426/* 427 * Return the index of the entry with the given refname from the 428 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 429 * no such entry is found. dir must already be complete. 430 */ 431static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 432{ 433struct ref_entry **r; 434struct string_slice key; 435 436if(refname == NULL || !dir->nr) 437return-1; 438 439sort_ref_dir(dir); 440 key.len = len; 441 key.str = refname; 442 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 443 ref_entry_cmp_sslice); 444 445if(r == NULL) 446return-1; 447 448return r - dir->entries; 449} 450 451/* 452 * Search for a directory entry directly within dir (without 453 * recursing). Sort dir if necessary. subdirname must be a directory 454 * name (i.e., end in '/'). If mkdir is set, then create the 455 * directory if it is missing; otherwise, return NULL if the desired 456 * directory cannot be found. dir must already be complete. 457 */ 458static struct ref_dir *search_for_subdir(struct ref_dir *dir, 459const char*subdirname,size_t len, 460int mkdir) 461{ 462int entry_index =search_ref_dir(dir, subdirname, len); 463struct ref_entry *entry; 464if(entry_index == -1) { 465if(!mkdir) 466return NULL; 467/* 468 * Since dir is complete, the absence of a subdir 469 * means that the subdir really doesn't exist; 470 * therefore, create an empty record for it but mark 471 * the record complete. 472 */ 473 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 474add_entry_to_dir(dir, entry); 475}else{ 476 entry = dir->entries[entry_index]; 477} 478returnget_ref_dir(entry); 479} 480 481/* 482 * If refname is a reference name, find the ref_dir within the dir 483 * tree that should hold refname. If refname is a directory name 484 * (i.e., ends in '/'), then return that ref_dir itself. dir must 485 * represent the top-level directory and must already be complete. 486 * Sort ref_dirs and recurse into subdirectories as necessary. If 487 * mkdir is set, then create any missing directories; otherwise, 488 * return NULL if the desired directory cannot be found. 489 */ 490static struct ref_dir *find_containing_dir(struct ref_dir *dir, 491const char*refname,int mkdir) 492{ 493const char*slash; 494for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 495size_t dirnamelen = slash - refname +1; 496struct ref_dir *subdir; 497 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 498if(!subdir) { 499 dir = NULL; 500break; 501} 502 dir = subdir; 503} 504 505return dir; 506} 507 508/* 509 * Find the value entry with the given name in dir, sorting ref_dirs 510 * and recursing into subdirectories as necessary. If the name is not 511 * found or it corresponds to a directory entry, return NULL. 512 */ 513static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 514{ 515int entry_index; 516struct ref_entry *entry; 517 dir =find_containing_dir(dir, refname,0); 518if(!dir) 519return NULL; 520 entry_index =search_ref_dir(dir, refname,strlen(refname)); 521if(entry_index == -1) 522return NULL; 523 entry = dir->entries[entry_index]; 524return(entry->flag & REF_DIR) ? NULL : entry; 525} 526 527/* 528 * Remove the entry with the given name from dir, recursing into 529 * subdirectories as necessary. If refname is the name of a directory 530 * (i.e., ends with '/'), then remove the directory and its contents. 531 * If the removal was successful, return the number of entries 532 * remaining in the directory entry that contained the deleted entry. 533 * If the name was not found, return -1. Please note that this 534 * function only deletes the entry from the cache; it does not delete 535 * it from the filesystem or ensure that other cache entries (which 536 * might be symbolic references to the removed entry) are updated. 537 * Nor does it remove any containing dir entries that might be made 538 * empty by the removal. dir must represent the top-level directory 539 * and must already be complete. 540 */ 541static intremove_entry(struct ref_dir *dir,const char*refname) 542{ 543int refname_len =strlen(refname); 544int entry_index; 545struct ref_entry *entry; 546int is_dir = refname[refname_len -1] =='/'; 547if(is_dir) { 548/* 549 * refname represents a reference directory. Remove 550 * the trailing slash; otherwise we will get the 551 * directory *representing* refname rather than the 552 * one *containing* it. 553 */ 554char*dirname =xmemdupz(refname, refname_len -1); 555 dir =find_containing_dir(dir, dirname,0); 556free(dirname); 557}else{ 558 dir =find_containing_dir(dir, refname,0); 559} 560if(!dir) 561return-1; 562 entry_index =search_ref_dir(dir, refname, refname_len); 563if(entry_index == -1) 564return-1; 565 entry = dir->entries[entry_index]; 566 567memmove(&dir->entries[entry_index], 568&dir->entries[entry_index +1], 569(dir->nr - entry_index -1) *sizeof(*dir->entries) 570); 571 dir->nr--; 572if(dir->sorted > entry_index) 573 dir->sorted--; 574free_ref_entry(entry); 575return dir->nr; 576} 577 578/* 579 * Add a ref_entry to the ref_dir (unsorted), recursing into 580 * subdirectories as necessary. dir must represent the top-level 581 * directory. Return 0 on success. 582 */ 583static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 584{ 585 dir =find_containing_dir(dir, ref->name,1); 586if(!dir) 587return-1; 588add_entry_to_dir(dir, ref); 589return0; 590} 591 592/* 593 * Emit a warning and return true iff ref1 and ref2 have the same name 594 * and the same sha1. Die if they have the same name but different 595 * sha1s. 596 */ 597static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 598{ 599if(strcmp(ref1->name, ref2->name)) 600return0; 601 602/* Duplicate name; make sure that they don't conflict: */ 603 604if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 605/* This is impossible by construction */ 606die("Reference directory conflict:%s", ref1->name); 607 608if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 609die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 610 611warning("Duplicated ref:%s", ref1->name); 612return1; 613} 614 615/* 616 * Sort the entries in dir non-recursively (if they are not already 617 * sorted) and remove any duplicate entries. 618 */ 619static voidsort_ref_dir(struct ref_dir *dir) 620{ 621int i, j; 622struct ref_entry *last = NULL; 623 624/* 625 * This check also prevents passing a zero-length array to qsort(), 626 * which is a problem on some platforms. 627 */ 628if(dir->sorted == dir->nr) 629return; 630 631qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 632 633/* Remove any duplicates: */ 634for(i =0, j =0; j < dir->nr; j++) { 635struct ref_entry *entry = dir->entries[j]; 636if(last &&is_dup_ref(last, entry)) 637free_ref_entry(entry); 638else 639 last = dir->entries[i++] = entry; 640} 641 dir->sorted = dir->nr = i; 642} 643 644/* Include broken references in a do_for_each_ref*() iteration: */ 645#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 646 647/* 648 * Return true iff the reference described by entry can be resolved to 649 * an object in the database. Emit a warning if the referred-to 650 * object does not exist. 651 */ 652static intref_resolves_to_object(struct ref_entry *entry) 653{ 654if(entry->flag & REF_ISBROKEN) 655return0; 656if(!has_sha1_file(entry->u.value.sha1)) { 657error("%sdoes not point to a valid object!", entry->name); 658return0; 659} 660return1; 661} 662 663/* 664 * current_ref is a performance hack: when iterating over references 665 * using the for_each_ref*() functions, current_ref is set to the 666 * current reference's entry before calling the callback function. If 667 * the callback function calls peel_ref(), then peel_ref() first 668 * checks whether the reference to be peeled is the current reference 669 * (it usually is) and if so, returns that reference's peeled version 670 * if it is available. This avoids a refname lookup in a common case. 671 */ 672static struct ref_entry *current_ref; 673 674typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 675 676struct ref_entry_cb { 677const char*base; 678int trim; 679int flags; 680 each_ref_fn *fn; 681void*cb_data; 682}; 683 684/* 685 * Handle one reference in a do_for_each_ref*()-style iteration, 686 * calling an each_ref_fn for each entry. 687 */ 688static intdo_one_ref(struct ref_entry *entry,void*cb_data) 689{ 690struct ref_entry_cb *data = cb_data; 691struct ref_entry *old_current_ref; 692int retval; 693 694if(!starts_with(entry->name, data->base)) 695return0; 696 697if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 698!ref_resolves_to_object(entry)) 699return0; 700 701/* Store the old value, in case this is a recursive call: */ 702 old_current_ref = current_ref; 703 current_ref = entry; 704 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 705 entry->flag, data->cb_data); 706 current_ref = old_current_ref; 707return retval; 708} 709 710/* 711 * Call fn for each reference in dir that has index in the range 712 * offset <= index < dir->nr. Recurse into subdirectories that are in 713 * that index range, sorting them before iterating. This function 714 * does not sort dir itself; it should be sorted beforehand. fn is 715 * called for all references, including broken ones. 716 */ 717static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 718 each_ref_entry_fn fn,void*cb_data) 719{ 720int i; 721assert(dir->sorted == dir->nr); 722for(i = offset; i < dir->nr; i++) { 723struct ref_entry *entry = dir->entries[i]; 724int retval; 725if(entry->flag & REF_DIR) { 726struct ref_dir *subdir =get_ref_dir(entry); 727sort_ref_dir(subdir); 728 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 729}else{ 730 retval =fn(entry, cb_data); 731} 732if(retval) 733return retval; 734} 735return0; 736} 737 738/* 739 * Call fn for each reference in the union of dir1 and dir2, in order 740 * by refname. Recurse into subdirectories. If a value entry appears 741 * in both dir1 and dir2, then only process the version that is in 742 * dir2. The input dirs must already be sorted, but subdirs will be 743 * sorted as needed. fn is called for all references, including 744 * broken ones. 745 */ 746static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 747struct ref_dir *dir2, 748 each_ref_entry_fn fn,void*cb_data) 749{ 750int retval; 751int i1 =0, i2 =0; 752 753assert(dir1->sorted == dir1->nr); 754assert(dir2->sorted == dir2->nr); 755while(1) { 756struct ref_entry *e1, *e2; 757int cmp; 758if(i1 == dir1->nr) { 759returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 760} 761if(i2 == dir2->nr) { 762returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 763} 764 e1 = dir1->entries[i1]; 765 e2 = dir2->entries[i2]; 766 cmp =strcmp(e1->name, e2->name); 767if(cmp ==0) { 768if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 769/* Both are directories; descend them in parallel. */ 770struct ref_dir *subdir1 =get_ref_dir(e1); 771struct ref_dir *subdir2 =get_ref_dir(e2); 772sort_ref_dir(subdir1); 773sort_ref_dir(subdir2); 774 retval =do_for_each_entry_in_dirs( 775 subdir1, subdir2, fn, cb_data); 776 i1++; 777 i2++; 778}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 779/* Both are references; ignore the one from dir1. */ 780 retval =fn(e2, cb_data); 781 i1++; 782 i2++; 783}else{ 784die("conflict between reference and directory:%s", 785 e1->name); 786} 787}else{ 788struct ref_entry *e; 789if(cmp <0) { 790 e = e1; 791 i1++; 792}else{ 793 e = e2; 794 i2++; 795} 796if(e->flag & REF_DIR) { 797struct ref_dir *subdir =get_ref_dir(e); 798sort_ref_dir(subdir); 799 retval =do_for_each_entry_in_dir( 800 subdir,0, fn, cb_data); 801}else{ 802 retval =fn(e, cb_data); 803} 804} 805if(retval) 806return retval; 807} 808} 809 810/* 811 * Load all of the refs from the dir into our in-memory cache. The hard work 812 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 813 * through all of the sub-directories. We do not even need to care about 814 * sorting, as traversal order does not matter to us. 815 */ 816static voidprime_ref_dir(struct ref_dir *dir) 817{ 818int i; 819for(i =0; i < dir->nr; i++) { 820struct ref_entry *entry = dir->entries[i]; 821if(entry->flag & REF_DIR) 822prime_ref_dir(get_ref_dir(entry)); 823} 824} 825 826static intentry_matches(struct ref_entry *entry,const struct string_list *list) 827{ 828return list &&string_list_has_string(list, entry->name); 829} 830 831struct nonmatching_ref_data { 832const struct string_list *skip; 833struct ref_entry *found; 834}; 835 836static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 837{ 838struct nonmatching_ref_data *data = vdata; 839 840if(entry_matches(entry, data->skip)) 841return0; 842 843 data->found = entry; 844return1; 845} 846 847static voidreport_refname_conflict(struct ref_entry *entry, 848const char*refname) 849{ 850error("'%s' exists; cannot create '%s'", entry->name, refname); 851} 852 853/* 854 * Return true iff a reference named refname could be created without 855 * conflicting with the name of an existing reference in dir. If 856 * skip is non-NULL, ignore potential conflicts with refs in skip 857 * (e.g., because they are scheduled for deletion in the same 858 * operation). 859 * 860 * Two reference names conflict if one of them exactly matches the 861 * leading components of the other; e.g., "foo/bar" conflicts with 862 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 863 * "foo/barbados". 864 * 865 * skip must be sorted. 866 */ 867static intis_refname_available(const char*refname, 868const struct string_list *skip, 869struct ref_dir *dir) 870{ 871const char*slash; 872size_t len; 873int pos; 874char*dirname; 875 876for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 877/* 878 * We are still at a leading dir of the refname; we are 879 * looking for a conflict with a leaf entry. 880 * 881 * If we find one, we still must make sure it is 882 * not in "skip". 883 */ 884 pos =search_ref_dir(dir, refname, slash - refname); 885if(pos >=0) { 886struct ref_entry *entry = dir->entries[pos]; 887if(entry_matches(entry, skip)) 888return1; 889report_refname_conflict(entry, refname); 890return0; 891} 892 893 894/* 895 * Otherwise, we can try to continue our search with 896 * the next component; if we come up empty, we know 897 * there is nothing under this whole prefix. 898 */ 899 pos =search_ref_dir(dir, refname, slash +1- refname); 900if(pos <0) 901return1; 902 903 dir =get_ref_dir(dir->entries[pos]); 904} 905 906/* 907 * We are at the leaf of our refname; we want to 908 * make sure there are no directories which match it. 909 */ 910 len =strlen(refname); 911 dirname =xmallocz(len +1); 912sprintf(dirname,"%s/", refname); 913 pos =search_ref_dir(dir, dirname, len +1); 914free(dirname); 915 916if(pos >=0) { 917/* 918 * We found a directory named "refname". It is a 919 * problem iff it contains any ref that is not 920 * in "skip". 921 */ 922struct ref_entry *entry = dir->entries[pos]; 923struct ref_dir *dir =get_ref_dir(entry); 924struct nonmatching_ref_data data; 925 926 data.skip = skip; 927sort_ref_dir(dir); 928if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 929return1; 930 931report_refname_conflict(data.found, refname); 932return0; 933} 934 935/* 936 * There is no point in searching for another leaf 937 * node which matches it; such an entry would be the 938 * ref we are looking for, not a conflict. 939 */ 940return1; 941} 942 943struct packed_ref_cache { 944struct ref_entry *root; 945 946/* 947 * Count of references to the data structure in this instance, 948 * including the pointer from ref_cache::packed if any. The 949 * data will not be freed as long as the reference count is 950 * nonzero. 951 */ 952unsigned int referrers; 953 954/* 955 * Iff the packed-refs file associated with this instance is 956 * currently locked for writing, this points at the associated 957 * lock (which is owned by somebody else). The referrer count 958 * is also incremented when the file is locked and decremented 959 * when it is unlocked. 960 */ 961struct lock_file *lock; 962 963/* The metadata from when this packed-refs cache was read */ 964struct stat_validity validity; 965}; 966 967/* 968 * Future: need to be in "struct repository" 969 * when doing a full libification. 970 */ 971static struct ref_cache { 972struct ref_cache *next; 973struct ref_entry *loose; 974struct packed_ref_cache *packed; 975/* 976 * The submodule name, or "" for the main repo. We allocate 977 * length 1 rather than FLEX_ARRAY so that the main ref_cache 978 * is initialized correctly. 979 */ 980char name[1]; 981} ref_cache, *submodule_ref_caches; 982 983/* Lock used for the main packed-refs file: */ 984static struct lock_file packlock; 985 986/* 987 * Increment the reference count of *packed_refs. 988 */ 989static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 990{ 991 packed_refs->referrers++; 992} 993 994/* 995 * Decrease the reference count of *packed_refs. If it goes to zero, 996 * free *packed_refs and return true; otherwise return false. 997 */ 998static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 999{1000if(!--packed_refs->referrers) {1001free_ref_entry(packed_refs->root);1002stat_validity_clear(&packed_refs->validity);1003free(packed_refs);1004return1;1005}else{1006return0;1007}1008}10091010static voidclear_packed_ref_cache(struct ref_cache *refs)1011{1012if(refs->packed) {1013struct packed_ref_cache *packed_refs = refs->packed;10141015if(packed_refs->lock)1016die("internal error: packed-ref cache cleared while locked");1017 refs->packed = NULL;1018release_packed_ref_cache(packed_refs);1019}1020}10211022static voidclear_loose_ref_cache(struct ref_cache *refs)1023{1024if(refs->loose) {1025free_ref_entry(refs->loose);1026 refs->loose = NULL;1027}1028}10291030static struct ref_cache *create_ref_cache(const char*submodule)1031{1032int len;1033struct ref_cache *refs;1034if(!submodule)1035 submodule ="";1036 len =strlen(submodule) +1;1037 refs =xcalloc(1,sizeof(struct ref_cache) + len);1038memcpy(refs->name, submodule, len);1039return refs;1040}10411042/*1043 * Return a pointer to a ref_cache for the specified submodule. For1044 * the main repository, use submodule==NULL. The returned structure1045 * will be allocated and initialized but not necessarily populated; it1046 * should not be freed.1047 */1048static struct ref_cache *get_ref_cache(const char*submodule)1049{1050struct ref_cache *refs;10511052if(!submodule || !*submodule)1053return&ref_cache;10541055for(refs = submodule_ref_caches; refs; refs = refs->next)1056if(!strcmp(submodule, refs->name))1057return refs;10581059 refs =create_ref_cache(submodule);1060 refs->next = submodule_ref_caches;1061 submodule_ref_caches = refs;1062return refs;1063}10641065/* The length of a peeled reference line in packed-refs, including EOL: */1066#define PEELED_LINE_LENGTH 4210671068/*1069 * The packed-refs header line that we write out. Perhaps other1070 * traits will be added later. The trailing space is required.1071 */1072static const char PACKED_REFS_HEADER[] =1073"# pack-refs with: peeled fully-peeled\n";10741075/*1076 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1077 * Return a pointer to the refname within the line (null-terminated),1078 * or NULL if there was a problem.1079 */1080static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1081{1082const char*ref;10831084/*1085 * 42: the answer to everything.1086 *1087 * In this case, it happens to be the answer to1088 * 40 (length of sha1 hex representation)1089 * +1 (space in between hex and name)1090 * +1 (newline at the end of the line)1091 */1092if(line->len <=42)1093return NULL;10941095if(get_sha1_hex(line->buf, sha1) <0)1096return NULL;1097if(!isspace(line->buf[40]))1098return NULL;10991100 ref = line->buf +41;1101if(isspace(*ref))1102return NULL;11031104if(line->buf[line->len -1] !='\n')1105return NULL;1106 line->buf[--line->len] =0;11071108return ref;1109}11101111/*1112 * Read f, which is a packed-refs file, into dir.1113 *1114 * A comment line of the form "# pack-refs with: " may contain zero or1115 * more traits. We interpret the traits as follows:1116 *1117 * No traits:1118 *1119 * Probably no references are peeled. But if the file contains a1120 * peeled value for a reference, we will use it.1121 *1122 * peeled:1123 *1124 * References under "refs/tags/", if they *can* be peeled, *are*1125 * peeled in this file. References outside of "refs/tags/" are1126 * probably not peeled even if they could have been, but if we find1127 * a peeled value for such a reference we will use it.1128 *1129 * fully-peeled:1130 *1131 * All references in the file that can be peeled are peeled.1132 * Inversely (and this is more important), any references in the1133 * file for which no peeled value is recorded is not peelable. This1134 * trait should typically be written alongside "peeled" for1135 * compatibility with older clients, but we do not require it1136 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1137 */1138static voidread_packed_refs(FILE*f,struct ref_dir *dir)1139{1140struct ref_entry *last = NULL;1141struct strbuf line = STRBUF_INIT;1142enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11431144while(strbuf_getwholeline(&line, f,'\n') != EOF) {1145unsigned char sha1[20];1146const char*refname;1147const char*traits;11481149if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1150if(strstr(traits," fully-peeled "))1151 peeled = PEELED_FULLY;1152else if(strstr(traits," peeled "))1153 peeled = PEELED_TAGS;1154/* perhaps other traits later as well */1155continue;1156}11571158 refname =parse_ref_line(&line, sha1);1159if(refname) {1160int flag = REF_ISPACKED;11611162if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1163hashclr(sha1);1164 flag |= REF_BAD_NAME | REF_ISBROKEN;1165}1166 last =create_ref_entry(refname, sha1, flag,0);1167if(peeled == PEELED_FULLY ||1168(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1169 last->flag |= REF_KNOWS_PEELED;1170add_ref(dir, last);1171continue;1172}1173if(last &&1174 line.buf[0] =='^'&&1175 line.len == PEELED_LINE_LENGTH &&1176 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1177!get_sha1_hex(line.buf +1, sha1)) {1178hashcpy(last->u.value.peeled, sha1);1179/*1180 * Regardless of what the file header said,1181 * we definitely know the value of *this*1182 * reference:1183 */1184 last->flag |= REF_KNOWS_PEELED;1185}1186}11871188strbuf_release(&line);1189}11901191/*1192 * Get the packed_ref_cache for the specified ref_cache, creating it1193 * if necessary.1194 */1195static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1196{1197const char*packed_refs_file;11981199if(*refs->name)1200 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1201else1202 packed_refs_file =git_path("packed-refs");12031204if(refs->packed &&1205!stat_validity_check(&refs->packed->validity, packed_refs_file))1206clear_packed_ref_cache(refs);12071208if(!refs->packed) {1209FILE*f;12101211 refs->packed =xcalloc(1,sizeof(*refs->packed));1212acquire_packed_ref_cache(refs->packed);1213 refs->packed->root =create_dir_entry(refs,"",0,0);1214 f =fopen(packed_refs_file,"r");1215if(f) {1216stat_validity_update(&refs->packed->validity,fileno(f));1217read_packed_refs(f,get_ref_dir(refs->packed->root));1218fclose(f);1219}1220}1221return refs->packed;1222}12231224static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1225{1226returnget_ref_dir(packed_ref_cache->root);1227}12281229static struct ref_dir *get_packed_refs(struct ref_cache *refs)1230{1231returnget_packed_ref_dir(get_packed_ref_cache(refs));1232}12331234voidadd_packed_ref(const char*refname,const unsigned char*sha1)1235{1236struct packed_ref_cache *packed_ref_cache =1237get_packed_ref_cache(&ref_cache);12381239if(!packed_ref_cache->lock)1240die("internal error: packed refs not locked");1241add_ref(get_packed_ref_dir(packed_ref_cache),1242create_ref_entry(refname, sha1, REF_ISPACKED,1));1243}12441245/*1246 * Read the loose references from the namespace dirname into dir1247 * (without recursing). dirname must end with '/'. dir must be the1248 * directory entry corresponding to dirname.1249 */1250static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1251{1252struct ref_cache *refs = dir->ref_cache;1253DIR*d;1254const char*path;1255struct dirent *de;1256int dirnamelen =strlen(dirname);1257struct strbuf refname;12581259if(*refs->name)1260 path =git_path_submodule(refs->name,"%s", dirname);1261else1262 path =git_path("%s", dirname);12631264 d =opendir(path);1265if(!d)1266return;12671268strbuf_init(&refname, dirnamelen +257);1269strbuf_add(&refname, dirname, dirnamelen);12701271while((de =readdir(d)) != NULL) {1272unsigned char sha1[20];1273struct stat st;1274int flag;1275const char*refdir;12761277if(de->d_name[0] =='.')1278continue;1279if(ends_with(de->d_name,".lock"))1280continue;1281strbuf_addstr(&refname, de->d_name);1282 refdir = *refs->name1283?git_path_submodule(refs->name,"%s", refname.buf)1284:git_path("%s", refname.buf);1285if(stat(refdir, &st) <0) {1286;/* silently ignore */1287}else if(S_ISDIR(st.st_mode)) {1288strbuf_addch(&refname,'/');1289add_entry_to_dir(dir,1290create_dir_entry(refs, refname.buf,1291 refname.len,1));1292}else{1293if(*refs->name) {1294hashclr(sha1);1295 flag =0;1296if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1297hashclr(sha1);1298 flag |= REF_ISBROKEN;1299}1300}else if(read_ref_full(refname.buf,1301 RESOLVE_REF_READING,1302 sha1, &flag)) {1303hashclr(sha1);1304 flag |= REF_ISBROKEN;1305}1306if(check_refname_format(refname.buf,1307 REFNAME_ALLOW_ONELEVEL)) {1308hashclr(sha1);1309 flag |= REF_BAD_NAME | REF_ISBROKEN;1310}1311add_entry_to_dir(dir,1312create_ref_entry(refname.buf, sha1, flag,0));1313}1314strbuf_setlen(&refname, dirnamelen);1315}1316strbuf_release(&refname);1317closedir(d);1318}13191320static struct ref_dir *get_loose_refs(struct ref_cache *refs)1321{1322if(!refs->loose) {1323/*1324 * Mark the top-level directory complete because we1325 * are about to read the only subdirectory that can1326 * hold references:1327 */1328 refs->loose =create_dir_entry(refs,"",0,0);1329/*1330 * Create an incomplete entry for "refs/":1331 */1332add_entry_to_dir(get_ref_dir(refs->loose),1333create_dir_entry(refs,"refs/",5,1));1334}1335returnget_ref_dir(refs->loose);1336}13371338/* We allow "recursive" symbolic refs. Only within reason, though */1339#define MAXDEPTH 51340#define MAXREFLEN (1024)13411342/*1343 * Called by resolve_gitlink_ref_recursive() after it failed to read1344 * from the loose refs in ref_cache refs. Find <refname> in the1345 * packed-refs file for the submodule.1346 */1347static intresolve_gitlink_packed_ref(struct ref_cache *refs,1348const char*refname,unsigned char*sha1)1349{1350struct ref_entry *ref;1351struct ref_dir *dir =get_packed_refs(refs);13521353 ref =find_ref(dir, refname);1354if(ref == NULL)1355return-1;13561357hashcpy(sha1, ref->u.value.sha1);1358return0;1359}13601361static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1362const char*refname,unsigned char*sha1,1363int recursion)1364{1365int fd, len;1366char buffer[128], *p;1367char*path;13681369if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1370return-1;1371 path = *refs->name1372?git_path_submodule(refs->name,"%s", refname)1373:git_path("%s", refname);1374 fd =open(path, O_RDONLY);1375if(fd <0)1376returnresolve_gitlink_packed_ref(refs, refname, sha1);13771378 len =read(fd, buffer,sizeof(buffer)-1);1379close(fd);1380if(len <0)1381return-1;1382while(len &&isspace(buffer[len-1]))1383 len--;1384 buffer[len] =0;13851386/* Was it a detached head or an old-fashioned symlink? */1387if(!get_sha1_hex(buffer, sha1))1388return0;13891390/* Symref? */1391if(strncmp(buffer,"ref:",4))1392return-1;1393 p = buffer +4;1394while(isspace(*p))1395 p++;13961397returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1398}13991400intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1401{1402int len =strlen(path), retval;1403char*submodule;1404struct ref_cache *refs;14051406while(len && path[len-1] =='/')1407 len--;1408if(!len)1409return-1;1410 submodule =xstrndup(path, len);1411 refs =get_ref_cache(submodule);1412free(submodule);14131414 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1415return retval;1416}14171418/*1419 * Return the ref_entry for the given refname from the packed1420 * references. If it does not exist, return NULL.1421 */1422static struct ref_entry *get_packed_ref(const char*refname)1423{1424returnfind_ref(get_packed_refs(&ref_cache), refname);1425}14261427/*1428 * A loose ref file doesn't exist; check for a packed ref. The1429 * options are forwarded from resolve_safe_unsafe().1430 */1431static intresolve_missing_loose_ref(const char*refname,1432int resolve_flags,1433unsigned char*sha1,1434int*flags)1435{1436struct ref_entry *entry;14371438/*1439 * The loose reference file does not exist; check for a packed1440 * reference.1441 */1442 entry =get_packed_ref(refname);1443if(entry) {1444hashcpy(sha1, entry->u.value.sha1);1445if(flags)1446*flags |= REF_ISPACKED;1447return0;1448}1449/* The reference is not a packed reference, either. */1450if(resolve_flags & RESOLVE_REF_READING) {1451 errno = ENOENT;1452return-1;1453}else{1454hashclr(sha1);1455return0;1456}1457}14581459/* This function needs to return a meaningful errno on failure */1460const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1461{1462int depth = MAXDEPTH;1463 ssize_t len;1464char buffer[256];1465static char refname_buffer[256];1466int bad_name =0;14671468if(flags)1469*flags =0;14701471if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1472if(flags)1473*flags |= REF_BAD_NAME;14741475if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1476!refname_is_safe(refname)) {1477 errno = EINVAL;1478return NULL;1479}1480/*1481 * dwim_ref() uses REF_ISBROKEN to distinguish between1482 * missing refs and refs that were present but invalid,1483 * to complain about the latter to stderr.1484 *1485 * We don't know whether the ref exists, so don't set1486 * REF_ISBROKEN yet.1487 */1488 bad_name =1;1489}1490for(;;) {1491char path[PATH_MAX];1492struct stat st;1493char*buf;1494int fd;14951496if(--depth <0) {1497 errno = ELOOP;1498return NULL;1499}15001501git_snpath(path,sizeof(path),"%s", refname);15021503/*1504 * We might have to loop back here to avoid a race1505 * condition: first we lstat() the file, then we try1506 * to read it as a link or as a file. But if somebody1507 * changes the type of the file (file <-> directory1508 * <-> symlink) between the lstat() and reading, then1509 * we don't want to report that as an error but rather1510 * try again starting with the lstat().1511 */1512 stat_ref:1513if(lstat(path, &st) <0) {1514if(errno != ENOENT)1515return NULL;1516if(resolve_missing_loose_ref(refname, resolve_flags,1517 sha1, flags))1518return NULL;1519if(bad_name) {1520hashclr(sha1);1521if(flags)1522*flags |= REF_ISBROKEN;1523}1524return refname;1525}15261527/* Follow "normalized" - ie "refs/.." symlinks by hand */1528if(S_ISLNK(st.st_mode)) {1529 len =readlink(path, buffer,sizeof(buffer)-1);1530if(len <0) {1531if(errno == ENOENT || errno == EINVAL)1532/* inconsistent with lstat; retry */1533goto stat_ref;1534else1535return NULL;1536}1537 buffer[len] =0;1538if(starts_with(buffer,"refs/") &&1539!check_refname_format(buffer,0)) {1540strcpy(refname_buffer, buffer);1541 refname = refname_buffer;1542if(flags)1543*flags |= REF_ISSYMREF;1544if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1545hashclr(sha1);1546return refname;1547}1548continue;1549}1550}15511552/* Is it a directory? */1553if(S_ISDIR(st.st_mode)) {1554 errno = EISDIR;1555return NULL;1556}15571558/*1559 * Anything else, just open it and try to use it as1560 * a ref1561 */1562 fd =open(path, O_RDONLY);1563if(fd <0) {1564if(errno == ENOENT)1565/* inconsistent with lstat; retry */1566goto stat_ref;1567else1568return NULL;1569}1570 len =read_in_full(fd, buffer,sizeof(buffer)-1);1571if(len <0) {1572int save_errno = errno;1573close(fd);1574 errno = save_errno;1575return NULL;1576}1577close(fd);1578while(len &&isspace(buffer[len-1]))1579 len--;1580 buffer[len] ='\0';15811582/*1583 * Is it a symbolic ref?1584 */1585if(!starts_with(buffer,"ref:")) {1586/*1587 * Please note that FETCH_HEAD has a second1588 * line containing other data.1589 */1590if(get_sha1_hex(buffer, sha1) ||1591(buffer[40] !='\0'&& !isspace(buffer[40]))) {1592if(flags)1593*flags |= REF_ISBROKEN;1594 errno = EINVAL;1595return NULL;1596}1597if(bad_name) {1598hashclr(sha1);1599if(flags)1600*flags |= REF_ISBROKEN;1601}1602return refname;1603}1604if(flags)1605*flags |= REF_ISSYMREF;1606 buf = buffer +4;1607while(isspace(*buf))1608 buf++;1609 refname =strcpy(refname_buffer, buf);1610if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1611hashclr(sha1);1612return refname;1613}1614if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1615if(flags)1616*flags |= REF_ISBROKEN;16171618if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1619!refname_is_safe(buf)) {1620 errno = EINVAL;1621return NULL;1622}1623 bad_name =1;1624}1625}1626}16271628char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1629{1630returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));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 missing =0;2262int attempts_remaining =3;22632264 lock =xcalloc(1,sizeof(struct ref_lock));2265 lock->lock_fd = -1;22662267if(mustexist)2268 resolve_flags |= RESOLVE_REF_READING;2269if(flags & REF_DELETING) {2270 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2271if(flags & REF_NODEREF)2272 resolve_flags |= RESOLVE_REF_NO_RECURSE;2273}22742275 refname =resolve_ref_unsafe(refname, resolve_flags,2276 lock->old_sha1, &type);2277if(!refname && errno == EISDIR) {2278/* we are trying to lock foo but we used to2279 * have foo/bar which now does not exist;2280 * it is normal for the empty directory 'foo'2281 * to remain.2282 */2283 ref_file =git_path("%s", orig_refname);2284if(remove_empty_directories(ref_file)) {2285 last_errno = errno;2286error("there are still refs under '%s'", orig_refname);2287goto error_return;2288}2289 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2290 lock->old_sha1, &type);2291}2292if(type_p)2293*type_p = type;2294if(!refname) {2295 last_errno = errno;2296error("unable to resolve reference%s:%s",2297 orig_refname,strerror(errno));2298goto error_return;2299}2300 missing =is_null_sha1(lock->old_sha1);2301/* When the ref did not exist and we are creating it,2302 * make sure there is no existing ref that is packed2303 * whose name begins with our refname, nor a ref whose2304 * name is a proper prefix of our refname.2305 */2306if(missing &&2307!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2308 last_errno = ENOTDIR;2309goto error_return;2310}23112312 lock->lk =xcalloc(1,sizeof(struct lock_file));23132314 lflags =0;2315if(flags & REF_NODEREF) {2316 refname = orig_refname;2317 lflags |= LOCK_NO_DEREF;2318}2319 lock->ref_name =xstrdup(refname);2320 lock->orig_ref_name =xstrdup(orig_refname);2321 ref_file =git_path("%s", refname);2322if(missing)2323 lock->force_write =1;2324if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2325 lock->force_write =1;23262327 retry:2328switch(safe_create_leading_directories(ref_file)) {2329case SCLD_OK:2330break;/* success */2331case SCLD_VANISHED:2332if(--attempts_remaining >0)2333goto retry;2334/* fall through */2335default:2336 last_errno = errno;2337error("unable to create directory for%s", ref_file);2338goto error_return;2339}23402341 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2342if(lock->lock_fd <0) {2343 last_errno = errno;2344if(errno == ENOENT && --attempts_remaining >0)2345/*2346 * Maybe somebody just deleted one of the2347 * directories leading to ref_file. Try2348 * again:2349 */2350goto retry;2351else{2352struct strbuf err = STRBUF_INIT;2353unable_to_lock_message(ref_file, errno, &err);2354error("%s", err.buf);2355strbuf_release(&err);2356goto error_return;2357}2358}2359return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23602361 error_return:2362unlock_ref(lock);2363 errno = last_errno;2364return NULL;2365}23662367/*2368 * Write an entry to the packed-refs file for the specified refname.2369 * If peeled is non-NULL, write it as the entry's peeled value.2370 */2371static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2372unsigned char*peeled)2373{2374fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2375if(peeled)2376fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2377}23782379/*2380 * An each_ref_entry_fn that writes the entry to a packed-refs file.2381 */2382static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2383{2384enum peel_status peel_status =peel_entry(entry,0);23852386if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2387error("internal error:%sis not a valid packed reference!",2388 entry->name);2389write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2390 peel_status == PEEL_PEELED ?2391 entry->u.value.peeled : NULL);2392return0;2393}23942395/* This should return a meaningful errno on failure */2396intlock_packed_refs(int flags)2397{2398struct packed_ref_cache *packed_ref_cache;23992400if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2401return-1;2402/*2403 * Get the current packed-refs while holding the lock. If the2404 * packed-refs file has been modified since we last read it,2405 * this will automatically invalidate the cache and re-read2406 * the packed-refs file.2407 */2408 packed_ref_cache =get_packed_ref_cache(&ref_cache);2409 packed_ref_cache->lock = &packlock;2410/* Increment the reference count to prevent it from being freed: */2411acquire_packed_ref_cache(packed_ref_cache);2412return0;2413}24142415/*2416 * Commit the packed refs changes.2417 * On error we must make sure that errno contains a meaningful value.2418 */2419intcommit_packed_refs(void)2420{2421struct packed_ref_cache *packed_ref_cache =2422get_packed_ref_cache(&ref_cache);2423int error =0;2424int save_errno =0;2425FILE*out;24262427if(!packed_ref_cache->lock)2428die("internal error: packed-refs not locked");24292430 out =fdopen_lock_file(packed_ref_cache->lock,"w");2431if(!out)2432die_errno("unable to fdopen packed-refs descriptor");24332434fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2435do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24360, write_packed_entry_fn, out);24372438if(commit_lock_file(packed_ref_cache->lock)) {2439 save_errno = errno;2440 error = -1;2441}2442 packed_ref_cache->lock = NULL;2443release_packed_ref_cache(packed_ref_cache);2444 errno = save_errno;2445return error;2446}24472448voidrollback_packed_refs(void)2449{2450struct packed_ref_cache *packed_ref_cache =2451get_packed_ref_cache(&ref_cache);24522453if(!packed_ref_cache->lock)2454die("internal error: packed-refs not locked");2455rollback_lock_file(packed_ref_cache->lock);2456 packed_ref_cache->lock = NULL;2457release_packed_ref_cache(packed_ref_cache);2458clear_packed_ref_cache(&ref_cache);2459}24602461struct ref_to_prune {2462struct ref_to_prune *next;2463unsigned char sha1[20];2464char name[FLEX_ARRAY];2465};24662467struct pack_refs_cb_data {2468unsigned int flags;2469struct ref_dir *packed_refs;2470struct ref_to_prune *ref_to_prune;2471};24722473/*2474 * An each_ref_entry_fn that is run over loose references only. If2475 * the loose reference can be packed, add an entry in the packed ref2476 * cache. If the reference should be pruned, also add it to2477 * ref_to_prune in the pack_refs_cb_data.2478 */2479static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2480{2481struct pack_refs_cb_data *cb = cb_data;2482enum peel_status peel_status;2483struct ref_entry *packed_entry;2484int is_tag_ref =starts_with(entry->name,"refs/tags/");24852486/* ALWAYS pack tags */2487if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2488return0;24892490/* Do not pack symbolic or broken refs: */2491if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2492return0;24932494/* Add a packed ref cache entry equivalent to the loose entry. */2495 peel_status =peel_entry(entry,1);2496if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2497die("internal error peeling reference%s(%s)",2498 entry->name,sha1_to_hex(entry->u.value.sha1));2499 packed_entry =find_ref(cb->packed_refs, entry->name);2500if(packed_entry) {2501/* Overwrite existing packed entry with info from loose entry */2502 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2503hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2504}else{2505 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2506 REF_ISPACKED | REF_KNOWS_PEELED,0);2507add_ref(cb->packed_refs, packed_entry);2508}2509hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25102511/* Schedule the loose reference for pruning if requested. */2512if((cb->flags & PACK_REFS_PRUNE)) {2513int namelen =strlen(entry->name) +1;2514struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2515hashcpy(n->sha1, entry->u.value.sha1);2516strcpy(n->name, entry->name);2517 n->next = cb->ref_to_prune;2518 cb->ref_to_prune = n;2519}2520return0;2521}25222523/*2524 * Remove empty parents, but spare refs/ and immediate subdirs.2525 * Note: munges *name.2526 */2527static voidtry_remove_empty_parents(char*name)2528{2529char*p, *q;2530int i;2531 p = name;2532for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2533while(*p && *p !='/')2534 p++;2535/* tolerate duplicate slashes; see check_refname_format() */2536while(*p =='/')2537 p++;2538}2539for(q = p; *q; q++)2540;2541while(1) {2542while(q > p && *q !='/')2543 q--;2544while(q > p && *(q-1) =='/')2545 q--;2546if(q == p)2547break;2548*q ='\0';2549if(rmdir(git_path("%s", name)))2550break;2551}2552}25532554/* make sure nobody touched the ref, and unlink */2555static voidprune_ref(struct ref_to_prune *r)2556{2557struct ref_transaction *transaction;2558struct strbuf err = STRBUF_INIT;25592560if(check_refname_format(r->name,0))2561return;25622563 transaction =ref_transaction_begin(&err);2564if(!transaction ||2565ref_transaction_delete(transaction, r->name, r->sha1,2566 REF_ISPRUNING,1, NULL, &err) ||2567ref_transaction_commit(transaction, &err)) {2568ref_transaction_free(transaction);2569error("%s", err.buf);2570strbuf_release(&err);2571return;2572}2573ref_transaction_free(transaction);2574strbuf_release(&err);2575try_remove_empty_parents(r->name);2576}25772578static voidprune_refs(struct ref_to_prune *r)2579{2580while(r) {2581prune_ref(r);2582 r = r->next;2583}2584}25852586intpack_refs(unsigned int flags)2587{2588struct pack_refs_cb_data cbdata;25892590memset(&cbdata,0,sizeof(cbdata));2591 cbdata.flags = flags;25922593lock_packed_refs(LOCK_DIE_ON_ERROR);2594 cbdata.packed_refs =get_packed_refs(&ref_cache);25952596do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2597 pack_if_possible_fn, &cbdata);25982599if(commit_packed_refs())2600die_errno("unable to overwrite old ref-pack file");26012602prune_refs(cbdata.ref_to_prune);2603return0;2604}26052606/*2607 * If entry is no longer needed in packed-refs, add it to the string2608 * list pointed to by cb_data. Reasons for deleting entries:2609 *2610 * - Entry is broken.2611 * - Entry is overridden by a loose ref.2612 * - Entry does not point at a valid object.2613 *2614 * In the first and third cases, also emit an error message because these2615 * are indications of repository corruption.2616 */2617static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2618{2619struct string_list *refs_to_delete = cb_data;26202621if(entry->flag & REF_ISBROKEN) {2622/* This shouldn't happen to packed refs. */2623error("%sis broken!", entry->name);2624string_list_append(refs_to_delete, entry->name);2625return0;2626}2627if(!has_sha1_file(entry->u.value.sha1)) {2628unsigned char sha1[20];2629int flags;26302631if(read_ref_full(entry->name,0, sha1, &flags))2632/* We should at least have found the packed ref. */2633die("Internal error");2634if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2635/*2636 * This packed reference is overridden by a2637 * loose reference, so it is OK that its value2638 * is no longer valid; for example, it might2639 * refer to an object that has been garbage2640 * collected. For this purpose we don't even2641 * care whether the loose reference itself is2642 * invalid, broken, symbolic, etc. Silently2643 * remove the packed reference.2644 */2645string_list_append(refs_to_delete, entry->name);2646return0;2647}2648/*2649 * There is no overriding loose reference, so the fact2650 * that this reference doesn't refer to a valid object2651 * indicates some kind of repository corruption.2652 * Report the problem, then omit the reference from2653 * the output.2654 */2655error("%sdoes not point to a valid object!", entry->name);2656string_list_append(refs_to_delete, entry->name);2657return0;2658}26592660return0;2661}26622663intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2664{2665struct ref_dir *packed;2666struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2667struct string_list_item *refname, *ref_to_delete;2668int ret, needs_repacking =0, removed =0;26692670assert(err);26712672/* Look for a packed ref */2673for_each_string_list_item(refname, refnames) {2674if(get_packed_ref(refname->string)) {2675 needs_repacking =1;2676break;2677}2678}26792680/* Avoid locking if we have nothing to do */2681if(!needs_repacking)2682return0;/* no refname exists in packed refs */26832684if(lock_packed_refs(0)) {2685unable_to_lock_message(git_path("packed-refs"), errno, err);2686return-1;2687}2688 packed =get_packed_refs(&ref_cache);26892690/* Remove refnames from the cache */2691for_each_string_list_item(refname, refnames)2692if(remove_entry(packed, refname->string) != -1)2693 removed =1;2694if(!removed) {2695/*2696 * All packed entries disappeared while we were2697 * acquiring the lock.2698 */2699rollback_packed_refs();2700return0;2701}27022703/* Remove any other accumulated cruft */2704do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2705for_each_string_list_item(ref_to_delete, &refs_to_delete) {2706if(remove_entry(packed, ref_to_delete->string) == -1)2707die("internal error");2708}27092710/* Write what remains */2711 ret =commit_packed_refs();2712if(ret)2713strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2714strerror(errno));2715return ret;2716}27172718static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2719{2720assert(err);27212722if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2723/*2724 * loose. The loose file name is the same as the2725 * lockfile name, minus ".lock":2726 */2727char*loose_filename =get_locked_file_path(lock->lk);2728int res =unlink_or_msg(loose_filename, err);2729free(loose_filename);2730if(res)2731return1;2732}2733return0;2734}27352736intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2737{2738struct ref_transaction *transaction;2739struct strbuf err = STRBUF_INIT;27402741 transaction =ref_transaction_begin(&err);2742if(!transaction ||2743ref_transaction_delete(transaction, refname, sha1, delopt,2744 sha1 && !is_null_sha1(sha1), NULL, &err) ||2745ref_transaction_commit(transaction, &err)) {2746error("%s", err.buf);2747ref_transaction_free(transaction);2748strbuf_release(&err);2749return1;2750}2751ref_transaction_free(transaction);2752strbuf_release(&err);2753return0;2754}27552756/*2757 * People using contrib's git-new-workdir have .git/logs/refs ->2758 * /some/other/path/.git/logs/refs, and that may live on another device.2759 *2760 * IOW, to avoid cross device rename errors, the temporary renamed log must2761 * live into logs/refs.2762 */2763#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27642765static intrename_tmp_log(const char*newrefname)2766{2767int attempts_remaining =4;27682769 retry:2770switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2771case SCLD_OK:2772break;/* success */2773case SCLD_VANISHED:2774if(--attempts_remaining >0)2775goto retry;2776/* fall through */2777default:2778error("unable to create directory for%s", newrefname);2779return-1;2780}27812782if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2783if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2784/*2785 * rename(a, b) when b is an existing2786 * directory ought to result in ISDIR, but2787 * Solaris 5.8 gives ENOTDIR. Sheesh.2788 */2789if(remove_empty_directories(git_path("logs/%s", newrefname))) {2790error("Directory not empty: logs/%s", newrefname);2791return-1;2792}2793goto retry;2794}else if(errno == ENOENT && --attempts_remaining >0) {2795/*2796 * Maybe another process just deleted one of2797 * the directories in the path to newrefname.2798 * Try again from the beginning.2799 */2800goto retry;2801}else{2802error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2803 newrefname,strerror(errno));2804return-1;2805}2806}2807return0;2808}28092810static intrename_ref_available(const char*oldname,const char*newname)2811{2812struct string_list skip = STRING_LIST_INIT_NODUP;2813int ret;28142815string_list_insert(&skip, oldname);2816 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2817&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2818string_list_clear(&skip,0);2819return ret;2820}28212822static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2823const char*logmsg);28242825intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2826{2827unsigned char sha1[20], orig_sha1[20];2828int flag =0, logmoved =0;2829struct ref_lock *lock;2830struct stat loginfo;2831int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2832const char*symref = NULL;28332834if(log &&S_ISLNK(loginfo.st_mode))2835returnerror("reflog for%sis a symlink", oldrefname);28362837 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2838 orig_sha1, &flag);2839if(flag & REF_ISSYMREF)2840returnerror("refname%sis a symbolic ref, renaming it is not supported",2841 oldrefname);2842if(!symref)2843returnerror("refname%snot found", oldrefname);28442845if(!rename_ref_available(oldrefname, newrefname))2846return1;28472848if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2849returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2850 oldrefname,strerror(errno));28512852if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2853error("unable to delete old%s", oldrefname);2854goto rollback;2855}28562857if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2858delete_ref(newrefname, sha1, REF_NODEREF)) {2859if(errno==EISDIR) {2860if(remove_empty_directories(git_path("%s", newrefname))) {2861error("Directory not empty:%s", newrefname);2862goto rollback;2863}2864}else{2865error("unable to delete existing%s", newrefname);2866goto rollback;2867}2868}28692870if(log &&rename_tmp_log(newrefname))2871goto rollback;28722873 logmoved = log;28742875 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2876if(!lock) {2877error("unable to lock%sfor update", newrefname);2878goto rollback;2879}2880 lock->force_write =1;2881hashcpy(lock->old_sha1, orig_sha1);2882if(write_ref_sha1(lock, orig_sha1, logmsg)) {2883error("unable to write current sha1 into%s", newrefname);2884goto rollback;2885}28862887return0;28882889 rollback:2890 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2891if(!lock) {2892error("unable to lock%sfor rollback", oldrefname);2893goto rollbacklog;2894}28952896 lock->force_write =1;2897 flag = log_all_ref_updates;2898 log_all_ref_updates =0;2899if(write_ref_sha1(lock, orig_sha1, NULL))2900error("unable to write current sha1 into%s", oldrefname);2901 log_all_ref_updates = flag;29022903 rollbacklog:2904if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2905error("unable to restore logfile%sfrom%s:%s",2906 oldrefname, newrefname,strerror(errno));2907if(!logmoved && log &&2908rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2909error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2910 oldrefname,strerror(errno));29112912return1;2913}29142915static intclose_ref(struct ref_lock *lock)2916{2917if(close_lock_file(lock->lk))2918return-1;2919 lock->lock_fd = -1;2920return0;2921}29222923static intcommit_ref(struct ref_lock *lock)2924{2925if(commit_lock_file(lock->lk))2926return-1;2927 lock->lock_fd = -1;2928return0;2929}29302931/*2932 * copy the reflog message msg to buf, which has been allocated sufficiently2933 * large, while cleaning up the whitespaces. Especially, convert LF to space,2934 * because reflog file is one line per entry.2935 */2936static intcopy_msg(char*buf,const char*msg)2937{2938char*cp = buf;2939char c;2940int wasspace =1;29412942*cp++ ='\t';2943while((c = *msg++)) {2944if(wasspace &&isspace(c))2945continue;2946 wasspace =isspace(c);2947if(wasspace)2948 c =' ';2949*cp++ = c;2950}2951while(buf < cp &&isspace(cp[-1]))2952 cp--;2953*cp++ ='\n';2954return cp - buf;2955}29562957/* This function must set a meaningful errno on failure */2958intlog_ref_setup(const char*refname,char*logfile,int bufsize)2959{2960int logfd, oflags = O_APPEND | O_WRONLY;29612962git_snpath(logfile, bufsize,"logs/%s", refname);2963if(log_all_ref_updates &&2964(starts_with(refname,"refs/heads/") ||2965starts_with(refname,"refs/remotes/") ||2966starts_with(refname,"refs/notes/") ||2967!strcmp(refname,"HEAD"))) {2968if(safe_create_leading_directories(logfile) <0) {2969int save_errno = errno;2970error("unable to create directory for%s", logfile);2971 errno = save_errno;2972return-1;2973}2974 oflags |= O_CREAT;2975}29762977 logfd =open(logfile, oflags,0666);2978if(logfd <0) {2979if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2980return0;29812982if(errno == EISDIR) {2983if(remove_empty_directories(logfile)) {2984int save_errno = errno;2985error("There are still logs under '%s'",2986 logfile);2987 errno = save_errno;2988return-1;2989}2990 logfd =open(logfile, oflags,0666);2991}29922993if(logfd <0) {2994int save_errno = errno;2995error("Unable to append to%s:%s", logfile,2996strerror(errno));2997 errno = save_errno;2998return-1;2999}3000}30013002adjust_shared_perm(logfile);3003close(logfd);3004return0;3005}30063007static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3008const unsigned char*new_sha1,3009const char*committer,const char*msg)3010{3011int msglen, written;3012unsigned maxlen, len;3013char*logrec;30143015 msglen = msg ?strlen(msg) :0;3016 maxlen =strlen(committer) + msglen +100;3017 logrec =xmalloc(maxlen);3018 len =sprintf(logrec,"%s %s %s\n",3019sha1_to_hex(old_sha1),3020sha1_to_hex(new_sha1),3021 committer);3022if(msglen)3023 len +=copy_msg(logrec + len -1, msg) -1;30243025 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3026free(logrec);3027if(written != len)3028return-1;30293030return0;3031}30323033static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3034const unsigned char*new_sha1,const char*msg)3035{3036int logfd, result, oflags = O_APPEND | O_WRONLY;3037char log_file[PATH_MAX];30383039if(log_all_ref_updates <0)3040 log_all_ref_updates = !is_bare_repository();30413042 result =log_ref_setup(refname, log_file,sizeof(log_file));3043if(result)3044return result;30453046 logfd =open(log_file, oflags);3047if(logfd <0)3048return0;3049 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3050git_committer_info(0), msg);3051if(result) {3052int save_errno = errno;3053close(logfd);3054error("Unable to append to%s", log_file);3055 errno = save_errno;3056return-1;3057}3058if(close(logfd)) {3059int save_errno = errno;3060error("Unable to append to%s", log_file);3061 errno = save_errno;3062return-1;3063}3064return0;3065}30663067intis_branch(const char*refname)3068{3069return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3070}30713072/*3073 * Write sha1 into the ref specified by the lock. Make sure that errno3074 * is sane on error.3075 */3076static intwrite_ref_sha1(struct ref_lock *lock,3077const unsigned char*sha1,const char*logmsg)3078{3079static char term ='\n';3080struct object *o;30813082if(!lock) {3083 errno = EINVAL;3084return-1;3085}3086if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3087unlock_ref(lock);3088return0;3089}3090 o =parse_object(sha1);3091if(!o) {3092error("Trying to write ref%swith nonexistent object%s",3093 lock->ref_name,sha1_to_hex(sha1));3094unlock_ref(lock);3095 errno = EINVAL;3096return-1;3097}3098if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3099error("Trying to write non-commit object%sto branch%s",3100sha1_to_hex(sha1), lock->ref_name);3101unlock_ref(lock);3102 errno = EINVAL;3103return-1;3104}3105if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3106write_in_full(lock->lock_fd, &term,1) !=1||3107close_ref(lock) <0) {3108int save_errno = errno;3109error("Couldn't write%s", lock->lk->filename.buf);3110unlock_ref(lock);3111 errno = save_errno;3112return-1;3113}3114clear_loose_ref_cache(&ref_cache);3115if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3116(strcmp(lock->ref_name, lock->orig_ref_name) &&3117log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3118unlock_ref(lock);3119return-1;3120}3121if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3122/*3123 * Special hack: If a branch is updated directly and HEAD3124 * points to it (may happen on the remote side of a push3125 * for example) then logically the HEAD reflog should be3126 * updated too.3127 * A generic solution implies reverse symref information,3128 * but finding all symrefs pointing to the given branch3129 * would be rather costly for this rare event (the direct3130 * update of a branch) to be worth it. So let's cheat and3131 * check with HEAD only which should cover 99% of all usage3132 * scenarios (even 100% of the default ones).3133 */3134unsigned char head_sha1[20];3135int head_flag;3136const char*head_ref;3137 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3138 head_sha1, &head_flag);3139if(head_ref && (head_flag & REF_ISSYMREF) &&3140!strcmp(head_ref, lock->ref_name))3141log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3142}3143if(commit_ref(lock)) {3144error("Couldn't set%s", lock->ref_name);3145unlock_ref(lock);3146return-1;3147}3148unlock_ref(lock);3149return0;3150}31513152intcreate_symref(const char*ref_target,const char*refs_heads_master,3153const char*logmsg)3154{3155const char*lockpath;3156char ref[1000];3157int fd, len, written;3158char*git_HEAD =git_pathdup("%s", ref_target);3159unsigned char old_sha1[20], new_sha1[20];31603161if(logmsg &&read_ref(ref_target, old_sha1))3162hashclr(old_sha1);31633164if(safe_create_leading_directories(git_HEAD) <0)3165returnerror("unable to create directory for%s", git_HEAD);31663167#ifndef NO_SYMLINK_HEAD3168if(prefer_symlink_refs) {3169unlink(git_HEAD);3170if(!symlink(refs_heads_master, git_HEAD))3171goto done;3172fprintf(stderr,"no symlink - falling back to symbolic ref\n");3173}3174#endif31753176 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3177if(sizeof(ref) <= len) {3178error("refname too long:%s", refs_heads_master);3179goto error_free_return;3180}3181 lockpath =mkpath("%s.lock", git_HEAD);3182 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3183if(fd <0) {3184error("Unable to open%sfor writing", lockpath);3185goto error_free_return;3186}3187 written =write_in_full(fd, ref, len);3188if(close(fd) !=0|| written != len) {3189error("Unable to write to%s", lockpath);3190goto error_unlink_return;3191}3192if(rename(lockpath, git_HEAD) <0) {3193error("Unable to create%s", git_HEAD);3194goto error_unlink_return;3195}3196if(adjust_shared_perm(git_HEAD)) {3197error("Unable to fix permissions on%s", lockpath);3198 error_unlink_return:3199unlink_or_warn(lockpath);3200 error_free_return:3201free(git_HEAD);3202return-1;3203}32043205#ifndef NO_SYMLINK_HEAD3206 done:3207#endif3208if(logmsg && !read_ref(refs_heads_master, new_sha1))3209log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32103211free(git_HEAD);3212return0;3213}32143215struct read_ref_at_cb {3216const char*refname;3217unsigned long at_time;3218int cnt;3219int reccnt;3220unsigned char*sha1;3221int found_it;32223223unsigned char osha1[20];3224unsigned char nsha1[20];3225int tz;3226unsigned long date;3227char**msg;3228unsigned long*cutoff_time;3229int*cutoff_tz;3230int*cutoff_cnt;3231};32323233static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3234const char*email,unsigned long timestamp,int tz,3235const char*message,void*cb_data)3236{3237struct read_ref_at_cb *cb = cb_data;32383239 cb->reccnt++;3240 cb->tz = tz;3241 cb->date = timestamp;32423243if(timestamp <= cb->at_time || cb->cnt ==0) {3244if(cb->msg)3245*cb->msg =xstrdup(message);3246if(cb->cutoff_time)3247*cb->cutoff_time = timestamp;3248if(cb->cutoff_tz)3249*cb->cutoff_tz = tz;3250if(cb->cutoff_cnt)3251*cb->cutoff_cnt = cb->reccnt -1;3252/*3253 * we have not yet updated cb->[n|o]sha1 so they still3254 * hold the values for the previous record.3255 */3256if(!is_null_sha1(cb->osha1)) {3257hashcpy(cb->sha1, nsha1);3258if(hashcmp(cb->osha1, nsha1))3259warning("Log for ref%shas gap after%s.",3260 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3261}3262else if(cb->date == cb->at_time)3263hashcpy(cb->sha1, nsha1);3264else if(hashcmp(nsha1, cb->sha1))3265warning("Log for ref%sunexpectedly ended on%s.",3266 cb->refname,show_date(cb->date, cb->tz,3267 DATE_RFC2822));3268hashcpy(cb->osha1, osha1);3269hashcpy(cb->nsha1, nsha1);3270 cb->found_it =1;3271return1;3272}3273hashcpy(cb->osha1, osha1);3274hashcpy(cb->nsha1, nsha1);3275if(cb->cnt >0)3276 cb->cnt--;3277return0;3278}32793280static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3281const char*email,unsigned long timestamp,3282int tz,const char*message,void*cb_data)3283{3284struct read_ref_at_cb *cb = cb_data;32853286if(cb->msg)3287*cb->msg =xstrdup(message);3288if(cb->cutoff_time)3289*cb->cutoff_time = timestamp;3290if(cb->cutoff_tz)3291*cb->cutoff_tz = tz;3292if(cb->cutoff_cnt)3293*cb->cutoff_cnt = cb->reccnt;3294hashcpy(cb->sha1, osha1);3295if(is_null_sha1(cb->sha1))3296hashcpy(cb->sha1, nsha1);3297/* We just want the first entry */3298return1;3299}33003301intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3302unsigned char*sha1,char**msg,3303unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3304{3305struct read_ref_at_cb cb;33063307memset(&cb,0,sizeof(cb));3308 cb.refname = refname;3309 cb.at_time = at_time;3310 cb.cnt = cnt;3311 cb.msg = msg;3312 cb.cutoff_time = cutoff_time;3313 cb.cutoff_tz = cutoff_tz;3314 cb.cutoff_cnt = cutoff_cnt;3315 cb.sha1 = sha1;33163317for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33183319if(!cb.reccnt) {3320if(flags & GET_SHA1_QUIETLY)3321exit(128);3322else3323die("Log for%sis empty.", refname);3324}3325if(cb.found_it)3326return0;33273328for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33293330return1;3331}33323333intreflog_exists(const char*refname)3334{3335struct stat st;33363337return!lstat(git_path("logs/%s", refname), &st) &&3338S_ISREG(st.st_mode);3339}33403341intdelete_reflog(const char*refname)3342{3343returnremove_path(git_path("logs/%s", refname));3344}33453346static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3347{3348unsigned char osha1[20], nsha1[20];3349char*email_end, *message;3350unsigned long timestamp;3351int tz;33523353/* old SP new SP name <email> SP time TAB msg LF */3354if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3355get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3356get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3357!(email_end =strchr(sb->buf +82,'>')) ||3358 email_end[1] !=' '||3359!(timestamp =strtoul(email_end +2, &message,10)) ||3360!message || message[0] !=' '||3361(message[1] !='+'&& message[1] !='-') ||3362!isdigit(message[2]) || !isdigit(message[3]) ||3363!isdigit(message[4]) || !isdigit(message[5]))3364return0;/* corrupt? */3365 email_end[1] ='\0';3366 tz =strtol(message +1, NULL,10);3367if(message[6] !='\t')3368 message +=6;3369else3370 message +=7;3371returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3372}33733374static char*find_beginning_of_line(char*bob,char*scan)3375{3376while(bob < scan && *(--scan) !='\n')3377;/* keep scanning backwards */3378/*3379 * Return either beginning of the buffer, or LF at the end of3380 * the previous line.3381 */3382return scan;3383}33843385intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3386{3387struct strbuf sb = STRBUF_INIT;3388FILE*logfp;3389long pos;3390int ret =0, at_tail =1;33913392 logfp =fopen(git_path("logs/%s", refname),"r");3393if(!logfp)3394return-1;33953396/* Jump to the end */3397if(fseek(logfp,0, SEEK_END) <0)3398returnerror("cannot seek back reflog for%s:%s",3399 refname,strerror(errno));3400 pos =ftell(logfp);3401while(!ret &&0< pos) {3402int cnt;3403size_t nread;3404char buf[BUFSIZ];3405char*endp, *scanp;34063407/* Fill next block from the end */3408 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3409if(fseek(logfp, pos - cnt, SEEK_SET))3410returnerror("cannot seek back reflog for%s:%s",3411 refname,strerror(errno));3412 nread =fread(buf, cnt,1, logfp);3413if(nread !=1)3414returnerror("cannot read%dbytes from reflog for%s:%s",3415 cnt, refname,strerror(errno));3416 pos -= cnt;34173418 scanp = endp = buf + cnt;3419if(at_tail && scanp[-1] =='\n')3420/* Looking at the final LF at the end of the file */3421 scanp--;3422 at_tail =0;34233424while(buf < scanp) {3425/*3426 * terminating LF of the previous line, or the beginning3427 * of the buffer.3428 */3429char*bp;34303431 bp =find_beginning_of_line(buf, scanp);34323433if(*bp =='\n') {3434/*3435 * The newline is the end of the previous line,3436 * so we know we have complete line starting3437 * at (bp + 1). Prefix it onto any prior data3438 * we collected for the line and process it.3439 */3440strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3441 scanp = bp;3442 endp = bp +1;3443 ret =show_one_reflog_ent(&sb, fn, cb_data);3444strbuf_reset(&sb);3445if(ret)3446break;3447}else if(!pos) {3448/*3449 * We are at the start of the buffer, and the3450 * start of the file; there is no previous3451 * line, and we have everything for this one.3452 * Process it, and we can end the loop.3453 */3454strbuf_splice(&sb,0,0, buf, endp - buf);3455 ret =show_one_reflog_ent(&sb, fn, cb_data);3456strbuf_reset(&sb);3457break;3458}34593460if(bp == buf) {3461/*3462 * We are at the start of the buffer, and there3463 * is more file to read backwards. Which means3464 * we are in the middle of a line. Note that we3465 * may get here even if *bp was a newline; that3466 * just means we are at the exact end of the3467 * previous line, rather than some spot in the3468 * middle.3469 *3470 * Save away what we have to be combined with3471 * the data from the next read.3472 */3473strbuf_splice(&sb,0,0, buf, endp - buf);3474break;3475}3476}34773478}3479if(!ret && sb.len)3480die("BUG: reverse reflog parser had leftover data");34813482fclose(logfp);3483strbuf_release(&sb);3484return ret;3485}34863487intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3488{3489FILE*logfp;3490struct strbuf sb = STRBUF_INIT;3491int ret =0;34923493 logfp =fopen(git_path("logs/%s", refname),"r");3494if(!logfp)3495return-1;34963497while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3498 ret =show_one_reflog_ent(&sb, fn, cb_data);3499fclose(logfp);3500strbuf_release(&sb);3501return ret;3502}3503/*3504 * Call fn for each reflog in the namespace indicated by name. name3505 * must be empty or end with '/'. Name will be used as a scratch3506 * space, but its contents will be restored before return.3507 */3508static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3509{3510DIR*d =opendir(git_path("logs/%s", name->buf));3511int retval =0;3512struct dirent *de;3513int oldlen = name->len;35143515if(!d)3516return name->len ? errno :0;35173518while((de =readdir(d)) != NULL) {3519struct stat st;35203521if(de->d_name[0] =='.')3522continue;3523if(ends_with(de->d_name,".lock"))3524continue;3525strbuf_addstr(name, de->d_name);3526if(stat(git_path("logs/%s", name->buf), &st) <0) {3527;/* silently ignore */3528}else{3529if(S_ISDIR(st.st_mode)) {3530strbuf_addch(name,'/');3531 retval =do_for_each_reflog(name, fn, cb_data);3532}else{3533unsigned char sha1[20];3534if(read_ref_full(name->buf,0, sha1, NULL))3535 retval =error("bad ref for%s", name->buf);3536else3537 retval =fn(name->buf, sha1,0, cb_data);3538}3539if(retval)3540break;3541}3542strbuf_setlen(name, oldlen);3543}3544closedir(d);3545return retval;3546}35473548intfor_each_reflog(each_ref_fn fn,void*cb_data)3549{3550int retval;3551struct strbuf name;3552strbuf_init(&name, PATH_MAX);3553 retval =do_for_each_reflog(&name, fn, cb_data);3554strbuf_release(&name);3555return retval;3556}35573558/**3559 * Information needed for a single ref update. Set new_sha1 to the3560 * new value or to zero to delete the ref. To check the old value3561 * while locking the ref, set have_old to 1 and set old_sha1 to the3562 * value or to zero to ensure the ref does not exist before update.3563 */3564struct ref_update {3565unsigned char new_sha1[20];3566unsigned char old_sha1[20];3567int flags;/* REF_NODEREF? */3568int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3569struct ref_lock *lock;3570int type;3571char*msg;3572const char refname[FLEX_ARRAY];3573};35743575/*3576 * Transaction states.3577 * OPEN: The transaction is in a valid state and can accept new updates.3578 * An OPEN transaction can be committed.3579 * CLOSED: A closed transaction is no longer active and no other operations3580 * than free can be used on it in this state.3581 * A transaction can either become closed by successfully committing3582 * an active transaction or if there is a failure while building3583 * the transaction thus rendering it failed/inactive.3584 */3585enum ref_transaction_state {3586 REF_TRANSACTION_OPEN =0,3587 REF_TRANSACTION_CLOSED =13588};35893590/*3591 * Data structure for holding a reference transaction, which can3592 * consist of checks and updates to multiple references, carried out3593 * as atomically as possible. This structure is opaque to callers.3594 */3595struct ref_transaction {3596struct ref_update **updates;3597size_t alloc;3598size_t nr;3599enum ref_transaction_state state;3600};36013602struct ref_transaction *ref_transaction_begin(struct strbuf *err)3603{3604assert(err);36053606returnxcalloc(1,sizeof(struct ref_transaction));3607}36083609voidref_transaction_free(struct ref_transaction *transaction)3610{3611int i;36123613if(!transaction)3614return;36153616for(i =0; i < transaction->nr; i++) {3617free(transaction->updates[i]->msg);3618free(transaction->updates[i]);3619}3620free(transaction->updates);3621free(transaction);3622}36233624static struct ref_update *add_update(struct ref_transaction *transaction,3625const char*refname)3626{3627size_t len =strlen(refname);3628struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36293630strcpy((char*)update->refname, refname);3631ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3632 transaction->updates[transaction->nr++] = update;3633return update;3634}36353636intref_transaction_update(struct ref_transaction *transaction,3637const char*refname,3638const unsigned char*new_sha1,3639const unsigned char*old_sha1,3640int flags,int have_old,const char*msg,3641struct strbuf *err)3642{3643struct ref_update *update;36443645assert(err);36463647if(transaction->state != REF_TRANSACTION_OPEN)3648die("BUG: update called for transaction that is not open");36493650if(have_old && !old_sha1)3651die("BUG: have_old is true but old_sha1 is NULL");36523653if(!is_null_sha1(new_sha1) &&3654check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3655strbuf_addf(err,"refusing to update ref with bad name%s",3656 refname);3657return-1;3658}36593660 update =add_update(transaction, refname);3661hashcpy(update->new_sha1, new_sha1);3662 update->flags = flags;3663 update->have_old = have_old;3664if(have_old)3665hashcpy(update->old_sha1, old_sha1);3666if(msg)3667 update->msg =xstrdup(msg);3668return0;3669}36703671intref_transaction_create(struct ref_transaction *transaction,3672const char*refname,3673const unsigned char*new_sha1,3674int flags,const char*msg,3675struct strbuf *err)3676{3677returnref_transaction_update(transaction, refname, new_sha1,3678 null_sha1, flags,1, msg, err);3679}36803681intref_transaction_delete(struct ref_transaction *transaction,3682const char*refname,3683const unsigned char*old_sha1,3684int flags,int have_old,const char*msg,3685struct strbuf *err)3686{3687returnref_transaction_update(transaction, refname, null_sha1,3688 old_sha1, flags, have_old, msg, err);3689}36903691intupdate_ref(const char*action,const char*refname,3692const unsigned char*sha1,const unsigned char*oldval,3693int flags,enum action_on_err onerr)3694{3695struct ref_transaction *t;3696struct strbuf err = STRBUF_INIT;36973698 t =ref_transaction_begin(&err);3699if(!t ||3700ref_transaction_update(t, refname, sha1, oldval, flags,3701!!oldval, action, &err) ||3702ref_transaction_commit(t, &err)) {3703const char*str ="update_ref failed for ref '%s':%s";37043705ref_transaction_free(t);3706switch(onerr) {3707case UPDATE_REFS_MSG_ON_ERR:3708error(str, refname, err.buf);3709break;3710case UPDATE_REFS_DIE_ON_ERR:3711die(str, refname, err.buf);3712break;3713case UPDATE_REFS_QUIET_ON_ERR:3714break;3715}3716strbuf_release(&err);3717return1;3718}3719strbuf_release(&err);3720ref_transaction_free(t);3721return0;3722}37233724static intref_update_compare(const void*r1,const void*r2)3725{3726const struct ref_update *const*u1 = r1;3727const struct ref_update *const*u2 = r2;3728returnstrcmp((*u1)->refname, (*u2)->refname);3729}37303731static intref_update_reject_duplicates(struct ref_update **updates,int n,3732struct strbuf *err)3733{3734int i;37353736assert(err);37373738for(i =1; i < n; i++)3739if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3740strbuf_addf(err,3741"Multiple updates for ref '%s' not allowed.",3742 updates[i]->refname);3743return1;3744}3745return0;3746}37473748intref_transaction_commit(struct ref_transaction *transaction,3749struct strbuf *err)3750{3751int ret =0, i;3752int n = transaction->nr;3753struct ref_update **updates = transaction->updates;3754struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3755struct string_list_item *ref_to_delete;37563757assert(err);37583759if(transaction->state != REF_TRANSACTION_OPEN)3760die("BUG: commit called for transaction that is not open");37613762if(!n) {3763 transaction->state = REF_TRANSACTION_CLOSED;3764return0;3765}37663767/* Copy, sort, and reject duplicate refs */3768qsort(updates, n,sizeof(*updates), ref_update_compare);3769if(ref_update_reject_duplicates(updates, n, err)) {3770 ret = TRANSACTION_GENERIC_ERROR;3771goto cleanup;3772}37733774/* Acquire all locks while verifying old values */3775for(i =0; i < n; i++) {3776struct ref_update *update = updates[i];3777int flags = update->flags;37783779if(is_null_sha1(update->new_sha1))3780 flags |= REF_DELETING;3781 update->lock =lock_ref_sha1_basic(update->refname,3782(update->have_old ?3783 update->old_sha1 :3784 NULL),3785 NULL,3786 flags,3787&update->type);3788if(!update->lock) {3789 ret = (errno == ENOTDIR)3790? TRANSACTION_NAME_CONFLICT3791: TRANSACTION_GENERIC_ERROR;3792strbuf_addf(err,"Cannot lock the ref '%s'.",3793 update->refname);3794goto cleanup;3795}3796}37973798/* Perform updates first so live commits remain referenced */3799for(i =0; i < n; i++) {3800struct ref_update *update = updates[i];38013802if(!is_null_sha1(update->new_sha1)) {3803if(write_ref_sha1(update->lock, update->new_sha1,3804 update->msg)) {3805 update->lock = NULL;/* freed by write_ref_sha1 */3806strbuf_addf(err,"Cannot update the ref '%s'.",3807 update->refname);3808 ret = TRANSACTION_GENERIC_ERROR;3809goto cleanup;3810}3811 update->lock = NULL;/* freed by write_ref_sha1 */3812}3813}38143815/* Perform deletes now that updates are safely completed */3816for(i =0; i < n; i++) {3817struct ref_update *update = updates[i];38183819if(update->lock) {3820if(delete_ref_loose(update->lock, update->type, err)) {3821 ret = TRANSACTION_GENERIC_ERROR;3822goto cleanup;3823}38243825if(!(update->flags & REF_ISPRUNING))3826string_list_append(&refs_to_delete,3827 update->lock->ref_name);3828}3829}38303831if(repack_without_refs(&refs_to_delete, err)) {3832 ret = TRANSACTION_GENERIC_ERROR;3833goto cleanup;3834}3835for_each_string_list_item(ref_to_delete, &refs_to_delete)3836unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3837clear_loose_ref_cache(&ref_cache);38383839cleanup:3840 transaction->state = REF_TRANSACTION_CLOSED;38413842for(i =0; i < n; i++)3843if(updates[i]->lock)3844unlock_ref(updates[i]->lock);3845string_list_clear(&refs_to_delete,0);3846return ret;3847}38483849char*shorten_unambiguous_ref(const char*refname,int strict)3850{3851int i;3852static char**scanf_fmts;3853static int nr_rules;3854char*short_name;38553856if(!nr_rules) {3857/*3858 * Pre-generate scanf formats from ref_rev_parse_rules[].3859 * Generate a format suitable for scanf from a3860 * ref_rev_parse_rules rule by interpolating "%s" at the3861 * location of the "%.*s".3862 */3863size_t total_len =0;3864size_t offset =0;38653866/* the rule list is NULL terminated, count them first */3867for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3868/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3869 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38703871 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38723873 offset =0;3874for(i =0; i < nr_rules; i++) {3875assert(offset < total_len);3876 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3877 offset +=snprintf(scanf_fmts[i], total_len - offset,3878 ref_rev_parse_rules[i],2,"%s") +1;3879}3880}38813882/* bail out if there are no rules */3883if(!nr_rules)3884returnxstrdup(refname);38853886/* buffer for scanf result, at most refname must fit */3887 short_name =xstrdup(refname);38883889/* skip first rule, it will always match */3890for(i = nr_rules -1; i >0; --i) {3891int j;3892int rules_to_fail = i;3893int short_name_len;38943895if(1!=sscanf(refname, scanf_fmts[i], short_name))3896continue;38973898 short_name_len =strlen(short_name);38993900/*3901 * in strict mode, all (except the matched one) rules3902 * must fail to resolve to a valid non-ambiguous ref3903 */3904if(strict)3905 rules_to_fail = nr_rules;39063907/*3908 * check if the short name resolves to a valid ref,3909 * but use only rules prior to the matched one3910 */3911for(j =0; j < rules_to_fail; j++) {3912const char*rule = ref_rev_parse_rules[j];3913char refname[PATH_MAX];39143915/* skip matched rule */3916if(i == j)3917continue;39183919/*3920 * the short name is ambiguous, if it resolves3921 * (with this previous rule) to a valid ref3922 * read_ref() returns 0 on success3923 */3924mksnpath(refname,sizeof(refname),3925 rule, short_name_len, short_name);3926if(ref_exists(refname))3927break;3928}39293930/*3931 * short name is non-ambiguous if all previous rules3932 * haven't resolved to a valid ref3933 */3934if(j == rules_to_fail)3935return short_name;3936}39373938free(short_name);3939returnxstrdup(refname);3940}39413942static struct string_list *hide_refs;39433944intparse_hide_refs_config(const char*var,const char*value,const char*section)3945{3946if(!strcmp("transfer.hiderefs", var) ||3947/* NEEDSWORK: use parse_config_key() once both are merged */3948(starts_with(var, section) && var[strlen(section)] =='.'&&3949!strcmp(var +strlen(section),".hiderefs"))) {3950char*ref;3951int len;39523953if(!value)3954returnconfig_error_nonbool(var);3955 ref =xstrdup(value);3956 len =strlen(ref);3957while(len && ref[len -1] =='/')3958 ref[--len] ='\0';3959if(!hide_refs) {3960 hide_refs =xcalloc(1,sizeof(*hide_refs));3961 hide_refs->strdup_strings =1;3962}3963string_list_append(hide_refs, ref);3964}3965return0;3966}39673968intref_is_hidden(const char*refname)3969{3970struct string_list_item *item;39713972if(!hide_refs)3973return0;3974for_each_string_list_item(item, hide_refs) {3975int len;3976if(!starts_with(refname, item->string))3977continue;3978 len =strlen(item->string);3979if(!refname[len] || refname[len] =='/')3980return1;3981}3982return0;3983}39843985struct expire_reflog_cb {3986unsigned int flags;3987 reflog_expiry_should_prune_fn *should_prune_fn;3988void*policy_cb;3989FILE*newlog;3990unsigned char last_kept_sha1[20];3991};39923993static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3994const char*email,unsigned long timestamp,int tz,3995const char*message,void*cb_data)3996{3997struct expire_reflog_cb *cb = cb_data;3998struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;39994000if(cb->flags & EXPIRE_REFLOGS_REWRITE)4001 osha1 = cb->last_kept_sha1;40024003if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4004 message, policy_cb)) {4005if(!cb->newlog)4006printf("would prune%s", message);4007else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4008printf("prune%s", message);4009}else{4010if(cb->newlog) {4011fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4012sha1_to_hex(osha1),sha1_to_hex(nsha1),4013 email, timestamp, tz, message);4014hashcpy(cb->last_kept_sha1, nsha1);4015}4016if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4017printf("keep%s", message);4018}4019return0;4020}40214022intreflog_expire(const char*refname,const unsigned char*sha1,4023unsigned int flags,4024 reflog_expiry_prepare_fn prepare_fn,4025 reflog_expiry_should_prune_fn should_prune_fn,4026 reflog_expiry_cleanup_fn cleanup_fn,4027void*policy_cb_data)4028{4029static struct lock_file reflog_lock;4030struct expire_reflog_cb cb;4031struct ref_lock *lock;4032char*log_file;4033int status =0;40344035memset(&cb,0,sizeof(cb));4036 cb.flags = flags;4037 cb.policy_cb = policy_cb_data;4038 cb.should_prune_fn = should_prune_fn;40394040/*4041 * The reflog file is locked by holding the lock on the4042 * reference itself, plus we might need to update the4043 * reference if --updateref was specified:4044 */4045 lock =lock_ref_sha1_basic(refname, sha1, NULL,0, NULL);4046if(!lock)4047returnerror("cannot lock ref '%s'", refname);4048if(!reflog_exists(refname)) {4049unlock_ref(lock);4050return0;4051}40524053 log_file =git_pathdup("logs/%s", refname);4054if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4055/*4056 * Even though holding $GIT_DIR/logs/$reflog.lock has4057 * no locking implications, we use the lock_file4058 * machinery here anyway because it does a lot of the4059 * work we need, including cleaning up if the program4060 * exits unexpectedly.4061 */4062if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4063struct strbuf err = STRBUF_INIT;4064unable_to_lock_message(log_file, errno, &err);4065error("%s", err.buf);4066strbuf_release(&err);4067goto failure;4068}4069 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4070if(!cb.newlog) {4071error("cannot fdopen%s(%s)",4072 reflog_lock.filename.buf,strerror(errno));4073goto failure;4074}4075}40764077(*prepare_fn)(refname, sha1, cb.policy_cb);4078for_each_reflog_ent(refname, expire_reflog_ent, &cb);4079(*cleanup_fn)(cb.policy_cb);40804081if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4082if(close_lock_file(&reflog_lock)) {4083 status |=error("couldn't write%s:%s", log_file,4084strerror(errno));4085}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&4086(write_in_full(lock->lock_fd,4087sha1_to_hex(cb.last_kept_sha1),40) !=40||4088write_str_in_full(lock->lock_fd,"\n") !=1||4089close_ref(lock) <0)) {4090 status |=error("couldn't write%s",4091 lock->lk->filename.buf);4092rollback_lock_file(&reflog_lock);4093}else if(commit_lock_file(&reflog_lock)) {4094 status |=error("unable to commit reflog '%s' (%s)",4095 log_file,strerror(errno));4096}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&commit_ref(lock)) {4097 status |=error("couldn't set%s", lock->ref_name);4098}4099}4100free(log_file);4101unlock_ref(lock);4102return status;41034104 failure:4105rollback_lock_file(&reflog_lock);4106free(log_file);4107unlock_ref(lock);4108return-1;4109}