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 9/* 10 * How to handle various characters in refnames: 11 * 0: An acceptable character for refs 12 * 1: End-of-component 13 * 2: ., look for a preceding . to reject .. in refs 14 * 3: {, look for a preceding @ to reject @{ in refs 15 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 16 */ 17static unsigned char refname_disposition[256] = { 181,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 194,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 204,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 210,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 220,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 230,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 250,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 26}; 27 28/* 29 * Used as a flag to ref_transaction_delete when a loose ref is being 30 * pruned. 31 */ 32#define REF_ISPRUNING 0x0100 33/* 34 * Try to read one refname component from the front of refname. 35 * Return the length of the component found, or -1 if the component is 36 * not legal. It is legal if it is something reasonable to have under 37 * ".git/refs/"; We do not like it if: 38 * 39 * - any path component of it begins with ".", or 40 * - it has double dots "..", or 41 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 42 * - it ends with a "/". 43 * - it ends with ".lock" 44 * - it contains a "\" (backslash) 45 */ 46static intcheck_refname_component(const char*refname,int flags) 47{ 48const char*cp; 49char last ='\0'; 50 51for(cp = refname; ; cp++) { 52int ch = *cp &255; 53unsigned char disp = refname_disposition[ch]; 54switch(disp) { 55case1: 56goto out; 57case2: 58if(last =='.') 59return-1;/* Refname contains "..". */ 60break; 61case3: 62if(last =='@') 63return-1;/* Refname contains "@{". */ 64break; 65case4: 66return-1; 67} 68 last = ch; 69} 70out: 71if(cp == refname) 72return0;/* Component has zero length. */ 73if(refname[0] =='.') { 74if(!(flags & REFNAME_DOT_COMPONENT)) 75return-1;/* Component starts with '.'. */ 76/* 77 * Even if leading dots are allowed, don't allow "." 78 * as a component (".." is prevented by a rule above). 79 */ 80if(refname[1] =='\0') 81return-1;/* Component equals ".". */ 82} 83if(cp - refname >= LOCK_SUFFIX_LEN && 84!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 85return-1;/* Refname ends with ".lock". */ 86return cp - refname; 87} 88 89intcheck_refname_format(const char*refname,int flags) 90{ 91int component_len, component_count =0; 92 93if(!strcmp(refname,"@")) 94/* Refname is a single character '@'. */ 95return-1; 96 97while(1) { 98/* We are at the start of a path component. */ 99 component_len =check_refname_component(refname, flags); 100if(component_len <=0) { 101if((flags & REFNAME_REFSPEC_PATTERN) && 102 refname[0] =='*'&& 103(refname[1] =='\0'|| refname[1] =='/')) { 104/* Accept one wildcard as a full refname component. */ 105 flags &= ~REFNAME_REFSPEC_PATTERN; 106 component_len =1; 107}else{ 108return-1; 109} 110} 111 component_count++; 112if(refname[component_len] =='\0') 113break; 114/* Skip to next component. */ 115 refname += component_len +1; 116} 117 118if(refname[component_len -1] =='.') 119return-1;/* Refname ends with '.'. */ 120if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 121return-1;/* Refname has only one component. */ 122return0; 123} 124 125struct ref_entry; 126 127/* 128 * Information used (along with the information in ref_entry) to 129 * describe a single cached reference. This data structure only 130 * occurs embedded in a union in struct ref_entry, and only when 131 * (ref_entry->flag & REF_DIR) is zero. 132 */ 133struct ref_value { 134/* 135 * The name of the object to which this reference resolves 136 * (which may be a tag object). If REF_ISBROKEN, this is 137 * null. If REF_ISSYMREF, then this is the name of the object 138 * referred to by the last reference in the symlink chain. 139 */ 140unsigned char sha1[20]; 141 142/* 143 * If REF_KNOWS_PEELED, then this field holds the peeled value 144 * of this reference, or null if the reference is known not to 145 * be peelable. See the documentation for peel_ref() for an 146 * exact definition of "peelable". 147 */ 148unsigned char peeled[20]; 149}; 150 151struct ref_cache; 152 153/* 154 * Information used (along with the information in ref_entry) to 155 * describe a level in the hierarchy of references. This data 156 * structure only occurs embedded in a union in struct ref_entry, and 157 * only when (ref_entry.flag & REF_DIR) is set. In that case, 158 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 159 * in the directory have already been read: 160 * 161 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 162 * or packed references, already read. 163 * 164 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 165 * references that hasn't been read yet (nor has any of its 166 * subdirectories). 167 * 168 * Entries within a directory are stored within a growable array of 169 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 170 * sorted are sorted by their component name in strcmp() order and the 171 * remaining entries are unsorted. 172 * 173 * Loose references are read lazily, one directory at a time. When a 174 * directory of loose references is read, then all of the references 175 * in that directory are stored, and REF_INCOMPLETE stubs are created 176 * for any subdirectories, but the subdirectories themselves are not 177 * read. The reading is triggered by get_ref_dir(). 178 */ 179struct ref_dir { 180int nr, alloc; 181 182/* 183 * Entries with index 0 <= i < sorted are sorted by name. New 184 * entries are appended to the list unsorted, and are sorted 185 * only when required; thus we avoid the need to sort the list 186 * after the addition of every reference. 187 */ 188int sorted; 189 190/* A pointer to the ref_cache that contains this ref_dir. */ 191struct ref_cache *ref_cache; 192 193struct ref_entry **entries; 194}; 195 196/* 197 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 198 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see 199 * refs.h. 200 */ 201 202/* 203 * The field ref_entry->u.value.peeled of this value entry contains 204 * the correct peeled value for the reference, which might be 205 * null_sha1 if the reference is not a tag or if it is broken. 206 */ 207#define REF_KNOWS_PEELED 0x08 208 209/* ref_entry represents a directory of references */ 210#define REF_DIR 0x10 211 212/* 213 * Entry has not yet been read from disk (used only for REF_DIR 214 * entries representing loose references) 215 */ 216#define REF_INCOMPLETE 0x20 217 218/* 219 * A ref_entry represents either a reference or a "subdirectory" of 220 * references. 221 * 222 * Each directory in the reference namespace is represented by a 223 * ref_entry with (flags & REF_DIR) set and containing a subdir member 224 * that holds the entries in that directory that have been read so 225 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 226 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 227 * used for loose reference directories. 228 * 229 * References are represented by a ref_entry with (flags & REF_DIR) 230 * unset and a value member that describes the reference's value. The 231 * flag member is at the ref_entry level, but it is also needed to 232 * interpret the contents of the value field (in other words, a 233 * ref_value object is not very much use without the enclosing 234 * ref_entry). 235 * 236 * Reference names cannot end with slash and directories' names are 237 * always stored with a trailing slash (except for the top-level 238 * directory, which is always denoted by ""). This has two nice 239 * consequences: (1) when the entries in each subdir are sorted 240 * lexicographically by name (as they usually are), the references in 241 * a whole tree can be generated in lexicographic order by traversing 242 * the tree in left-to-right, depth-first order; (2) the names of 243 * references and subdirectories cannot conflict, and therefore the 244 * presence of an empty subdirectory does not block the creation of a 245 * similarly-named reference. (The fact that reference names with the 246 * same leading components can conflict *with each other* is a 247 * separate issue that is regulated by is_refname_available().) 248 * 249 * Please note that the name field contains the fully-qualified 250 * reference (or subdirectory) name. Space could be saved by only 251 * storing the relative names. But that would require the full names 252 * to be generated on the fly when iterating in do_for_each_ref(), and 253 * would break callback functions, who have always been able to assume 254 * that the name strings that they are passed will not be freed during 255 * the iteration. 256 */ 257struct ref_entry { 258unsigned char flag;/* ISSYMREF? ISPACKED? */ 259union{ 260struct ref_value value;/* if not (flags&REF_DIR) */ 261struct ref_dir subdir;/* if (flags&REF_DIR) */ 262} u; 263/* 264 * The full name of the reference (e.g., "refs/heads/master") 265 * or the full name of the directory with a trailing slash 266 * (e.g., "refs/heads/"): 267 */ 268char name[FLEX_ARRAY]; 269}; 270 271static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 272 273static struct ref_dir *get_ref_dir(struct ref_entry *entry) 274{ 275struct ref_dir *dir; 276assert(entry->flag & REF_DIR); 277 dir = &entry->u.subdir; 278if(entry->flag & REF_INCOMPLETE) { 279read_loose_refs(entry->name, dir); 280 entry->flag &= ~REF_INCOMPLETE; 281} 282return dir; 283} 284 285static struct ref_entry *create_ref_entry(const char*refname, 286const unsigned char*sha1,int flag, 287int check_name) 288{ 289int len; 290struct ref_entry *ref; 291 292if(check_name && 293check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 294die("Reference has invalid format: '%s'", refname); 295 len =strlen(refname) +1; 296 ref =xmalloc(sizeof(struct ref_entry) + len); 297hashcpy(ref->u.value.sha1, sha1); 298hashclr(ref->u.value.peeled); 299memcpy(ref->name, refname, len); 300 ref->flag = flag; 301return ref; 302} 303 304static voidclear_ref_dir(struct ref_dir *dir); 305 306static voidfree_ref_entry(struct ref_entry *entry) 307{ 308if(entry->flag & REF_DIR) { 309/* 310 * Do not use get_ref_dir() here, as that might 311 * trigger the reading of loose refs. 312 */ 313clear_ref_dir(&entry->u.subdir); 314} 315free(entry); 316} 317 318/* 319 * Add a ref_entry to the end of dir (unsorted). Entry is always 320 * stored directly in dir; no recursion into subdirectories is 321 * done. 322 */ 323static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 324{ 325ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 326 dir->entries[dir->nr++] = entry; 327/* optimize for the case that entries are added in order */ 328if(dir->nr ==1|| 329(dir->nr == dir->sorted +1&& 330strcmp(dir->entries[dir->nr -2]->name, 331 dir->entries[dir->nr -1]->name) <0)) 332 dir->sorted = dir->nr; 333} 334 335/* 336 * Clear and free all entries in dir, recursively. 337 */ 338static voidclear_ref_dir(struct ref_dir *dir) 339{ 340int i; 341for(i =0; i < dir->nr; i++) 342free_ref_entry(dir->entries[i]); 343free(dir->entries); 344 dir->sorted = dir->nr = dir->alloc =0; 345 dir->entries = NULL; 346} 347 348/* 349 * Create a struct ref_entry object for the specified dirname. 350 * dirname is the name of the directory with a trailing slash (e.g., 351 * "refs/heads/") or "" for the top-level directory. 352 */ 353static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 354const char*dirname,size_t len, 355int incomplete) 356{ 357struct ref_entry *direntry; 358 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 359memcpy(direntry->name, dirname, len); 360 direntry->name[len] ='\0'; 361 direntry->u.subdir.ref_cache = ref_cache; 362 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 363return direntry; 364} 365 366static intref_entry_cmp(const void*a,const void*b) 367{ 368struct ref_entry *one = *(struct ref_entry **)a; 369struct ref_entry *two = *(struct ref_entry **)b; 370returnstrcmp(one->name, two->name); 371} 372 373static voidsort_ref_dir(struct ref_dir *dir); 374 375struct string_slice { 376size_t len; 377const char*str; 378}; 379 380static intref_entry_cmp_sslice(const void*key_,const void*ent_) 381{ 382const struct string_slice *key = key_; 383const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 384int cmp =strncmp(key->str, ent->name, key->len); 385if(cmp) 386return cmp; 387return'\0'- (unsigned char)ent->name[key->len]; 388} 389 390/* 391 * Return the index of the entry with the given refname from the 392 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 393 * no such entry is found. dir must already be complete. 394 */ 395static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 396{ 397struct ref_entry **r; 398struct string_slice key; 399 400if(refname == NULL || !dir->nr) 401return-1; 402 403sort_ref_dir(dir); 404 key.len = len; 405 key.str = refname; 406 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 407 ref_entry_cmp_sslice); 408 409if(r == NULL) 410return-1; 411 412return r - dir->entries; 413} 414 415/* 416 * Search for a directory entry directly within dir (without 417 * recursing). Sort dir if necessary. subdirname must be a directory 418 * name (i.e., end in '/'). If mkdir is set, then create the 419 * directory if it is missing; otherwise, return NULL if the desired 420 * directory cannot be found. dir must already be complete. 421 */ 422static struct ref_dir *search_for_subdir(struct ref_dir *dir, 423const char*subdirname,size_t len, 424int mkdir) 425{ 426int entry_index =search_ref_dir(dir, subdirname, len); 427struct ref_entry *entry; 428if(entry_index == -1) { 429if(!mkdir) 430return NULL; 431/* 432 * Since dir is complete, the absence of a subdir 433 * means that the subdir really doesn't exist; 434 * therefore, create an empty record for it but mark 435 * the record complete. 436 */ 437 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 438add_entry_to_dir(dir, entry); 439}else{ 440 entry = dir->entries[entry_index]; 441} 442returnget_ref_dir(entry); 443} 444 445/* 446 * If refname is a reference name, find the ref_dir within the dir 447 * tree that should hold refname. If refname is a directory name 448 * (i.e., ends in '/'), then return that ref_dir itself. dir must 449 * represent the top-level directory and must already be complete. 450 * Sort ref_dirs and recurse into subdirectories as necessary. If 451 * mkdir is set, then create any missing directories; otherwise, 452 * return NULL if the desired directory cannot be found. 453 */ 454static struct ref_dir *find_containing_dir(struct ref_dir *dir, 455const char*refname,int mkdir) 456{ 457const char*slash; 458for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 459size_t dirnamelen = slash - refname +1; 460struct ref_dir *subdir; 461 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 462if(!subdir) { 463 dir = NULL; 464break; 465} 466 dir = subdir; 467} 468 469return dir; 470} 471 472/* 473 * Find the value entry with the given name in dir, sorting ref_dirs 474 * and recursing into subdirectories as necessary. If the name is not 475 * found or it corresponds to a directory entry, return NULL. 476 */ 477static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 478{ 479int entry_index; 480struct ref_entry *entry; 481 dir =find_containing_dir(dir, refname,0); 482if(!dir) 483return NULL; 484 entry_index =search_ref_dir(dir, refname,strlen(refname)); 485if(entry_index == -1) 486return NULL; 487 entry = dir->entries[entry_index]; 488return(entry->flag & REF_DIR) ? NULL : entry; 489} 490 491/* 492 * Remove the entry with the given name from dir, recursing into 493 * subdirectories as necessary. If refname is the name of a directory 494 * (i.e., ends with '/'), then remove the directory and its contents. 495 * If the removal was successful, return the number of entries 496 * remaining in the directory entry that contained the deleted entry. 497 * If the name was not found, return -1. Please note that this 498 * function only deletes the entry from the cache; it does not delete 499 * it from the filesystem or ensure that other cache entries (which 500 * might be symbolic references to the removed entry) are updated. 501 * Nor does it remove any containing dir entries that might be made 502 * empty by the removal. dir must represent the top-level directory 503 * and must already be complete. 504 */ 505static intremove_entry(struct ref_dir *dir,const char*refname) 506{ 507int refname_len =strlen(refname); 508int entry_index; 509struct ref_entry *entry; 510int is_dir = refname[refname_len -1] =='/'; 511if(is_dir) { 512/* 513 * refname represents a reference directory. Remove 514 * the trailing slash; otherwise we will get the 515 * directory *representing* refname rather than the 516 * one *containing* it. 517 */ 518char*dirname =xmemdupz(refname, refname_len -1); 519 dir =find_containing_dir(dir, dirname,0); 520free(dirname); 521}else{ 522 dir =find_containing_dir(dir, refname,0); 523} 524if(!dir) 525return-1; 526 entry_index =search_ref_dir(dir, refname, refname_len); 527if(entry_index == -1) 528return-1; 529 entry = dir->entries[entry_index]; 530 531memmove(&dir->entries[entry_index], 532&dir->entries[entry_index +1], 533(dir->nr - entry_index -1) *sizeof(*dir->entries) 534); 535 dir->nr--; 536if(dir->sorted > entry_index) 537 dir->sorted--; 538free_ref_entry(entry); 539return dir->nr; 540} 541 542/* 543 * Add a ref_entry to the ref_dir (unsorted), recursing into 544 * subdirectories as necessary. dir must represent the top-level 545 * directory. Return 0 on success. 546 */ 547static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 548{ 549 dir =find_containing_dir(dir, ref->name,1); 550if(!dir) 551return-1; 552add_entry_to_dir(dir, ref); 553return0; 554} 555 556/* 557 * Emit a warning and return true iff ref1 and ref2 have the same name 558 * and the same sha1. Die if they have the same name but different 559 * sha1s. 560 */ 561static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 562{ 563if(strcmp(ref1->name, ref2->name)) 564return0; 565 566/* Duplicate name; make sure that they don't conflict: */ 567 568if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 569/* This is impossible by construction */ 570die("Reference directory conflict:%s", ref1->name); 571 572if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 573die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 574 575warning("Duplicated ref:%s", ref1->name); 576return1; 577} 578 579/* 580 * Sort the entries in dir non-recursively (if they are not already 581 * sorted) and remove any duplicate entries. 582 */ 583static voidsort_ref_dir(struct ref_dir *dir) 584{ 585int i, j; 586struct ref_entry *last = NULL; 587 588/* 589 * This check also prevents passing a zero-length array to qsort(), 590 * which is a problem on some platforms. 591 */ 592if(dir->sorted == dir->nr) 593return; 594 595qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 596 597/* Remove any duplicates: */ 598for(i =0, j =0; j < dir->nr; j++) { 599struct ref_entry *entry = dir->entries[j]; 600if(last &&is_dup_ref(last, entry)) 601free_ref_entry(entry); 602else 603 last = dir->entries[i++] = entry; 604} 605 dir->sorted = dir->nr = i; 606} 607 608/* Include broken references in a do_for_each_ref*() iteration: */ 609#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 610 611/* 612 * Return true iff the reference described by entry can be resolved to 613 * an object in the database. Emit a warning if the referred-to 614 * object does not exist. 615 */ 616static intref_resolves_to_object(struct ref_entry *entry) 617{ 618if(entry->flag & REF_ISBROKEN) 619return0; 620if(!has_sha1_file(entry->u.value.sha1)) { 621error("%sdoes not point to a valid object!", entry->name); 622return0; 623} 624return1; 625} 626 627/* 628 * current_ref is a performance hack: when iterating over references 629 * using the for_each_ref*() functions, current_ref is set to the 630 * current reference's entry before calling the callback function. If 631 * the callback function calls peel_ref(), then peel_ref() first 632 * checks whether the reference to be peeled is the current reference 633 * (it usually is) and if so, returns that reference's peeled version 634 * if it is available. This avoids a refname lookup in a common case. 635 */ 636static struct ref_entry *current_ref; 637 638typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 639 640struct ref_entry_cb { 641const char*base; 642int trim; 643int flags; 644 each_ref_fn *fn; 645void*cb_data; 646}; 647 648/* 649 * Handle one reference in a do_for_each_ref*()-style iteration, 650 * calling an each_ref_fn for each entry. 651 */ 652static intdo_one_ref(struct ref_entry *entry,void*cb_data) 653{ 654struct ref_entry_cb *data = cb_data; 655struct ref_entry *old_current_ref; 656int retval; 657 658if(!starts_with(entry->name, data->base)) 659return0; 660 661if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 662!ref_resolves_to_object(entry)) 663return0; 664 665/* Store the old value, in case this is a recursive call: */ 666 old_current_ref = current_ref; 667 current_ref = entry; 668 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 669 entry->flag, data->cb_data); 670 current_ref = old_current_ref; 671return retval; 672} 673 674/* 675 * Call fn for each reference in dir that has index in the range 676 * offset <= index < dir->nr. Recurse into subdirectories that are in 677 * that index range, sorting them before iterating. This function 678 * does not sort dir itself; it should be sorted beforehand. fn is 679 * called for all references, including broken ones. 680 */ 681static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 682 each_ref_entry_fn fn,void*cb_data) 683{ 684int i; 685assert(dir->sorted == dir->nr); 686for(i = offset; i < dir->nr; i++) { 687struct ref_entry *entry = dir->entries[i]; 688int retval; 689if(entry->flag & REF_DIR) { 690struct ref_dir *subdir =get_ref_dir(entry); 691sort_ref_dir(subdir); 692 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 693}else{ 694 retval =fn(entry, cb_data); 695} 696if(retval) 697return retval; 698} 699return0; 700} 701 702/* 703 * Call fn for each reference in the union of dir1 and dir2, in order 704 * by refname. Recurse into subdirectories. If a value entry appears 705 * in both dir1 and dir2, then only process the version that is in 706 * dir2. The input dirs must already be sorted, but subdirs will be 707 * sorted as needed. fn is called for all references, including 708 * broken ones. 709 */ 710static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 711struct ref_dir *dir2, 712 each_ref_entry_fn fn,void*cb_data) 713{ 714int retval; 715int i1 =0, i2 =0; 716 717assert(dir1->sorted == dir1->nr); 718assert(dir2->sorted == dir2->nr); 719while(1) { 720struct ref_entry *e1, *e2; 721int cmp; 722if(i1 == dir1->nr) { 723returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 724} 725if(i2 == dir2->nr) { 726returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 727} 728 e1 = dir1->entries[i1]; 729 e2 = dir2->entries[i2]; 730 cmp =strcmp(e1->name, e2->name); 731if(cmp ==0) { 732if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 733/* Both are directories; descend them in parallel. */ 734struct ref_dir *subdir1 =get_ref_dir(e1); 735struct ref_dir *subdir2 =get_ref_dir(e2); 736sort_ref_dir(subdir1); 737sort_ref_dir(subdir2); 738 retval =do_for_each_entry_in_dirs( 739 subdir1, subdir2, fn, cb_data); 740 i1++; 741 i2++; 742}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 743/* Both are references; ignore the one from dir1. */ 744 retval =fn(e2, cb_data); 745 i1++; 746 i2++; 747}else{ 748die("conflict between reference and directory:%s", 749 e1->name); 750} 751}else{ 752struct ref_entry *e; 753if(cmp <0) { 754 e = e1; 755 i1++; 756}else{ 757 e = e2; 758 i2++; 759} 760if(e->flag & REF_DIR) { 761struct ref_dir *subdir =get_ref_dir(e); 762sort_ref_dir(subdir); 763 retval =do_for_each_entry_in_dir( 764 subdir,0, fn, cb_data); 765}else{ 766 retval =fn(e, cb_data); 767} 768} 769if(retval) 770return retval; 771} 772} 773 774/* 775 * Load all of the refs from the dir into our in-memory cache. The hard work 776 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 777 * through all of the sub-directories. We do not even need to care about 778 * sorting, as traversal order does not matter to us. 779 */ 780static voidprime_ref_dir(struct ref_dir *dir) 781{ 782int i; 783for(i =0; i < dir->nr; i++) { 784struct ref_entry *entry = dir->entries[i]; 785if(entry->flag & REF_DIR) 786prime_ref_dir(get_ref_dir(entry)); 787} 788} 789 790static intentry_matches(struct ref_entry *entry,const struct string_list *list) 791{ 792return list &&string_list_has_string(list, entry->name); 793} 794 795struct nonmatching_ref_data { 796const struct string_list *skip; 797struct ref_entry *found; 798}; 799 800static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 801{ 802struct nonmatching_ref_data *data = vdata; 803 804if(entry_matches(entry, data->skip)) 805return0; 806 807 data->found = entry; 808return1; 809} 810 811static voidreport_refname_conflict(struct ref_entry *entry, 812const char*refname) 813{ 814error("'%s' exists; cannot create '%s'", entry->name, refname); 815} 816 817/* 818 * Return true iff a reference named refname could be created without 819 * conflicting with the name of an existing reference in dir. If 820 * skip is non-NULL, ignore potential conflicts with refs in skip 821 * (e.g., because they are scheduled for deletion in the same 822 * operation). 823 * 824 * Two reference names conflict if one of them exactly matches the 825 * leading components of the other; e.g., "foo/bar" conflicts with 826 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 827 * "foo/barbados". 828 * 829 * skip must be sorted. 830 */ 831static intis_refname_available(const char*refname, 832const struct string_list *skip, 833struct ref_dir *dir) 834{ 835const char*slash; 836size_t len; 837int pos; 838char*dirname; 839 840for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 841/* 842 * We are still at a leading dir of the refname; we are 843 * looking for a conflict with a leaf entry. 844 * 845 * If we find one, we still must make sure it is 846 * not in "skip". 847 */ 848 pos =search_ref_dir(dir, refname, slash - refname); 849if(pos >=0) { 850struct ref_entry *entry = dir->entries[pos]; 851if(entry_matches(entry, skip)) 852return1; 853report_refname_conflict(entry, refname); 854return0; 855} 856 857 858/* 859 * Otherwise, we can try to continue our search with 860 * the next component; if we come up empty, we know 861 * there is nothing under this whole prefix. 862 */ 863 pos =search_ref_dir(dir, refname, slash +1- refname); 864if(pos <0) 865return1; 866 867 dir =get_ref_dir(dir->entries[pos]); 868} 869 870/* 871 * We are at the leaf of our refname; we want to 872 * make sure there are no directories which match it. 873 */ 874 len =strlen(refname); 875 dirname =xmallocz(len +1); 876sprintf(dirname,"%s/", refname); 877 pos =search_ref_dir(dir, dirname, len +1); 878free(dirname); 879 880if(pos >=0) { 881/* 882 * We found a directory named "refname". It is a 883 * problem iff it contains any ref that is not 884 * in "skip". 885 */ 886struct ref_entry *entry = dir->entries[pos]; 887struct ref_dir *dir =get_ref_dir(entry); 888struct nonmatching_ref_data data; 889 890 data.skip = skip; 891sort_ref_dir(dir); 892if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 893return1; 894 895report_refname_conflict(data.found, refname); 896return0; 897} 898 899/* 900 * There is no point in searching for another leaf 901 * node which matches it; such an entry would be the 902 * ref we are looking for, not a conflict. 903 */ 904return1; 905} 906 907struct packed_ref_cache { 908struct ref_entry *root; 909 910/* 911 * Count of references to the data structure in this instance, 912 * including the pointer from ref_cache::packed if any. The 913 * data will not be freed as long as the reference count is 914 * nonzero. 915 */ 916unsigned int referrers; 917 918/* 919 * Iff the packed-refs file associated with this instance is 920 * currently locked for writing, this points at the associated 921 * lock (which is owned by somebody else). The referrer count 922 * is also incremented when the file is locked and decremented 923 * when it is unlocked. 924 */ 925struct lock_file *lock; 926 927/* The metadata from when this packed-refs cache was read */ 928struct stat_validity validity; 929}; 930 931/* 932 * Future: need to be in "struct repository" 933 * when doing a full libification. 934 */ 935static struct ref_cache { 936struct ref_cache *next; 937struct ref_entry *loose; 938struct packed_ref_cache *packed; 939/* 940 * The submodule name, or "" for the main repo. We allocate 941 * length 1 rather than FLEX_ARRAY so that the main ref_cache 942 * is initialized correctly. 943 */ 944char name[1]; 945} ref_cache, *submodule_ref_caches; 946 947/* Lock used for the main packed-refs file: */ 948static struct lock_file packlock; 949 950/* 951 * Increment the reference count of *packed_refs. 952 */ 953static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 954{ 955 packed_refs->referrers++; 956} 957 958/* 959 * Decrease the reference count of *packed_refs. If it goes to zero, 960 * free *packed_refs and return true; otherwise return false. 961 */ 962static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 963{ 964if(!--packed_refs->referrers) { 965free_ref_entry(packed_refs->root); 966stat_validity_clear(&packed_refs->validity); 967free(packed_refs); 968return1; 969}else{ 970return0; 971} 972} 973 974static voidclear_packed_ref_cache(struct ref_cache *refs) 975{ 976if(refs->packed) { 977struct packed_ref_cache *packed_refs = refs->packed; 978 979if(packed_refs->lock) 980die("internal error: packed-ref cache cleared while locked"); 981 refs->packed = NULL; 982release_packed_ref_cache(packed_refs); 983} 984} 985 986static voidclear_loose_ref_cache(struct ref_cache *refs) 987{ 988if(refs->loose) { 989free_ref_entry(refs->loose); 990 refs->loose = NULL; 991} 992} 993 994static struct ref_cache *create_ref_cache(const char*submodule) 995{ 996int len; 997struct ref_cache *refs; 998if(!submodule) 999 submodule ="";1000 len =strlen(submodule) +1;1001 refs =xcalloc(1,sizeof(struct ref_cache) + len);1002memcpy(refs->name, submodule, len);1003return refs;1004}10051006/*1007 * Return a pointer to a ref_cache for the specified submodule. For1008 * the main repository, use submodule==NULL. The returned structure1009 * will be allocated and initialized but not necessarily populated; it1010 * should not be freed.1011 */1012static struct ref_cache *get_ref_cache(const char*submodule)1013{1014struct ref_cache *refs;10151016if(!submodule || !*submodule)1017return&ref_cache;10181019for(refs = submodule_ref_caches; refs; refs = refs->next)1020if(!strcmp(submodule, refs->name))1021return refs;10221023 refs =create_ref_cache(submodule);1024 refs->next = submodule_ref_caches;1025 submodule_ref_caches = refs;1026return refs;1027}10281029/* The length of a peeled reference line in packed-refs, including EOL: */1030#define PEELED_LINE_LENGTH 4210311032/*1033 * The packed-refs header line that we write out. Perhaps other1034 * traits will be added later. The trailing space is required.1035 */1036static const char PACKED_REFS_HEADER[] =1037"# pack-refs with: peeled fully-peeled\n";10381039/*1040 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1041 * Return a pointer to the refname within the line (null-terminated),1042 * or NULL if there was a problem.1043 */1044static const char*parse_ref_line(char*line,unsigned char*sha1)1045{1046/*1047 * 42: the answer to everything.1048 *1049 * In this case, it happens to be the answer to1050 * 40 (length of sha1 hex representation)1051 * +1 (space in between hex and name)1052 * +1 (newline at the end of the line)1053 */1054int len =strlen(line) -42;10551056if(len <=0)1057return NULL;1058if(get_sha1_hex(line, sha1) <0)1059return NULL;1060if(!isspace(line[40]))1061return NULL;1062 line +=41;1063if(isspace(*line))1064return NULL;1065if(line[len] !='\n')1066return NULL;1067 line[len] =0;10681069return line;1070}10711072/*1073 * Read f, which is a packed-refs file, into dir.1074 *1075 * A comment line of the form "# pack-refs with: " may contain zero or1076 * more traits. We interpret the traits as follows:1077 *1078 * No traits:1079 *1080 * Probably no references are peeled. But if the file contains a1081 * peeled value for a reference, we will use it.1082 *1083 * peeled:1084 *1085 * References under "refs/tags/", if they *can* be peeled, *are*1086 * peeled in this file. References outside of "refs/tags/" are1087 * probably not peeled even if they could have been, but if we find1088 * a peeled value for such a reference we will use it.1089 *1090 * fully-peeled:1091 *1092 * All references in the file that can be peeled are peeled.1093 * Inversely (and this is more important), any references in the1094 * file for which no peeled value is recorded is not peelable. This1095 * trait should typically be written alongside "peeled" for1096 * compatibility with older clients, but we do not require it1097 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1098 */1099static voidread_packed_refs(FILE*f,struct ref_dir *dir)1100{1101struct ref_entry *last = NULL;1102char refline[PATH_MAX];1103enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11041105while(fgets(refline,sizeof(refline), f)) {1106unsigned char sha1[20];1107const char*refname;1108static const char header[] ="# pack-refs with:";11091110if(!strncmp(refline, header,sizeof(header)-1)) {1111const char*traits = refline +sizeof(header) -1;1112if(strstr(traits," fully-peeled "))1113 peeled = PEELED_FULLY;1114else if(strstr(traits," peeled "))1115 peeled = PEELED_TAGS;1116/* perhaps other traits later as well */1117continue;1118}11191120 refname =parse_ref_line(refline, sha1);1121if(refname) {1122 last =create_ref_entry(refname, sha1, REF_ISPACKED,1);1123if(peeled == PEELED_FULLY ||1124(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1125 last->flag |= REF_KNOWS_PEELED;1126add_ref(dir, last);1127continue;1128}1129if(last &&1130 refline[0] =='^'&&1131strlen(refline) == PEELED_LINE_LENGTH &&1132 refline[PEELED_LINE_LENGTH -1] =='\n'&&1133!get_sha1_hex(refline +1, sha1)) {1134hashcpy(last->u.value.peeled, sha1);1135/*1136 * Regardless of what the file header said,1137 * we definitely know the value of *this*1138 * reference:1139 */1140 last->flag |= REF_KNOWS_PEELED;1141}1142}1143}11441145/*1146 * Get the packed_ref_cache for the specified ref_cache, creating it1147 * if necessary.1148 */1149static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1150{1151const char*packed_refs_file;11521153if(*refs->name)1154 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1155else1156 packed_refs_file =git_path("packed-refs");11571158if(refs->packed &&1159!stat_validity_check(&refs->packed->validity, packed_refs_file))1160clear_packed_ref_cache(refs);11611162if(!refs->packed) {1163FILE*f;11641165 refs->packed =xcalloc(1,sizeof(*refs->packed));1166acquire_packed_ref_cache(refs->packed);1167 refs->packed->root =create_dir_entry(refs,"",0,0);1168 f =fopen(packed_refs_file,"r");1169if(f) {1170stat_validity_update(&refs->packed->validity,fileno(f));1171read_packed_refs(f,get_ref_dir(refs->packed->root));1172fclose(f);1173}1174}1175return refs->packed;1176}11771178static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1179{1180returnget_ref_dir(packed_ref_cache->root);1181}11821183static struct ref_dir *get_packed_refs(struct ref_cache *refs)1184{1185returnget_packed_ref_dir(get_packed_ref_cache(refs));1186}11871188voidadd_packed_ref(const char*refname,const unsigned char*sha1)1189{1190struct packed_ref_cache *packed_ref_cache =1191get_packed_ref_cache(&ref_cache);11921193if(!packed_ref_cache->lock)1194die("internal error: packed refs not locked");1195add_ref(get_packed_ref_dir(packed_ref_cache),1196create_ref_entry(refname, sha1, REF_ISPACKED,1));1197}11981199/*1200 * Read the loose references from the namespace dirname into dir1201 * (without recursing). dirname must end with '/'. dir must be the1202 * directory entry corresponding to dirname.1203 */1204static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1205{1206struct ref_cache *refs = dir->ref_cache;1207DIR*d;1208const char*path;1209struct dirent *de;1210int dirnamelen =strlen(dirname);1211struct strbuf refname;12121213if(*refs->name)1214 path =git_path_submodule(refs->name,"%s", dirname);1215else1216 path =git_path("%s", dirname);12171218 d =opendir(path);1219if(!d)1220return;12211222strbuf_init(&refname, dirnamelen +257);1223strbuf_add(&refname, dirname, dirnamelen);12241225while((de =readdir(d)) != NULL) {1226unsigned char sha1[20];1227struct stat st;1228int flag;1229const char*refdir;12301231if(de->d_name[0] =='.')1232continue;1233if(ends_with(de->d_name,".lock"))1234continue;1235strbuf_addstr(&refname, de->d_name);1236 refdir = *refs->name1237?git_path_submodule(refs->name,"%s", refname.buf)1238:git_path("%s", refname.buf);1239if(stat(refdir, &st) <0) {1240;/* silently ignore */1241}else if(S_ISDIR(st.st_mode)) {1242strbuf_addch(&refname,'/');1243add_entry_to_dir(dir,1244create_dir_entry(refs, refname.buf,1245 refname.len,1));1246}else{1247if(*refs->name) {1248hashclr(sha1);1249 flag =0;1250if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1251hashclr(sha1);1252 flag |= REF_ISBROKEN;1253}1254}else if(read_ref_full(refname.buf, sha1,1, &flag)) {1255hashclr(sha1);1256 flag |= REF_ISBROKEN;1257}1258add_entry_to_dir(dir,1259create_ref_entry(refname.buf, sha1, flag,1));1260}1261strbuf_setlen(&refname, dirnamelen);1262}1263strbuf_release(&refname);1264closedir(d);1265}12661267static struct ref_dir *get_loose_refs(struct ref_cache *refs)1268{1269if(!refs->loose) {1270/*1271 * Mark the top-level directory complete because we1272 * are about to read the only subdirectory that can1273 * hold references:1274 */1275 refs->loose =create_dir_entry(refs,"",0,0);1276/*1277 * Create an incomplete entry for "refs/":1278 */1279add_entry_to_dir(get_ref_dir(refs->loose),1280create_dir_entry(refs,"refs/",5,1));1281}1282returnget_ref_dir(refs->loose);1283}12841285/* We allow "recursive" symbolic refs. Only within reason, though */1286#define MAXDEPTH 51287#define MAXREFLEN (1024)12881289/*1290 * Called by resolve_gitlink_ref_recursive() after it failed to read1291 * from the loose refs in ref_cache refs. Find <refname> in the1292 * packed-refs file for the submodule.1293 */1294static intresolve_gitlink_packed_ref(struct ref_cache *refs,1295const char*refname,unsigned char*sha1)1296{1297struct ref_entry *ref;1298struct ref_dir *dir =get_packed_refs(refs);12991300 ref =find_ref(dir, refname);1301if(ref == NULL)1302return-1;13031304hashcpy(sha1, ref->u.value.sha1);1305return0;1306}13071308static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1309const char*refname,unsigned char*sha1,1310int recursion)1311{1312int fd, len;1313char buffer[128], *p;1314char*path;13151316if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1317return-1;1318 path = *refs->name1319?git_path_submodule(refs->name,"%s", refname)1320:git_path("%s", refname);1321 fd =open(path, O_RDONLY);1322if(fd <0)1323returnresolve_gitlink_packed_ref(refs, refname, sha1);13241325 len =read(fd, buffer,sizeof(buffer)-1);1326close(fd);1327if(len <0)1328return-1;1329while(len &&isspace(buffer[len-1]))1330 len--;1331 buffer[len] =0;13321333/* Was it a detached head or an old-fashioned symlink? */1334if(!get_sha1_hex(buffer, sha1))1335return0;13361337/* Symref? */1338if(strncmp(buffer,"ref:",4))1339return-1;1340 p = buffer +4;1341while(isspace(*p))1342 p++;13431344returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1345}13461347intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1348{1349int len =strlen(path), retval;1350char*submodule;1351struct ref_cache *refs;13521353while(len && path[len-1] =='/')1354 len--;1355if(!len)1356return-1;1357 submodule =xstrndup(path, len);1358 refs =get_ref_cache(submodule);1359free(submodule);13601361 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1362return retval;1363}13641365/*1366 * Return the ref_entry for the given refname from the packed1367 * references. If it does not exist, return NULL.1368 */1369static struct ref_entry *get_packed_ref(const char*refname)1370{1371returnfind_ref(get_packed_refs(&ref_cache), refname);1372}13731374/*1375 * A loose ref file doesn't exist; check for a packed ref. The1376 * options are forwarded from resolve_safe_unsafe().1377 */1378static const char*handle_missing_loose_ref(const char*refname,1379unsigned char*sha1,1380int reading,1381int*flag)1382{1383struct ref_entry *entry;13841385/*1386 * The loose reference file does not exist; check for a packed1387 * reference.1388 */1389 entry =get_packed_ref(refname);1390if(entry) {1391hashcpy(sha1, entry->u.value.sha1);1392if(flag)1393*flag |= REF_ISPACKED;1394return refname;1395}1396/* The reference is not a packed reference, either. */1397if(reading) {1398return NULL;1399}else{1400hashclr(sha1);1401return refname;1402}1403}14041405/* This function needs to return a meaningful errno on failure */1406const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1407{1408int depth = MAXDEPTH;1409 ssize_t len;1410char buffer[256];1411static char refname_buffer[256];14121413if(flag)1414*flag =0;14151416if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1417 errno = EINVAL;1418return NULL;1419}14201421for(;;) {1422char path[PATH_MAX];1423struct stat st;1424char*buf;1425int fd;14261427if(--depth <0) {1428 errno = ELOOP;1429return NULL;1430}14311432git_snpath(path,sizeof(path),"%s", refname);14331434/*1435 * We might have to loop back here to avoid a race1436 * condition: first we lstat() the file, then we try1437 * to read it as a link or as a file. But if somebody1438 * changes the type of the file (file <-> directory1439 * <-> symlink) between the lstat() and reading, then1440 * we don't want to report that as an error but rather1441 * try again starting with the lstat().1442 */1443 stat_ref:1444if(lstat(path, &st) <0) {1445if(errno == ENOENT)1446returnhandle_missing_loose_ref(refname, sha1,1447 reading, flag);1448else1449return NULL;1450}14511452/* Follow "normalized" - ie "refs/.." symlinks by hand */1453if(S_ISLNK(st.st_mode)) {1454 len =readlink(path, buffer,sizeof(buffer)-1);1455if(len <0) {1456if(errno == ENOENT || errno == EINVAL)1457/* inconsistent with lstat; retry */1458goto stat_ref;1459else1460return NULL;1461}1462 buffer[len] =0;1463if(starts_with(buffer,"refs/") &&1464!check_refname_format(buffer,0)) {1465strcpy(refname_buffer, buffer);1466 refname = refname_buffer;1467if(flag)1468*flag |= REF_ISSYMREF;1469continue;1470}1471}14721473/* Is it a directory? */1474if(S_ISDIR(st.st_mode)) {1475 errno = EISDIR;1476return NULL;1477}14781479/*1480 * Anything else, just open it and try to use it as1481 * a ref1482 */1483 fd =open(path, O_RDONLY);1484if(fd <0) {1485if(errno == ENOENT)1486/* inconsistent with lstat; retry */1487goto stat_ref;1488else1489return NULL;1490}1491 len =read_in_full(fd, buffer,sizeof(buffer)-1);1492if(len <0) {1493int save_errno = errno;1494close(fd);1495 errno = save_errno;1496return NULL;1497}1498close(fd);1499while(len &&isspace(buffer[len-1]))1500 len--;1501 buffer[len] ='\0';15021503/*1504 * Is it a symbolic ref?1505 */1506if(!starts_with(buffer,"ref:")) {1507/*1508 * Please note that FETCH_HEAD has a second1509 * line containing other data.1510 */1511if(get_sha1_hex(buffer, sha1) ||1512(buffer[40] !='\0'&& !isspace(buffer[40]))) {1513if(flag)1514*flag |= REF_ISBROKEN;1515 errno = EINVAL;1516return NULL;1517}1518return refname;1519}1520if(flag)1521*flag |= REF_ISSYMREF;1522 buf = buffer +4;1523while(isspace(*buf))1524 buf++;1525if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1526if(flag)1527*flag |= REF_ISBROKEN;1528 errno = EINVAL;1529return NULL;1530}1531 refname =strcpy(refname_buffer, buf);1532}1533}15341535char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1536{1537const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1538return ret ?xstrdup(ret) : NULL;1539}15401541/* The argument to filter_refs */1542struct ref_filter {1543const char*pattern;1544 each_ref_fn *fn;1545void*cb_data;1546};15471548intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1549{1550if(resolve_ref_unsafe(refname, sha1, reading, flags))1551return0;1552return-1;1553}15541555intread_ref(const char*refname,unsigned char*sha1)1556{1557returnread_ref_full(refname, sha1,1, NULL);1558}15591560intref_exists(const char*refname)1561{1562unsigned char sha1[20];1563return!!resolve_ref_unsafe(refname, sha1,1, NULL);1564}15651566static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1567void*data)1568{1569struct ref_filter *filter = (struct ref_filter *)data;1570if(wildmatch(filter->pattern, refname,0, NULL))1571return0;1572return filter->fn(refname, sha1, flags, filter->cb_data);1573}15741575enum peel_status {1576/* object was peeled successfully: */1577 PEEL_PEELED =0,15781579/*1580 * object cannot be peeled because the named object (or an1581 * object referred to by a tag in the peel chain), does not1582 * exist.1583 */1584 PEEL_INVALID = -1,15851586/* object cannot be peeled because it is not a tag: */1587 PEEL_NON_TAG = -2,15881589/* ref_entry contains no peeled value because it is a symref: */1590 PEEL_IS_SYMREF = -3,15911592/*1593 * ref_entry cannot be peeled because it is broken (i.e., the1594 * symbolic reference cannot even be resolved to an object1595 * name):1596 */1597 PEEL_BROKEN = -41598};15991600/*1601 * Peel the named object; i.e., if the object is a tag, resolve the1602 * tag recursively until a non-tag is found. If successful, store the1603 * result to sha1 and return PEEL_PEELED. If the object is not a tag1604 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1605 * and leave sha1 unchanged.1606 */1607static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1608{1609struct object *o =lookup_unknown_object(name);16101611if(o->type == OBJ_NONE) {1612int type =sha1_object_info(name, NULL);1613if(type <0|| !object_as_type(o, type,0))1614return PEEL_INVALID;1615}16161617if(o->type != OBJ_TAG)1618return PEEL_NON_TAG;16191620 o =deref_tag_noverify(o);1621if(!o)1622return PEEL_INVALID;16231624hashcpy(sha1, o->sha1);1625return PEEL_PEELED;1626}16271628/*1629 * Peel the entry (if possible) and return its new peel_status. If1630 * repeel is true, re-peel the entry even if there is an old peeled1631 * value that is already stored in it.1632 *1633 * It is OK to call this function with a packed reference entry that1634 * might be stale and might even refer to an object that has since1635 * been garbage-collected. In such a case, if the entry has1636 * REF_KNOWS_PEELED then leave the status unchanged and return1637 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1638 */1639static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1640{1641enum peel_status status;16421643if(entry->flag & REF_KNOWS_PEELED) {1644if(repeel) {1645 entry->flag &= ~REF_KNOWS_PEELED;1646hashclr(entry->u.value.peeled);1647}else{1648returnis_null_sha1(entry->u.value.peeled) ?1649 PEEL_NON_TAG : PEEL_PEELED;1650}1651}1652if(entry->flag & REF_ISBROKEN)1653return PEEL_BROKEN;1654if(entry->flag & REF_ISSYMREF)1655return PEEL_IS_SYMREF;16561657 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1658if(status == PEEL_PEELED || status == PEEL_NON_TAG)1659 entry->flag |= REF_KNOWS_PEELED;1660return status;1661}16621663intpeel_ref(const char*refname,unsigned char*sha1)1664{1665int flag;1666unsigned char base[20];16671668if(current_ref && (current_ref->name == refname1669|| !strcmp(current_ref->name, refname))) {1670if(peel_entry(current_ref,0))1671return-1;1672hashcpy(sha1, current_ref->u.value.peeled);1673return0;1674}16751676if(read_ref_full(refname, base,1, &flag))1677return-1;16781679/*1680 * If the reference is packed, read its ref_entry from the1681 * cache in the hope that we already know its peeled value.1682 * We only try this optimization on packed references because1683 * (a) forcing the filling of the loose reference cache could1684 * be expensive and (b) loose references anyway usually do not1685 * have REF_KNOWS_PEELED.1686 */1687if(flag & REF_ISPACKED) {1688struct ref_entry *r =get_packed_ref(refname);1689if(r) {1690if(peel_entry(r,0))1691return-1;1692hashcpy(sha1, r->u.value.peeled);1693return0;1694}1695}16961697returnpeel_object(base, sha1);1698}16991700struct warn_if_dangling_data {1701FILE*fp;1702const char*refname;1703const struct string_list *refnames;1704const char*msg_fmt;1705};17061707static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1708int flags,void*cb_data)1709{1710struct warn_if_dangling_data *d = cb_data;1711const char*resolves_to;1712unsigned char junk[20];17131714if(!(flags & REF_ISSYMREF))1715return0;17161717 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1718if(!resolves_to1719|| (d->refname1720?strcmp(resolves_to, d->refname)1721: !string_list_has_string(d->refnames, resolves_to))) {1722return0;1723}17241725fprintf(d->fp, d->msg_fmt, refname);1726fputc('\n', d->fp);1727return0;1728}17291730voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1731{1732struct warn_if_dangling_data data;17331734 data.fp = fp;1735 data.refname = refname;1736 data.refnames = NULL;1737 data.msg_fmt = msg_fmt;1738for_each_rawref(warn_if_dangling_symref, &data);1739}17401741voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1742{1743struct warn_if_dangling_data data;17441745 data.fp = fp;1746 data.refname = NULL;1747 data.refnames = refnames;1748 data.msg_fmt = msg_fmt;1749for_each_rawref(warn_if_dangling_symref, &data);1750}17511752/*1753 * Call fn for each reference in the specified ref_cache, omitting1754 * references not in the containing_dir of base. fn is called for all1755 * references, including broken ones. If fn ever returns a non-zero1756 * value, stop the iteration and return that value; otherwise, return1757 * 0.1758 */1759static intdo_for_each_entry(struct ref_cache *refs,const char*base,1760 each_ref_entry_fn fn,void*cb_data)1761{1762struct packed_ref_cache *packed_ref_cache;1763struct ref_dir *loose_dir;1764struct ref_dir *packed_dir;1765int retval =0;17661767/*1768 * We must make sure that all loose refs are read before accessing the1769 * packed-refs file; this avoids a race condition in which loose refs1770 * are migrated to the packed-refs file by a simultaneous process, but1771 * our in-memory view is from before the migration. get_packed_ref_cache()1772 * takes care of making sure our view is up to date with what is on1773 * disk.1774 */1775 loose_dir =get_loose_refs(refs);1776if(base && *base) {1777 loose_dir =find_containing_dir(loose_dir, base,0);1778}1779if(loose_dir)1780prime_ref_dir(loose_dir);17811782 packed_ref_cache =get_packed_ref_cache(refs);1783acquire_packed_ref_cache(packed_ref_cache);1784 packed_dir =get_packed_ref_dir(packed_ref_cache);1785if(base && *base) {1786 packed_dir =find_containing_dir(packed_dir, base,0);1787}17881789if(packed_dir && loose_dir) {1790sort_ref_dir(packed_dir);1791sort_ref_dir(loose_dir);1792 retval =do_for_each_entry_in_dirs(1793 packed_dir, loose_dir, fn, cb_data);1794}else if(packed_dir) {1795sort_ref_dir(packed_dir);1796 retval =do_for_each_entry_in_dir(1797 packed_dir,0, fn, cb_data);1798}else if(loose_dir) {1799sort_ref_dir(loose_dir);1800 retval =do_for_each_entry_in_dir(1801 loose_dir,0, fn, cb_data);1802}18031804release_packed_ref_cache(packed_ref_cache);1805return retval;1806}18071808/*1809 * Call fn for each reference in the specified ref_cache for which the1810 * refname begins with base. If trim is non-zero, then trim that many1811 * characters off the beginning of each refname before passing the1812 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1813 * broken references in the iteration. If fn ever returns a non-zero1814 * value, stop the iteration and return that value; otherwise, return1815 * 0.1816 */1817static intdo_for_each_ref(struct ref_cache *refs,const char*base,1818 each_ref_fn fn,int trim,int flags,void*cb_data)1819{1820struct ref_entry_cb data;1821 data.base = base;1822 data.trim = trim;1823 data.flags = flags;1824 data.fn = fn;1825 data.cb_data = cb_data;18261827returndo_for_each_entry(refs, base, do_one_ref, &data);1828}18291830static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1831{1832unsigned char sha1[20];1833int flag;18341835if(submodule) {1836if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1837returnfn("HEAD", sha1,0, cb_data);18381839return0;1840}18411842if(!read_ref_full("HEAD", sha1,1, &flag))1843returnfn("HEAD", sha1, flag, cb_data);18441845return0;1846}18471848inthead_ref(each_ref_fn fn,void*cb_data)1849{1850returndo_head_ref(NULL, fn, cb_data);1851}18521853inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1854{1855returndo_head_ref(submodule, fn, cb_data);1856}18571858intfor_each_ref(each_ref_fn fn,void*cb_data)1859{1860returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1861}18621863intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1864{1865returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1866}18671868intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1869{1870returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1871}18721873intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1874 each_ref_fn fn,void*cb_data)1875{1876returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1877}18781879intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1880{1881returnfor_each_ref_in("refs/tags/", fn, cb_data);1882}18831884intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1885{1886returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1887}18881889intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1890{1891returnfor_each_ref_in("refs/heads/", fn, cb_data);1892}18931894intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1895{1896returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1897}18981899intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1900{1901returnfor_each_ref_in("refs/remotes/", fn, cb_data);1902}19031904intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1905{1906returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1907}19081909intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1910{1911returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);1912}19131914inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1915{1916struct strbuf buf = STRBUF_INIT;1917int ret =0;1918unsigned char sha1[20];1919int flag;19201921strbuf_addf(&buf,"%sHEAD",get_git_namespace());1922if(!read_ref_full(buf.buf, sha1,1, &flag))1923 ret =fn(buf.buf, sha1, flag, cb_data);1924strbuf_release(&buf);19251926return ret;1927}19281929intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1930{1931struct strbuf buf = STRBUF_INIT;1932int ret;1933strbuf_addf(&buf,"%srefs/",get_git_namespace());1934 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1935strbuf_release(&buf);1936return ret;1937}19381939intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1940const char*prefix,void*cb_data)1941{1942struct strbuf real_pattern = STRBUF_INIT;1943struct ref_filter filter;1944int ret;19451946if(!prefix && !starts_with(pattern,"refs/"))1947strbuf_addstr(&real_pattern,"refs/");1948else if(prefix)1949strbuf_addstr(&real_pattern, prefix);1950strbuf_addstr(&real_pattern, pattern);19511952if(!has_glob_specials(pattern)) {1953/* Append implied '/' '*' if not present. */1954if(real_pattern.buf[real_pattern.len -1] !='/')1955strbuf_addch(&real_pattern,'/');1956/* No need to check for '*', there is none. */1957strbuf_addch(&real_pattern,'*');1958}19591960 filter.pattern = real_pattern.buf;1961 filter.fn = fn;1962 filter.cb_data = cb_data;1963 ret =for_each_ref(filter_refs, &filter);19641965strbuf_release(&real_pattern);1966return ret;1967}19681969intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1970{1971returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1972}19731974intfor_each_rawref(each_ref_fn fn,void*cb_data)1975{1976returndo_for_each_ref(&ref_cache,"", fn,0,1977 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1978}19791980const char*prettify_refname(const char*name)1981{1982return name + (1983starts_with(name,"refs/heads/") ?11:1984starts_with(name,"refs/tags/") ?10:1985starts_with(name,"refs/remotes/") ?13:19860);1987}19881989static const char*ref_rev_parse_rules[] = {1990"%.*s",1991"refs/%.*s",1992"refs/tags/%.*s",1993"refs/heads/%.*s",1994"refs/remotes/%.*s",1995"refs/remotes/%.*s/HEAD",1996 NULL1997};19981999intrefname_match(const char*abbrev_name,const char*full_name)2000{2001const char**p;2002const int abbrev_name_len =strlen(abbrev_name);20032004for(p = ref_rev_parse_rules; *p; p++) {2005if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2006return1;2007}2008}20092010return0;2011}20122013/* This function should make sure errno is meaningful on error */2014static struct ref_lock *verify_lock(struct ref_lock *lock,2015const unsigned char*old_sha1,int mustexist)2016{2017if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {2018int save_errno = errno;2019error("Can't verify ref%s", lock->ref_name);2020unlock_ref(lock);2021 errno = save_errno;2022return NULL;2023}2024if(hashcmp(lock->old_sha1, old_sha1)) {2025error("Ref%sis at%sbut expected%s", lock->ref_name,2026sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2027unlock_ref(lock);2028 errno = EBUSY;2029return NULL;2030}2031return lock;2032}20332034static intremove_empty_directories(const char*file)2035{2036/* we want to create a file but there is a directory there;2037 * if that is an empty directory (or a directory that contains2038 * only empty directories), remove them.2039 */2040struct strbuf path;2041int result, save_errno;20422043strbuf_init(&path,20);2044strbuf_addstr(&path, file);20452046 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2047 save_errno = errno;20482049strbuf_release(&path);2050 errno = save_errno;20512052return result;2053}20542055/*2056 * *string and *len will only be substituted, and *string returned (for2057 * later free()ing) if the string passed in is a magic short-hand form2058 * to name a branch.2059 */2060static char*substitute_branch_name(const char**string,int*len)2061{2062struct strbuf buf = STRBUF_INIT;2063int ret =interpret_branch_name(*string, *len, &buf);20642065if(ret == *len) {2066size_t size;2067*string =strbuf_detach(&buf, &size);2068*len = size;2069return(char*)*string;2070}20712072return NULL;2073}20742075intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2076{2077char*last_branch =substitute_branch_name(&str, &len);2078const char**p, *r;2079int refs_found =0;20802081*ref = NULL;2082for(p = ref_rev_parse_rules; *p; p++) {2083char fullref[PATH_MAX];2084unsigned char sha1_from_ref[20];2085unsigned char*this_result;2086int flag;20872088 this_result = refs_found ? sha1_from_ref : sha1;2089mksnpath(fullref,sizeof(fullref), *p, len, str);2090 r =resolve_ref_unsafe(fullref, this_result,1, &flag);2091if(r) {2092if(!refs_found++)2093*ref =xstrdup(r);2094if(!warn_ambiguous_refs)2095break;2096}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2097warning("ignoring dangling symref%s.", fullref);2098}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2099warning("ignoring broken ref%s.", fullref);2100}2101}2102free(last_branch);2103return refs_found;2104}21052106intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2107{2108char*last_branch =substitute_branch_name(&str, &len);2109const char**p;2110int logs_found =0;21112112*log = NULL;2113for(p = ref_rev_parse_rules; *p; p++) {2114unsigned char hash[20];2115char path[PATH_MAX];2116const char*ref, *it;21172118mksnpath(path,sizeof(path), *p, len, str);2119 ref =resolve_ref_unsafe(path, hash,1, NULL);2120if(!ref)2121continue;2122if(reflog_exists(path))2123 it = path;2124else if(strcmp(ref, path) &&reflog_exists(ref))2125 it = ref;2126else2127continue;2128if(!logs_found++) {2129*log =xstrdup(it);2130hashcpy(sha1, hash);2131}2132if(!warn_ambiguous_refs)2133break;2134}2135free(last_branch);2136return logs_found;2137}21382139/*2140 * Locks a ref returning the lock on success and NULL on failure.2141 * On failure errno is set to something meaningful.2142 */2143static struct ref_lock *lock_ref_sha1_basic(const char*refname,2144const unsigned char*old_sha1,2145const struct string_list *skip,2146int flags,int*type_p)2147{2148char*ref_file;2149const char*orig_refname = refname;2150struct ref_lock *lock;2151int last_errno =0;2152int type, lflags;2153int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2154int missing =0;2155int attempts_remaining =3;21562157if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {2158 errno = EINVAL;2159return NULL;2160}21612162 lock =xcalloc(1,sizeof(struct ref_lock));2163 lock->lock_fd = -1;21642165 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);2166if(!refname && errno == EISDIR) {2167/* we are trying to lock foo but we used to2168 * have foo/bar which now does not exist;2169 * it is normal for the empty directory 'foo'2170 * to remain.2171 */2172 ref_file =git_path("%s", orig_refname);2173if(remove_empty_directories(ref_file)) {2174 last_errno = errno;2175error("there are still refs under '%s'", orig_refname);2176goto error_return;2177}2178 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);2179}2180if(type_p)2181*type_p = type;2182if(!refname) {2183 last_errno = errno;2184error("unable to resolve reference%s:%s",2185 orig_refname,strerror(errno));2186goto error_return;2187}2188 missing =is_null_sha1(lock->old_sha1);2189/* When the ref did not exist and we are creating it,2190 * make sure there is no existing ref that is packed2191 * whose name begins with our refname, nor a ref whose2192 * name is a proper prefix of our refname.2193 */2194if(missing &&2195!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2196 last_errno = ENOTDIR;2197goto error_return;2198}21992200 lock->lk =xcalloc(1,sizeof(struct lock_file));22012202 lflags =0;2203if(flags & REF_NODEREF) {2204 refname = orig_refname;2205 lflags |= LOCK_NO_DEREF;2206}2207 lock->ref_name =xstrdup(refname);2208 lock->orig_ref_name =xstrdup(orig_refname);2209 ref_file =git_path("%s", refname);2210if(missing)2211 lock->force_write =1;2212if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2213 lock->force_write =1;22142215 retry:2216switch(safe_create_leading_directories(ref_file)) {2217case SCLD_OK:2218break;/* success */2219case SCLD_VANISHED:2220if(--attempts_remaining >0)2221goto retry;2222/* fall through */2223default:2224 last_errno = errno;2225error("unable to create directory for%s", ref_file);2226goto error_return;2227}22282229 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2230if(lock->lock_fd <0) {2231if(errno == ENOENT && --attempts_remaining >0)2232/*2233 * Maybe somebody just deleted one of the2234 * directories leading to ref_file. Try2235 * again:2236 */2237goto retry;2238else2239unable_to_lock_die(ref_file, errno);2240}2241return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;22422243 error_return:2244unlock_ref(lock);2245 errno = last_errno;2246return NULL;2247}22482249struct ref_lock *lock_any_ref_for_update(const char*refname,2250const unsigned char*old_sha1,2251int flags,int*type_p)2252{2253returnlock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);2254}22552256/*2257 * Write an entry to the packed-refs file for the specified refname.2258 * If peeled is non-NULL, write it as the entry's peeled value.2259 */2260static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2261unsigned char*peeled)2262{2263fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2264if(peeled)2265fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2266}22672268/*2269 * An each_ref_entry_fn that writes the entry to a packed-refs file.2270 */2271static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2272{2273enum peel_status peel_status =peel_entry(entry,0);22742275if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2276error("internal error:%sis not a valid packed reference!",2277 entry->name);2278write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2279 peel_status == PEEL_PEELED ?2280 entry->u.value.peeled : NULL);2281return0;2282}22832284/* This should return a meaningful errno on failure */2285intlock_packed_refs(int flags)2286{2287struct packed_ref_cache *packed_ref_cache;22882289if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2290return-1;2291/*2292 * Get the current packed-refs while holding the lock. If the2293 * packed-refs file has been modified since we last read it,2294 * this will automatically invalidate the cache and re-read2295 * the packed-refs file.2296 */2297 packed_ref_cache =get_packed_ref_cache(&ref_cache);2298 packed_ref_cache->lock = &packlock;2299/* Increment the reference count to prevent it from being freed: */2300acquire_packed_ref_cache(packed_ref_cache);2301return0;2302}23032304/*2305 * Commit the packed refs changes.2306 * On error we must make sure that errno contains a meaningful value.2307 */2308intcommit_packed_refs(void)2309{2310struct packed_ref_cache *packed_ref_cache =2311get_packed_ref_cache(&ref_cache);2312int error =0;2313int save_errno =0;2314FILE*out;23152316if(!packed_ref_cache->lock)2317die("internal error: packed-refs not locked");23182319 out =fdopen_lock_file(packed_ref_cache->lock,"w");2320if(!out)2321die_errno("unable to fdopen packed-refs descriptor");23222323fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2324do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),23250, write_packed_entry_fn, out);23262327if(commit_lock_file(packed_ref_cache->lock)) {2328 save_errno = errno;2329 error = -1;2330}2331 packed_ref_cache->lock = NULL;2332release_packed_ref_cache(packed_ref_cache);2333 errno = save_errno;2334return error;2335}23362337voidrollback_packed_refs(void)2338{2339struct packed_ref_cache *packed_ref_cache =2340get_packed_ref_cache(&ref_cache);23412342if(!packed_ref_cache->lock)2343die("internal error: packed-refs not locked");2344rollback_lock_file(packed_ref_cache->lock);2345 packed_ref_cache->lock = NULL;2346release_packed_ref_cache(packed_ref_cache);2347clear_packed_ref_cache(&ref_cache);2348}23492350struct ref_to_prune {2351struct ref_to_prune *next;2352unsigned char sha1[20];2353char name[FLEX_ARRAY];2354};23552356struct pack_refs_cb_data {2357unsigned int flags;2358struct ref_dir *packed_refs;2359struct ref_to_prune *ref_to_prune;2360};23612362/*2363 * An each_ref_entry_fn that is run over loose references only. If2364 * the loose reference can be packed, add an entry in the packed ref2365 * cache. If the reference should be pruned, also add it to2366 * ref_to_prune in the pack_refs_cb_data.2367 */2368static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2369{2370struct pack_refs_cb_data *cb = cb_data;2371enum peel_status peel_status;2372struct ref_entry *packed_entry;2373int is_tag_ref =starts_with(entry->name,"refs/tags/");23742375/* ALWAYS pack tags */2376if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2377return0;23782379/* Do not pack symbolic or broken refs: */2380if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2381return0;23822383/* Add a packed ref cache entry equivalent to the loose entry. */2384 peel_status =peel_entry(entry,1);2385if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2386die("internal error peeling reference%s(%s)",2387 entry->name,sha1_to_hex(entry->u.value.sha1));2388 packed_entry =find_ref(cb->packed_refs, entry->name);2389if(packed_entry) {2390/* Overwrite existing packed entry with info from loose entry */2391 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2392hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2393}else{2394 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2395 REF_ISPACKED | REF_KNOWS_PEELED,0);2396add_ref(cb->packed_refs, packed_entry);2397}2398hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);23992400/* Schedule the loose reference for pruning if requested. */2401if((cb->flags & PACK_REFS_PRUNE)) {2402int namelen =strlen(entry->name) +1;2403struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2404hashcpy(n->sha1, entry->u.value.sha1);2405strcpy(n->name, entry->name);2406 n->next = cb->ref_to_prune;2407 cb->ref_to_prune = n;2408}2409return0;2410}24112412/*2413 * Remove empty parents, but spare refs/ and immediate subdirs.2414 * Note: munges *name.2415 */2416static voidtry_remove_empty_parents(char*name)2417{2418char*p, *q;2419int i;2420 p = name;2421for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2422while(*p && *p !='/')2423 p++;2424/* tolerate duplicate slashes; see check_refname_format() */2425while(*p =='/')2426 p++;2427}2428for(q = p; *q; q++)2429;2430while(1) {2431while(q > p && *q !='/')2432 q--;2433while(q > p && *(q-1) =='/')2434 q--;2435if(q == p)2436break;2437*q ='\0';2438if(rmdir(git_path("%s", name)))2439break;2440}2441}24422443/* make sure nobody touched the ref, and unlink */2444static voidprune_ref(struct ref_to_prune *r)2445{2446struct ref_transaction *transaction;2447struct strbuf err = STRBUF_INIT;24482449if(check_refname_format(r->name,0))2450return;24512452 transaction =ref_transaction_begin(&err);2453if(!transaction ||2454ref_transaction_delete(transaction, r->name, r->sha1,2455 REF_ISPRUNING,1, NULL, &err) ||2456ref_transaction_commit(transaction, &err)) {2457ref_transaction_free(transaction);2458error("%s", err.buf);2459strbuf_release(&err);2460return;2461}2462ref_transaction_free(transaction);2463strbuf_release(&err);2464try_remove_empty_parents(r->name);2465}24662467static voidprune_refs(struct ref_to_prune *r)2468{2469while(r) {2470prune_ref(r);2471 r = r->next;2472}2473}24742475intpack_refs(unsigned int flags)2476{2477struct pack_refs_cb_data cbdata;24782479memset(&cbdata,0,sizeof(cbdata));2480 cbdata.flags = flags;24812482lock_packed_refs(LOCK_DIE_ON_ERROR);2483 cbdata.packed_refs =get_packed_refs(&ref_cache);24842485do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2486 pack_if_possible_fn, &cbdata);24872488if(commit_packed_refs())2489die_errno("unable to overwrite old ref-pack file");24902491prune_refs(cbdata.ref_to_prune);2492return0;2493}24942495/*2496 * If entry is no longer needed in packed-refs, add it to the string2497 * list pointed to by cb_data. Reasons for deleting entries:2498 *2499 * - Entry is broken.2500 * - Entry is overridden by a loose ref.2501 * - Entry does not point at a valid object.2502 *2503 * In the first and third cases, also emit an error message because these2504 * are indications of repository corruption.2505 */2506static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2507{2508struct string_list *refs_to_delete = cb_data;25092510if(entry->flag & REF_ISBROKEN) {2511/* This shouldn't happen to packed refs. */2512error("%sis broken!", entry->name);2513string_list_append(refs_to_delete, entry->name);2514return0;2515}2516if(!has_sha1_file(entry->u.value.sha1)) {2517unsigned char sha1[20];2518int flags;25192520if(read_ref_full(entry->name, sha1,0, &flags))2521/* We should at least have found the packed ref. */2522die("Internal error");2523if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2524/*2525 * This packed reference is overridden by a2526 * loose reference, so it is OK that its value2527 * is no longer valid; for example, it might2528 * refer to an object that has been garbage2529 * collected. For this purpose we don't even2530 * care whether the loose reference itself is2531 * invalid, broken, symbolic, etc. Silently2532 * remove the packed reference.2533 */2534string_list_append(refs_to_delete, entry->name);2535return0;2536}2537/*2538 * There is no overriding loose reference, so the fact2539 * that this reference doesn't refer to a valid object2540 * indicates some kind of repository corruption.2541 * Report the problem, then omit the reference from2542 * the output.2543 */2544error("%sdoes not point to a valid object!", entry->name);2545string_list_append(refs_to_delete, entry->name);2546return0;2547}25482549return0;2550}25512552intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2553{2554struct ref_dir *packed;2555struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2556struct string_list_item *ref_to_delete;2557int i, ret, removed =0;25582559/* Look for a packed ref */2560for(i =0; i < n; i++)2561if(get_packed_ref(refnames[i]))2562break;25632564/* Avoid locking if we have nothing to do */2565if(i == n)2566return0;/* no refname exists in packed refs */25672568if(lock_packed_refs(0)) {2569if(err) {2570unable_to_lock_message(git_path("packed-refs"), errno,2571 err);2572return-1;2573}2574unable_to_lock_error(git_path("packed-refs"), errno);2575returnerror("cannot delete '%s' from packed refs", refnames[i]);2576}2577 packed =get_packed_refs(&ref_cache);25782579/* Remove refnames from the cache */2580for(i =0; i < n; i++)2581if(remove_entry(packed, refnames[i]) != -1)2582 removed =1;2583if(!removed) {2584/*2585 * All packed entries disappeared while we were2586 * acquiring the lock.2587 */2588rollback_packed_refs();2589return0;2590}25912592/* Remove any other accumulated cruft */2593do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2594for_each_string_list_item(ref_to_delete, &refs_to_delete) {2595if(remove_entry(packed, ref_to_delete->string) == -1)2596die("internal error");2597}25982599/* Write what remains */2600 ret =commit_packed_refs();2601if(ret && err)2602strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2603strerror(errno));2604return ret;2605}26062607static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2608{2609if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2610/*2611 * loose. The loose file name is the same as the2612 * lockfile name, minus ".lock":2613 */2614char*loose_filename =get_locked_file_path(lock->lk);2615int res =unlink_or_msg(loose_filename, err);2616free(loose_filename);2617if(res)2618return1;2619}2620return0;2621}26222623intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2624{2625struct ref_transaction *transaction;2626struct strbuf err = STRBUF_INIT;26272628 transaction =ref_transaction_begin(&err);2629if(!transaction ||2630ref_transaction_delete(transaction, refname, sha1, delopt,2631 sha1 && !is_null_sha1(sha1), NULL, &err) ||2632ref_transaction_commit(transaction, &err)) {2633error("%s", err.buf);2634ref_transaction_free(transaction);2635strbuf_release(&err);2636return1;2637}2638ref_transaction_free(transaction);2639strbuf_release(&err);2640return0;2641}26422643/*2644 * People using contrib's git-new-workdir have .git/logs/refs ->2645 * /some/other/path/.git/logs/refs, and that may live on another device.2646 *2647 * IOW, to avoid cross device rename errors, the temporary renamed log must2648 * live into logs/refs.2649 */2650#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"26512652static intrename_tmp_log(const char*newrefname)2653{2654int attempts_remaining =4;26552656 retry:2657switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2658case SCLD_OK:2659break;/* success */2660case SCLD_VANISHED:2661if(--attempts_remaining >0)2662goto retry;2663/* fall through */2664default:2665error("unable to create directory for%s", newrefname);2666return-1;2667}26682669if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2670if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2671/*2672 * rename(a, b) when b is an existing2673 * directory ought to result in ISDIR, but2674 * Solaris 5.8 gives ENOTDIR. Sheesh.2675 */2676if(remove_empty_directories(git_path("logs/%s", newrefname))) {2677error("Directory not empty: logs/%s", newrefname);2678return-1;2679}2680goto retry;2681}else if(errno == ENOENT && --attempts_remaining >0) {2682/*2683 * Maybe another process just deleted one of2684 * the directories in the path to newrefname.2685 * Try again from the beginning.2686 */2687goto retry;2688}else{2689error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2690 newrefname,strerror(errno));2691return-1;2692}2693}2694return0;2695}26962697static intrename_ref_available(const char*oldname,const char*newname)2698{2699struct string_list skip = STRING_LIST_INIT_NODUP;2700int ret;27012702string_list_insert(&skip, oldname);2703 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2704&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2705string_list_clear(&skip,0);2706return ret;2707}27082709intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2710{2711unsigned char sha1[20], orig_sha1[20];2712int flag =0, logmoved =0;2713struct ref_lock *lock;2714struct stat loginfo;2715int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2716const char*symref = NULL;27172718if(log &&S_ISLNK(loginfo.st_mode))2719returnerror("reflog for%sis a symlink", oldrefname);27202721 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);2722if(flag & REF_ISSYMREF)2723returnerror("refname%sis a symbolic ref, renaming it is not supported",2724 oldrefname);2725if(!symref)2726returnerror("refname%snot found", oldrefname);27272728if(!rename_ref_available(oldrefname, newrefname))2729return1;27302731if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2732returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2733 oldrefname,strerror(errno));27342735if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2736error("unable to delete old%s", oldrefname);2737goto rollback;2738}27392740if(!read_ref_full(newrefname, sha1,1, NULL) &&2741delete_ref(newrefname, sha1, REF_NODEREF)) {2742if(errno==EISDIR) {2743if(remove_empty_directories(git_path("%s", newrefname))) {2744error("Directory not empty:%s", newrefname);2745goto rollback;2746}2747}else{2748error("unable to delete existing%s", newrefname);2749goto rollback;2750}2751}27522753if(log &&rename_tmp_log(newrefname))2754goto rollback;27552756 logmoved = log;27572758 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2759if(!lock) {2760error("unable to lock%sfor update", newrefname);2761goto rollback;2762}2763 lock->force_write =1;2764hashcpy(lock->old_sha1, orig_sha1);2765if(write_ref_sha1(lock, orig_sha1, logmsg)) {2766error("unable to write current sha1 into%s", newrefname);2767goto rollback;2768}27692770return0;27712772 rollback:2773 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2774if(!lock) {2775error("unable to lock%sfor rollback", oldrefname);2776goto rollbacklog;2777}27782779 lock->force_write =1;2780 flag = log_all_ref_updates;2781 log_all_ref_updates =0;2782if(write_ref_sha1(lock, orig_sha1, NULL))2783error("unable to write current sha1 into%s", oldrefname);2784 log_all_ref_updates = flag;27852786 rollbacklog:2787if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2788error("unable to restore logfile%sfrom%s:%s",2789 oldrefname, newrefname,strerror(errno));2790if(!logmoved && log &&2791rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2792error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2793 oldrefname,strerror(errno));27942795return1;2796}27972798intclose_ref(struct ref_lock *lock)2799{2800if(close_lock_file(lock->lk))2801return-1;2802 lock->lock_fd = -1;2803return0;2804}28052806intcommit_ref(struct ref_lock *lock)2807{2808if(commit_lock_file(lock->lk))2809return-1;2810 lock->lock_fd = -1;2811return0;2812}28132814voidunlock_ref(struct ref_lock *lock)2815{2816/* Do not free lock->lk -- atexit() still looks at them */2817if(lock->lk)2818rollback_lock_file(lock->lk);2819free(lock->ref_name);2820free(lock->orig_ref_name);2821free(lock);2822}28232824/*2825 * copy the reflog message msg to buf, which has been allocated sufficiently2826 * large, while cleaning up the whitespaces. Especially, convert LF to space,2827 * because reflog file is one line per entry.2828 */2829static intcopy_msg(char*buf,const char*msg)2830{2831char*cp = buf;2832char c;2833int wasspace =1;28342835*cp++ ='\t';2836while((c = *msg++)) {2837if(wasspace &&isspace(c))2838continue;2839 wasspace =isspace(c);2840if(wasspace)2841 c =' ';2842*cp++ = c;2843}2844while(buf < cp &&isspace(cp[-1]))2845 cp--;2846*cp++ ='\n';2847return cp - buf;2848}28492850/* This function must set a meaningful errno on failure */2851intlog_ref_setup(const char*refname,char*logfile,int bufsize)2852{2853int logfd, oflags = O_APPEND | O_WRONLY;28542855git_snpath(logfile, bufsize,"logs/%s", refname);2856if(log_all_ref_updates &&2857(starts_with(refname,"refs/heads/") ||2858starts_with(refname,"refs/remotes/") ||2859starts_with(refname,"refs/notes/") ||2860!strcmp(refname,"HEAD"))) {2861if(safe_create_leading_directories(logfile) <0) {2862int save_errno = errno;2863error("unable to create directory for%s", logfile);2864 errno = save_errno;2865return-1;2866}2867 oflags |= O_CREAT;2868}28692870 logfd =open(logfile, oflags,0666);2871if(logfd <0) {2872if(!(oflags & O_CREAT) && errno == ENOENT)2873return0;28742875if((oflags & O_CREAT) && errno == EISDIR) {2876if(remove_empty_directories(logfile)) {2877int save_errno = errno;2878error("There are still logs under '%s'",2879 logfile);2880 errno = save_errno;2881return-1;2882}2883 logfd =open(logfile, oflags,0666);2884}28852886if(logfd <0) {2887int save_errno = errno;2888error("Unable to append to%s:%s", logfile,2889strerror(errno));2890 errno = save_errno;2891return-1;2892}2893}28942895adjust_shared_perm(logfile);2896close(logfd);2897return0;2898}28992900static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2901const unsigned char*new_sha1,const char*msg)2902{2903int logfd, result, written, oflags = O_APPEND | O_WRONLY;2904unsigned maxlen, len;2905int msglen;2906char log_file[PATH_MAX];2907char*logrec;2908const char*committer;29092910if(log_all_ref_updates <0)2911 log_all_ref_updates = !is_bare_repository();29122913 result =log_ref_setup(refname, log_file,sizeof(log_file));2914if(result)2915return result;29162917 logfd =open(log_file, oflags);2918if(logfd <0)2919return0;2920 msglen = msg ?strlen(msg) :0;2921 committer =git_committer_info(0);2922 maxlen =strlen(committer) + msglen +100;2923 logrec =xmalloc(maxlen);2924 len =sprintf(logrec,"%s %s %s\n",2925sha1_to_hex(old_sha1),2926sha1_to_hex(new_sha1),2927 committer);2928if(msglen)2929 len +=copy_msg(logrec + len -1, msg) -1;2930 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2931free(logrec);2932if(written != len) {2933int save_errno = errno;2934close(logfd);2935error("Unable to append to%s", log_file);2936 errno = save_errno;2937return-1;2938}2939if(close(logfd)) {2940int save_errno = errno;2941error("Unable to append to%s", log_file);2942 errno = save_errno;2943return-1;2944}2945return0;2946}29472948intis_branch(const char*refname)2949{2950return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");2951}29522953/* This function must return a meaningful errno */2954intwrite_ref_sha1(struct ref_lock *lock,2955const unsigned char*sha1,const char*logmsg)2956{2957static char term ='\n';2958struct object *o;29592960if(!lock) {2961 errno = EINVAL;2962return-1;2963}2964if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2965unlock_ref(lock);2966return0;2967}2968 o =parse_object(sha1);2969if(!o) {2970error("Trying to write ref%swith nonexistent object%s",2971 lock->ref_name,sha1_to_hex(sha1));2972unlock_ref(lock);2973 errno = EINVAL;2974return-1;2975}2976if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2977error("Trying to write non-commit object%sto branch%s",2978sha1_to_hex(sha1), lock->ref_name);2979unlock_ref(lock);2980 errno = EINVAL;2981return-1;2982}2983if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||2984write_in_full(lock->lock_fd, &term,1) !=1||2985close_ref(lock) <0) {2986int save_errno = errno;2987error("Couldn't write%s", lock->lk->filename.buf);2988unlock_ref(lock);2989 errno = save_errno;2990return-1;2991}2992clear_loose_ref_cache(&ref_cache);2993if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||2994(strcmp(lock->ref_name, lock->orig_ref_name) &&2995log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {2996unlock_ref(lock);2997return-1;2998}2999if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3000/*3001 * Special hack: If a branch is updated directly and HEAD3002 * points to it (may happen on the remote side of a push3003 * for example) then logically the HEAD reflog should be3004 * updated too.3005 * A generic solution implies reverse symref information,3006 * but finding all symrefs pointing to the given branch3007 * would be rather costly for this rare event (the direct3008 * update of a branch) to be worth it. So let's cheat and3009 * check with HEAD only which should cover 99% of all usage3010 * scenarios (even 100% of the default ones).3011 */3012unsigned char head_sha1[20];3013int head_flag;3014const char*head_ref;3015 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);3016if(head_ref && (head_flag & REF_ISSYMREF) &&3017!strcmp(head_ref, lock->ref_name))3018log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3019}3020if(commit_ref(lock)) {3021error("Couldn't set%s", lock->ref_name);3022unlock_ref(lock);3023return-1;3024}3025unlock_ref(lock);3026return0;3027}30283029intcreate_symref(const char*ref_target,const char*refs_heads_master,3030const char*logmsg)3031{3032const char*lockpath;3033char ref[1000];3034int fd, len, written;3035char*git_HEAD =git_pathdup("%s", ref_target);3036unsigned char old_sha1[20], new_sha1[20];30373038if(logmsg &&read_ref(ref_target, old_sha1))3039hashclr(old_sha1);30403041if(safe_create_leading_directories(git_HEAD) <0)3042returnerror("unable to create directory for%s", git_HEAD);30433044#ifndef NO_SYMLINK_HEAD3045if(prefer_symlink_refs) {3046unlink(git_HEAD);3047if(!symlink(refs_heads_master, git_HEAD))3048goto done;3049fprintf(stderr,"no symlink - falling back to symbolic ref\n");3050}3051#endif30523053 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3054if(sizeof(ref) <= len) {3055error("refname too long:%s", refs_heads_master);3056goto error_free_return;3057}3058 lockpath =mkpath("%s.lock", git_HEAD);3059 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3060if(fd <0) {3061error("Unable to open%sfor writing", lockpath);3062goto error_free_return;3063}3064 written =write_in_full(fd, ref, len);3065if(close(fd) !=0|| written != len) {3066error("Unable to write to%s", lockpath);3067goto error_unlink_return;3068}3069if(rename(lockpath, git_HEAD) <0) {3070error("Unable to create%s", git_HEAD);3071goto error_unlink_return;3072}3073if(adjust_shared_perm(git_HEAD)) {3074error("Unable to fix permissions on%s", lockpath);3075 error_unlink_return:3076unlink_or_warn(lockpath);3077 error_free_return:3078free(git_HEAD);3079return-1;3080}30813082#ifndef NO_SYMLINK_HEAD3083 done:3084#endif3085if(logmsg && !read_ref(refs_heads_master, new_sha1))3086log_ref_write(ref_target, old_sha1, new_sha1, logmsg);30873088free(git_HEAD);3089return0;3090}30913092struct read_ref_at_cb {3093const char*refname;3094unsigned long at_time;3095int cnt;3096int reccnt;3097unsigned char*sha1;3098int found_it;30993100unsigned char osha1[20];3101unsigned char nsha1[20];3102int tz;3103unsigned long date;3104char**msg;3105unsigned long*cutoff_time;3106int*cutoff_tz;3107int*cutoff_cnt;3108};31093110static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3111const char*email,unsigned long timestamp,int tz,3112const char*message,void*cb_data)3113{3114struct read_ref_at_cb *cb = cb_data;31153116 cb->reccnt++;3117 cb->tz = tz;3118 cb->date = timestamp;31193120if(timestamp <= cb->at_time || cb->cnt ==0) {3121if(cb->msg)3122*cb->msg =xstrdup(message);3123if(cb->cutoff_time)3124*cb->cutoff_time = timestamp;3125if(cb->cutoff_tz)3126*cb->cutoff_tz = tz;3127if(cb->cutoff_cnt)3128*cb->cutoff_cnt = cb->reccnt -1;3129/*3130 * we have not yet updated cb->[n|o]sha1 so they still3131 * hold the values for the previous record.3132 */3133if(!is_null_sha1(cb->osha1)) {3134hashcpy(cb->sha1, nsha1);3135if(hashcmp(cb->osha1, nsha1))3136warning("Log for ref%shas gap after%s.",3137 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3138}3139else if(cb->date == cb->at_time)3140hashcpy(cb->sha1, nsha1);3141else if(hashcmp(nsha1, cb->sha1))3142warning("Log for ref%sunexpectedly ended on%s.",3143 cb->refname,show_date(cb->date, cb->tz,3144 DATE_RFC2822));3145hashcpy(cb->osha1, osha1);3146hashcpy(cb->nsha1, nsha1);3147 cb->found_it =1;3148return1;3149}3150hashcpy(cb->osha1, osha1);3151hashcpy(cb->nsha1, nsha1);3152if(cb->cnt >0)3153 cb->cnt--;3154return0;3155}31563157static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3158const char*email,unsigned long timestamp,3159int tz,const char*message,void*cb_data)3160{3161struct read_ref_at_cb *cb = cb_data;31623163if(cb->msg)3164*cb->msg =xstrdup(message);3165if(cb->cutoff_time)3166*cb->cutoff_time = timestamp;3167if(cb->cutoff_tz)3168*cb->cutoff_tz = tz;3169if(cb->cutoff_cnt)3170*cb->cutoff_cnt = cb->reccnt;3171hashcpy(cb->sha1, osha1);3172if(is_null_sha1(cb->sha1))3173hashcpy(cb->sha1, nsha1);3174/* We just want the first entry */3175return1;3176}31773178intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3179unsigned char*sha1,char**msg,3180unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3181{3182struct read_ref_at_cb cb;31833184memset(&cb,0,sizeof(cb));3185 cb.refname = refname;3186 cb.at_time = at_time;3187 cb.cnt = cnt;3188 cb.msg = msg;3189 cb.cutoff_time = cutoff_time;3190 cb.cutoff_tz = cutoff_tz;3191 cb.cutoff_cnt = cutoff_cnt;3192 cb.sha1 = sha1;31933194for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);31953196if(!cb.reccnt) {3197if(flags & GET_SHA1_QUIETLY)3198exit(128);3199else3200die("Log for%sis empty.", refname);3201}3202if(cb.found_it)3203return0;32043205for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);32063207return1;3208}32093210intreflog_exists(const char*refname)3211{3212struct stat st;32133214return!lstat(git_path("logs/%s", refname), &st) &&3215S_ISREG(st.st_mode);3216}32173218intdelete_reflog(const char*refname)3219{3220returnremove_path(git_path("logs/%s", refname));3221}32223223static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3224{3225unsigned char osha1[20], nsha1[20];3226char*email_end, *message;3227unsigned long timestamp;3228int tz;32293230/* old SP new SP name <email> SP time TAB msg LF */3231if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3232get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3233get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3234!(email_end =strchr(sb->buf +82,'>')) ||3235 email_end[1] !=' '||3236!(timestamp =strtoul(email_end +2, &message,10)) ||3237!message || message[0] !=' '||3238(message[1] !='+'&& message[1] !='-') ||3239!isdigit(message[2]) || !isdigit(message[3]) ||3240!isdigit(message[4]) || !isdigit(message[5]))3241return0;/* corrupt? */3242 email_end[1] ='\0';3243 tz =strtol(message +1, NULL,10);3244if(message[6] !='\t')3245 message +=6;3246else3247 message +=7;3248returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3249}32503251static char*find_beginning_of_line(char*bob,char*scan)3252{3253while(bob < scan && *(--scan) !='\n')3254;/* keep scanning backwards */3255/*3256 * Return either beginning of the buffer, or LF at the end of3257 * the previous line.3258 */3259return scan;3260}32613262intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3263{3264struct strbuf sb = STRBUF_INIT;3265FILE*logfp;3266long pos;3267int ret =0, at_tail =1;32683269 logfp =fopen(git_path("logs/%s", refname),"r");3270if(!logfp)3271return-1;32723273/* Jump to the end */3274if(fseek(logfp,0, SEEK_END) <0)3275returnerror("cannot seek back reflog for%s:%s",3276 refname,strerror(errno));3277 pos =ftell(logfp);3278while(!ret &&0< pos) {3279int cnt;3280size_t nread;3281char buf[BUFSIZ];3282char*endp, *scanp;32833284/* Fill next block from the end */3285 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3286if(fseek(logfp, pos - cnt, SEEK_SET))3287returnerror("cannot seek back reflog for%s:%s",3288 refname,strerror(errno));3289 nread =fread(buf, cnt,1, logfp);3290if(nread !=1)3291returnerror("cannot read%dbytes from reflog for%s:%s",3292 cnt, refname,strerror(errno));3293 pos -= cnt;32943295 scanp = endp = buf + cnt;3296if(at_tail && scanp[-1] =='\n')3297/* Looking at the final LF at the end of the file */3298 scanp--;3299 at_tail =0;33003301while(buf < scanp) {3302/*3303 * terminating LF of the previous line, or the beginning3304 * of the buffer.3305 */3306char*bp;33073308 bp =find_beginning_of_line(buf, scanp);33093310if(*bp !='\n') {3311strbuf_splice(&sb,0,0, buf, endp - buf);3312if(pos)3313break;/* need to fill another block */3314 scanp = buf -1;/* leave loop */3315}else{3316/*3317 * (bp + 1) thru endp is the beginning of the3318 * current line we have in sb3319 */3320strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3321 scanp = bp;3322 endp = bp +1;3323}3324 ret =show_one_reflog_ent(&sb, fn, cb_data);3325strbuf_reset(&sb);3326if(ret)3327break;3328}33293330}3331if(!ret && sb.len)3332 ret =show_one_reflog_ent(&sb, fn, cb_data);33333334fclose(logfp);3335strbuf_release(&sb);3336return ret;3337}33383339intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3340{3341FILE*logfp;3342struct strbuf sb = STRBUF_INIT;3343int ret =0;33443345 logfp =fopen(git_path("logs/%s", refname),"r");3346if(!logfp)3347return-1;33483349while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3350 ret =show_one_reflog_ent(&sb, fn, cb_data);3351fclose(logfp);3352strbuf_release(&sb);3353return ret;3354}3355/*3356 * Call fn for each reflog in the namespace indicated by name. name3357 * must be empty or end with '/'. Name will be used as a scratch3358 * space, but its contents will be restored before return.3359 */3360static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3361{3362DIR*d =opendir(git_path("logs/%s", name->buf));3363int retval =0;3364struct dirent *de;3365int oldlen = name->len;33663367if(!d)3368return name->len ? errno :0;33693370while((de =readdir(d)) != NULL) {3371struct stat st;33723373if(de->d_name[0] =='.')3374continue;3375if(ends_with(de->d_name,".lock"))3376continue;3377strbuf_addstr(name, de->d_name);3378if(stat(git_path("logs/%s", name->buf), &st) <0) {3379;/* silently ignore */3380}else{3381if(S_ISDIR(st.st_mode)) {3382strbuf_addch(name,'/');3383 retval =do_for_each_reflog(name, fn, cb_data);3384}else{3385unsigned char sha1[20];3386if(read_ref_full(name->buf, sha1,0, NULL))3387 retval =error("bad ref for%s", name->buf);3388else3389 retval =fn(name->buf, sha1,0, cb_data);3390}3391if(retval)3392break;3393}3394strbuf_setlen(name, oldlen);3395}3396closedir(d);3397return retval;3398}33993400intfor_each_reflog(each_ref_fn fn,void*cb_data)3401{3402int retval;3403struct strbuf name;3404strbuf_init(&name, PATH_MAX);3405 retval =do_for_each_reflog(&name, fn, cb_data);3406strbuf_release(&name);3407return retval;3408}34093410/**3411 * Information needed for a single ref update. Set new_sha1 to the3412 * new value or to zero to delete the ref. To check the old value3413 * while locking the ref, set have_old to 1 and set old_sha1 to the3414 * value or to zero to ensure the ref does not exist before update.3415 */3416struct ref_update {3417unsigned char new_sha1[20];3418unsigned char old_sha1[20];3419int flags;/* REF_NODEREF? */3420int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3421struct ref_lock *lock;3422int type;3423char*msg;3424const char refname[FLEX_ARRAY];3425};34263427/*3428 * Transaction states.3429 * OPEN: The transaction is in a valid state and can accept new updates.3430 * An OPEN transaction can be committed.3431 * CLOSED: A closed transaction is no longer active and no other operations3432 * than free can be used on it in this state.3433 * A transaction can either become closed by successfully committing3434 * an active transaction or if there is a failure while building3435 * the transaction thus rendering it failed/inactive.3436 */3437enum ref_transaction_state {3438 REF_TRANSACTION_OPEN =0,3439 REF_TRANSACTION_CLOSED =13440};34413442/*3443 * Data structure for holding a reference transaction, which can3444 * consist of checks and updates to multiple references, carried out3445 * as atomically as possible. This structure is opaque to callers.3446 */3447struct ref_transaction {3448struct ref_update **updates;3449size_t alloc;3450size_t nr;3451enum ref_transaction_state state;3452};34533454struct ref_transaction *ref_transaction_begin(struct strbuf *err)3455{3456returnxcalloc(1,sizeof(struct ref_transaction));3457}34583459voidref_transaction_free(struct ref_transaction *transaction)3460{3461int i;34623463if(!transaction)3464return;34653466for(i =0; i < transaction->nr; i++) {3467free(transaction->updates[i]->msg);3468free(transaction->updates[i]);3469}3470free(transaction->updates);3471free(transaction);3472}34733474static struct ref_update *add_update(struct ref_transaction *transaction,3475const char*refname)3476{3477size_t len =strlen(refname);3478struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);34793480strcpy((char*)update->refname, refname);3481ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3482 transaction->updates[transaction->nr++] = update;3483return update;3484}34853486intref_transaction_update(struct ref_transaction *transaction,3487const char*refname,3488const unsigned char*new_sha1,3489const unsigned char*old_sha1,3490int flags,int have_old,const char*msg,3491struct strbuf *err)3492{3493struct ref_update *update;34943495if(transaction->state != REF_TRANSACTION_OPEN)3496die("BUG: update called for transaction that is not open");34973498if(have_old && !old_sha1)3499die("BUG: have_old is true but old_sha1 is NULL");35003501 update =add_update(transaction, refname);3502hashcpy(update->new_sha1, new_sha1);3503 update->flags = flags;3504 update->have_old = have_old;3505if(have_old)3506hashcpy(update->old_sha1, old_sha1);3507if(msg)3508 update->msg =xstrdup(msg);3509return0;3510}35113512intref_transaction_create(struct ref_transaction *transaction,3513const char*refname,3514const unsigned char*new_sha1,3515int flags,const char*msg,3516struct strbuf *err)3517{3518struct ref_update *update;35193520if(transaction->state != REF_TRANSACTION_OPEN)3521die("BUG: create called for transaction that is not open");35223523if(!new_sha1 ||is_null_sha1(new_sha1))3524die("BUG: create ref with null new_sha1");35253526 update =add_update(transaction, refname);35273528hashcpy(update->new_sha1, new_sha1);3529hashclr(update->old_sha1);3530 update->flags = flags;3531 update->have_old =1;3532if(msg)3533 update->msg =xstrdup(msg);3534return0;3535}35363537intref_transaction_delete(struct ref_transaction *transaction,3538const char*refname,3539const unsigned char*old_sha1,3540int flags,int have_old,const char*msg,3541struct strbuf *err)3542{3543struct ref_update *update;35443545if(transaction->state != REF_TRANSACTION_OPEN)3546die("BUG: delete called for transaction that is not open");35473548if(have_old && !old_sha1)3549die("BUG: have_old is true but old_sha1 is NULL");35503551 update =add_update(transaction, refname);3552 update->flags = flags;3553 update->have_old = have_old;3554if(have_old) {3555assert(!is_null_sha1(old_sha1));3556hashcpy(update->old_sha1, old_sha1);3557}3558if(msg)3559 update->msg =xstrdup(msg);3560return0;3561}35623563intupdate_ref(const char*action,const char*refname,3564const unsigned char*sha1,const unsigned char*oldval,3565int flags,enum action_on_err onerr)3566{3567struct ref_transaction *t;3568struct strbuf err = STRBUF_INIT;35693570 t =ref_transaction_begin(&err);3571if(!t ||3572ref_transaction_update(t, refname, sha1, oldval, flags,3573!!oldval, action, &err) ||3574ref_transaction_commit(t, &err)) {3575const char*str ="update_ref failed for ref '%s':%s";35763577ref_transaction_free(t);3578switch(onerr) {3579case UPDATE_REFS_MSG_ON_ERR:3580error(str, refname, err.buf);3581break;3582case UPDATE_REFS_DIE_ON_ERR:3583die(str, refname, err.buf);3584break;3585case UPDATE_REFS_QUIET_ON_ERR:3586break;3587}3588strbuf_release(&err);3589return1;3590}3591strbuf_release(&err);3592ref_transaction_free(t);3593return0;3594}35953596static intref_update_compare(const void*r1,const void*r2)3597{3598const struct ref_update *const*u1 = r1;3599const struct ref_update *const*u2 = r2;3600returnstrcmp((*u1)->refname, (*u2)->refname);3601}36023603static intref_update_reject_duplicates(struct ref_update **updates,int n,3604struct strbuf *err)3605{3606int i;3607for(i =1; i < n; i++)3608if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3609const char*str =3610"Multiple updates for ref '%s' not allowed.";3611if(err)3612strbuf_addf(err, str, updates[i]->refname);36133614return1;3615}3616return0;3617}36183619intref_transaction_commit(struct ref_transaction *transaction,3620struct strbuf *err)3621{3622int ret =0, delnum =0, i;3623const char**delnames;3624int n = transaction->nr;3625struct ref_update **updates = transaction->updates;36263627if(transaction->state != REF_TRANSACTION_OPEN)3628die("BUG: commit called for transaction that is not open");36293630if(!n) {3631 transaction->state = REF_TRANSACTION_CLOSED;3632return0;3633}36343635/* Allocate work space */3636 delnames =xmalloc(sizeof(*delnames) * n);36373638/* Copy, sort, and reject duplicate refs */3639qsort(updates, n,sizeof(*updates), ref_update_compare);3640if(ref_update_reject_duplicates(updates, n, err)) {3641 ret = TRANSACTION_GENERIC_ERROR;3642goto cleanup;3643}36443645/* Acquire all locks while verifying old values */3646for(i =0; i < n; i++) {3647struct ref_update *update = updates[i];36483649 update->lock =lock_ref_sha1_basic(update->refname,3650(update->have_old ?3651 update->old_sha1 :3652 NULL),3653 NULL,3654 update->flags,3655&update->type);3656if(!update->lock) {3657 ret = (errno == ENOTDIR)3658? TRANSACTION_NAME_CONFLICT3659: TRANSACTION_GENERIC_ERROR;3660if(err)3661strbuf_addf(err,"Cannot lock the ref '%s'.",3662 update->refname);3663goto cleanup;3664}3665}36663667/* Perform updates first so live commits remain referenced */3668for(i =0; i < n; i++) {3669struct ref_update *update = updates[i];36703671if(!is_null_sha1(update->new_sha1)) {3672if(write_ref_sha1(update->lock, update->new_sha1,3673 update->msg)) {3674 update->lock = NULL;/* freed by write_ref_sha1 */3675if(err)3676strbuf_addf(err,"Cannot update the ref '%s'.",3677 update->refname);3678 ret = TRANSACTION_GENERIC_ERROR;3679goto cleanup;3680}3681 update->lock = NULL;/* freed by write_ref_sha1 */3682}3683}36843685/* Perform deletes now that updates are safely completed */3686for(i =0; i < n; i++) {3687struct ref_update *update = updates[i];36883689if(update->lock) {3690if(delete_ref_loose(update->lock, update->type, err))3691 ret = TRANSACTION_GENERIC_ERROR;36923693if(!(update->flags & REF_ISPRUNING))3694 delnames[delnum++] = update->lock->ref_name;3695}3696}36973698if(repack_without_refs(delnames, delnum, err))3699 ret = TRANSACTION_GENERIC_ERROR;3700for(i =0; i < delnum; i++)3701unlink_or_warn(git_path("logs/%s", delnames[i]));3702clear_loose_ref_cache(&ref_cache);37033704cleanup:3705 transaction->state = REF_TRANSACTION_CLOSED;37063707for(i =0; i < n; i++)3708if(updates[i]->lock)3709unlock_ref(updates[i]->lock);3710free(delnames);3711return ret;3712}37133714char*shorten_unambiguous_ref(const char*refname,int strict)3715{3716int i;3717static char**scanf_fmts;3718static int nr_rules;3719char*short_name;37203721if(!nr_rules) {3722/*3723 * Pre-generate scanf formats from ref_rev_parse_rules[].3724 * Generate a format suitable for scanf from a3725 * ref_rev_parse_rules rule by interpolating "%s" at the3726 * location of the "%.*s".3727 */3728size_t total_len =0;3729size_t offset =0;37303731/* the rule list is NULL terminated, count them first */3732for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3733/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3734 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;37353736 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);37373738 offset =0;3739for(i =0; i < nr_rules; i++) {3740assert(offset < total_len);3741 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3742 offset +=snprintf(scanf_fmts[i], total_len - offset,3743 ref_rev_parse_rules[i],2,"%s") +1;3744}3745}37463747/* bail out if there are no rules */3748if(!nr_rules)3749returnxstrdup(refname);37503751/* buffer for scanf result, at most refname must fit */3752 short_name =xstrdup(refname);37533754/* skip first rule, it will always match */3755for(i = nr_rules -1; i >0; --i) {3756int j;3757int rules_to_fail = i;3758int short_name_len;37593760if(1!=sscanf(refname, scanf_fmts[i], short_name))3761continue;37623763 short_name_len =strlen(short_name);37643765/*3766 * in strict mode, all (except the matched one) rules3767 * must fail to resolve to a valid non-ambiguous ref3768 */3769if(strict)3770 rules_to_fail = nr_rules;37713772/*3773 * check if the short name resolves to a valid ref,3774 * but use only rules prior to the matched one3775 */3776for(j =0; j < rules_to_fail; j++) {3777const char*rule = ref_rev_parse_rules[j];3778char refname[PATH_MAX];37793780/* skip matched rule */3781if(i == j)3782continue;37833784/*3785 * the short name is ambiguous, if it resolves3786 * (with this previous rule) to a valid ref3787 * read_ref() returns 0 on success3788 */3789mksnpath(refname,sizeof(refname),3790 rule, short_name_len, short_name);3791if(ref_exists(refname))3792break;3793}37943795/*3796 * short name is non-ambiguous if all previous rules3797 * haven't resolved to a valid ref3798 */3799if(j == rules_to_fail)3800return short_name;3801}38023803free(short_name);3804returnxstrdup(refname);3805}38063807static struct string_list *hide_refs;38083809intparse_hide_refs_config(const char*var,const char*value,const char*section)3810{3811if(!strcmp("transfer.hiderefs", var) ||3812/* NEEDSWORK: use parse_config_key() once both are merged */3813(starts_with(var, section) && var[strlen(section)] =='.'&&3814!strcmp(var +strlen(section),".hiderefs"))) {3815char*ref;3816int len;38173818if(!value)3819returnconfig_error_nonbool(var);3820 ref =xstrdup(value);3821 len =strlen(ref);3822while(len && ref[len -1] =='/')3823 ref[--len] ='\0';3824if(!hide_refs) {3825 hide_refs =xcalloc(1,sizeof(*hide_refs));3826 hide_refs->strdup_strings =1;3827}3828string_list_append(hide_refs, ref);3829}3830return0;3831}38323833intref_is_hidden(const char*refname)3834{3835struct string_list_item *item;38363837if(!hide_refs)3838return0;3839for_each_string_list_item(item, hide_refs) {3840int len;3841if(!starts_with(refname, item->string))3842continue;3843 len =strlen(item->string);3844if(!refname[len] || refname[len] =='/')3845return1;3846}3847return0;3848}