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,1255 RESOLVE_REF_READING,1256 sha1, &flag)) {1257hashclr(sha1);1258 flag |= REF_ISBROKEN;1259}1260add_entry_to_dir(dir,1261create_ref_entry(refname.buf, sha1, flag,1));1262}1263strbuf_setlen(&refname, dirnamelen);1264}1265strbuf_release(&refname);1266closedir(d);1267}12681269static struct ref_dir *get_loose_refs(struct ref_cache *refs)1270{1271if(!refs->loose) {1272/*1273 * Mark the top-level directory complete because we1274 * are about to read the only subdirectory that can1275 * hold references:1276 */1277 refs->loose =create_dir_entry(refs,"",0,0);1278/*1279 * Create an incomplete entry for "refs/":1280 */1281add_entry_to_dir(get_ref_dir(refs->loose),1282create_dir_entry(refs,"refs/",5,1));1283}1284returnget_ref_dir(refs->loose);1285}12861287/* We allow "recursive" symbolic refs. Only within reason, though */1288#define MAXDEPTH 51289#define MAXREFLEN (1024)12901291/*1292 * Called by resolve_gitlink_ref_recursive() after it failed to read1293 * from the loose refs in ref_cache refs. Find <refname> in the1294 * packed-refs file for the submodule.1295 */1296static intresolve_gitlink_packed_ref(struct ref_cache *refs,1297const char*refname,unsigned char*sha1)1298{1299struct ref_entry *ref;1300struct ref_dir *dir =get_packed_refs(refs);13011302 ref =find_ref(dir, refname);1303if(ref == NULL)1304return-1;13051306hashcpy(sha1, ref->u.value.sha1);1307return0;1308}13091310static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1311const char*refname,unsigned char*sha1,1312int recursion)1313{1314int fd, len;1315char buffer[128], *p;1316char*path;13171318if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1319return-1;1320 path = *refs->name1321?git_path_submodule(refs->name,"%s", refname)1322:git_path("%s", refname);1323 fd =open(path, O_RDONLY);1324if(fd <0)1325returnresolve_gitlink_packed_ref(refs, refname, sha1);13261327 len =read(fd, buffer,sizeof(buffer)-1);1328close(fd);1329if(len <0)1330return-1;1331while(len &&isspace(buffer[len-1]))1332 len--;1333 buffer[len] =0;13341335/* Was it a detached head or an old-fashioned symlink? */1336if(!get_sha1_hex(buffer, sha1))1337return0;13381339/* Symref? */1340if(strncmp(buffer,"ref:",4))1341return-1;1342 p = buffer +4;1343while(isspace(*p))1344 p++;13451346returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1347}13481349intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1350{1351int len =strlen(path), retval;1352char*submodule;1353struct ref_cache *refs;13541355while(len && path[len-1] =='/')1356 len--;1357if(!len)1358return-1;1359 submodule =xstrndup(path, len);1360 refs =get_ref_cache(submodule);1361free(submodule);13621363 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1364return retval;1365}13661367/*1368 * Return the ref_entry for the given refname from the packed1369 * references. If it does not exist, return NULL.1370 */1371static struct ref_entry *get_packed_ref(const char*refname)1372{1373returnfind_ref(get_packed_refs(&ref_cache), refname);1374}13751376/*1377 * A loose ref file doesn't exist; check for a packed ref. The1378 * options are forwarded from resolve_safe_unsafe().1379 */1380static const char*handle_missing_loose_ref(const char*refname,1381int resolve_flags,1382unsigned char*sha1,1383int*flags)1384{1385struct ref_entry *entry;13861387/*1388 * The loose reference file does not exist; check for a packed1389 * reference.1390 */1391 entry =get_packed_ref(refname);1392if(entry) {1393hashcpy(sha1, entry->u.value.sha1);1394if(flags)1395*flags |= REF_ISPACKED;1396return refname;1397}1398/* The reference is not a packed reference, either. */1399if(resolve_flags & RESOLVE_REF_READING) {1400return NULL;1401}else{1402hashclr(sha1);1403return refname;1404}1405}14061407/* This function needs to return a meaningful errno on failure */1408const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1409{1410int depth = MAXDEPTH;1411 ssize_t len;1412char buffer[256];1413static char refname_buffer[256];14141415if(flags)1416*flags =0;14171418if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1419 errno = EINVAL;1420return NULL;1421}1422for(;;) {1423char path[PATH_MAX];1424struct stat st;1425char*buf;1426int fd;14271428if(--depth <0) {1429 errno = ELOOP;1430return NULL;1431}14321433git_snpath(path,sizeof(path),"%s", refname);14341435/*1436 * We might have to loop back here to avoid a race1437 * condition: first we lstat() the file, then we try1438 * to read it as a link or as a file. But if somebody1439 * changes the type of the file (file <-> directory1440 * <-> symlink) between the lstat() and reading, then1441 * we don't want to report that as an error but rather1442 * try again starting with the lstat().1443 */1444 stat_ref:1445if(lstat(path, &st) <0) {1446if(errno == ENOENT)1447returnhandle_missing_loose_ref(refname,1448 resolve_flags, sha1, flags);1449else1450return NULL;1451}14521453/* Follow "normalized" - ie "refs/.." symlinks by hand */1454if(S_ISLNK(st.st_mode)) {1455 len =readlink(path, buffer,sizeof(buffer)-1);1456if(len <0) {1457if(errno == ENOENT || errno == EINVAL)1458/* inconsistent with lstat; retry */1459goto stat_ref;1460else1461return NULL;1462}1463 buffer[len] =0;1464if(starts_with(buffer,"refs/") &&1465!check_refname_format(buffer,0)) {1466strcpy(refname_buffer, buffer);1467 refname = refname_buffer;1468if(flags)1469*flags |= REF_ISSYMREF;1470continue;1471}1472}14731474/* Is it a directory? */1475if(S_ISDIR(st.st_mode)) {1476 errno = EISDIR;1477return NULL;1478}14791480/*1481 * Anything else, just open it and try to use it as1482 * a ref1483 */1484 fd =open(path, O_RDONLY);1485if(fd <0) {1486if(errno == ENOENT)1487/* inconsistent with lstat; retry */1488goto stat_ref;1489else1490return NULL;1491}1492 len =read_in_full(fd, buffer,sizeof(buffer)-1);1493if(len <0) {1494int save_errno = errno;1495close(fd);1496 errno = save_errno;1497return NULL;1498}1499close(fd);1500while(len &&isspace(buffer[len-1]))1501 len--;1502 buffer[len] ='\0';15031504/*1505 * Is it a symbolic ref?1506 */1507if(!starts_with(buffer,"ref:")) {1508/*1509 * Please note that FETCH_HEAD has a second1510 * line containing other data.1511 */1512if(get_sha1_hex(buffer, sha1) ||1513(buffer[40] !='\0'&& !isspace(buffer[40]))) {1514if(flags)1515*flags |= REF_ISBROKEN;1516 errno = EINVAL;1517return NULL;1518}1519return refname;1520}1521if(flags)1522*flags |= REF_ISSYMREF;1523 buf = buffer +4;1524while(isspace(*buf))1525 buf++;1526if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1527if(flags)1528*flags |= REF_ISBROKEN;1529 errno = EINVAL;1530return NULL;1531}1532 refname =strcpy(refname_buffer, buf);1533}1534}15351536char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1537{1538const char*ret =resolve_ref_unsafe(ref, resolve_flags, sha1, flags);1539return ret ?xstrdup(ret) : NULL;1540}15411542/* The argument to filter_refs */1543struct ref_filter {1544const char*pattern;1545 each_ref_fn *fn;1546void*cb_data;1547};15481549intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1550{1551if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1552return0;1553return-1;1554}15551556intread_ref(const char*refname,unsigned char*sha1)1557{1558returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1559}15601561intref_exists(const char*refname)1562{1563unsigned char sha1[20];1564return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1565}15661567static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1568void*data)1569{1570struct ref_filter *filter = (struct ref_filter *)data;1571if(wildmatch(filter->pattern, refname,0, NULL))1572return0;1573return filter->fn(refname, sha1, flags, filter->cb_data);1574}15751576enum peel_status {1577/* object was peeled successfully: */1578 PEEL_PEELED =0,15791580/*1581 * object cannot be peeled because the named object (or an1582 * object referred to by a tag in the peel chain), does not1583 * exist.1584 */1585 PEEL_INVALID = -1,15861587/* object cannot be peeled because it is not a tag: */1588 PEEL_NON_TAG = -2,15891590/* ref_entry contains no peeled value because it is a symref: */1591 PEEL_IS_SYMREF = -3,15921593/*1594 * ref_entry cannot be peeled because it is broken (i.e., the1595 * symbolic reference cannot even be resolved to an object1596 * name):1597 */1598 PEEL_BROKEN = -41599};16001601/*1602 * Peel the named object; i.e., if the object is a tag, resolve the1603 * tag recursively until a non-tag is found. If successful, store the1604 * result to sha1 and return PEEL_PEELED. If the object is not a tag1605 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1606 * and leave sha1 unchanged.1607 */1608static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1609{1610struct object *o =lookup_unknown_object(name);16111612if(o->type == OBJ_NONE) {1613int type =sha1_object_info(name, NULL);1614if(type <0|| !object_as_type(o, type,0))1615return PEEL_INVALID;1616}16171618if(o->type != OBJ_TAG)1619return PEEL_NON_TAG;16201621 o =deref_tag_noverify(o);1622if(!o)1623return PEEL_INVALID;16241625hashcpy(sha1, o->sha1);1626return PEEL_PEELED;1627}16281629/*1630 * Peel the entry (if possible) and return its new peel_status. If1631 * repeel is true, re-peel the entry even if there is an old peeled1632 * value that is already stored in it.1633 *1634 * It is OK to call this function with a packed reference entry that1635 * might be stale and might even refer to an object that has since1636 * been garbage-collected. In such a case, if the entry has1637 * REF_KNOWS_PEELED then leave the status unchanged and return1638 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1639 */1640static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1641{1642enum peel_status status;16431644if(entry->flag & REF_KNOWS_PEELED) {1645if(repeel) {1646 entry->flag &= ~REF_KNOWS_PEELED;1647hashclr(entry->u.value.peeled);1648}else{1649returnis_null_sha1(entry->u.value.peeled) ?1650 PEEL_NON_TAG : PEEL_PEELED;1651}1652}1653if(entry->flag & REF_ISBROKEN)1654return PEEL_BROKEN;1655if(entry->flag & REF_ISSYMREF)1656return PEEL_IS_SYMREF;16571658 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1659if(status == PEEL_PEELED || status == PEEL_NON_TAG)1660 entry->flag |= REF_KNOWS_PEELED;1661return status;1662}16631664intpeel_ref(const char*refname,unsigned char*sha1)1665{1666int flag;1667unsigned char base[20];16681669if(current_ref && (current_ref->name == refname1670|| !strcmp(current_ref->name, refname))) {1671if(peel_entry(current_ref,0))1672return-1;1673hashcpy(sha1, current_ref->u.value.peeled);1674return0;1675}16761677if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1678return-1;16791680/*1681 * If the reference is packed, read its ref_entry from the1682 * cache in the hope that we already know its peeled value.1683 * We only try this optimization on packed references because1684 * (a) forcing the filling of the loose reference cache could1685 * be expensive and (b) loose references anyway usually do not1686 * have REF_KNOWS_PEELED.1687 */1688if(flag & REF_ISPACKED) {1689struct ref_entry *r =get_packed_ref(refname);1690if(r) {1691if(peel_entry(r,0))1692return-1;1693hashcpy(sha1, r->u.value.peeled);1694return0;1695}1696}16971698returnpeel_object(base, sha1);1699}17001701struct warn_if_dangling_data {1702FILE*fp;1703const char*refname;1704const struct string_list *refnames;1705const char*msg_fmt;1706};17071708static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1709int flags,void*cb_data)1710{1711struct warn_if_dangling_data *d = cb_data;1712const char*resolves_to;1713unsigned char junk[20];17141715if(!(flags & REF_ISSYMREF))1716return0;17171718 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1719if(!resolves_to1720|| (d->refname1721?strcmp(resolves_to, d->refname)1722: !string_list_has_string(d->refnames, resolves_to))) {1723return0;1724}17251726fprintf(d->fp, d->msg_fmt, refname);1727fputc('\n', d->fp);1728return0;1729}17301731voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1732{1733struct warn_if_dangling_data data;17341735 data.fp = fp;1736 data.refname = refname;1737 data.refnames = NULL;1738 data.msg_fmt = msg_fmt;1739for_each_rawref(warn_if_dangling_symref, &data);1740}17411742voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1743{1744struct warn_if_dangling_data data;17451746 data.fp = fp;1747 data.refname = NULL;1748 data.refnames = refnames;1749 data.msg_fmt = msg_fmt;1750for_each_rawref(warn_if_dangling_symref, &data);1751}17521753/*1754 * Call fn for each reference in the specified ref_cache, omitting1755 * references not in the containing_dir of base. fn is called for all1756 * references, including broken ones. If fn ever returns a non-zero1757 * value, stop the iteration and return that value; otherwise, return1758 * 0.1759 */1760static intdo_for_each_entry(struct ref_cache *refs,const char*base,1761 each_ref_entry_fn fn,void*cb_data)1762{1763struct packed_ref_cache *packed_ref_cache;1764struct ref_dir *loose_dir;1765struct ref_dir *packed_dir;1766int retval =0;17671768/*1769 * We must make sure that all loose refs are read before accessing the1770 * packed-refs file; this avoids a race condition in which loose refs1771 * are migrated to the packed-refs file by a simultaneous process, but1772 * our in-memory view is from before the migration. get_packed_ref_cache()1773 * takes care of making sure our view is up to date with what is on1774 * disk.1775 */1776 loose_dir =get_loose_refs(refs);1777if(base && *base) {1778 loose_dir =find_containing_dir(loose_dir, base,0);1779}1780if(loose_dir)1781prime_ref_dir(loose_dir);17821783 packed_ref_cache =get_packed_ref_cache(refs);1784acquire_packed_ref_cache(packed_ref_cache);1785 packed_dir =get_packed_ref_dir(packed_ref_cache);1786if(base && *base) {1787 packed_dir =find_containing_dir(packed_dir, base,0);1788}17891790if(packed_dir && loose_dir) {1791sort_ref_dir(packed_dir);1792sort_ref_dir(loose_dir);1793 retval =do_for_each_entry_in_dirs(1794 packed_dir, loose_dir, fn, cb_data);1795}else if(packed_dir) {1796sort_ref_dir(packed_dir);1797 retval =do_for_each_entry_in_dir(1798 packed_dir,0, fn, cb_data);1799}else if(loose_dir) {1800sort_ref_dir(loose_dir);1801 retval =do_for_each_entry_in_dir(1802 loose_dir,0, fn, cb_data);1803}18041805release_packed_ref_cache(packed_ref_cache);1806return retval;1807}18081809/*1810 * Call fn for each reference in the specified ref_cache for which the1811 * refname begins with base. If trim is non-zero, then trim that many1812 * characters off the beginning of each refname before passing the1813 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1814 * broken references in the iteration. If fn ever returns a non-zero1815 * value, stop the iteration and return that value; otherwise, return1816 * 0.1817 */1818static intdo_for_each_ref(struct ref_cache *refs,const char*base,1819 each_ref_fn fn,int trim,int flags,void*cb_data)1820{1821struct ref_entry_cb data;1822 data.base = base;1823 data.trim = trim;1824 data.flags = flags;1825 data.fn = fn;1826 data.cb_data = cb_data;18271828returndo_for_each_entry(refs, base, do_one_ref, &data);1829}18301831static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1832{1833unsigned char sha1[20];1834int flag;18351836if(submodule) {1837if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1838returnfn("HEAD", sha1,0, cb_data);18391840return0;1841}18421843if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1844returnfn("HEAD", sha1, flag, cb_data);18451846return0;1847}18481849inthead_ref(each_ref_fn fn,void*cb_data)1850{1851returndo_head_ref(NULL, fn, cb_data);1852}18531854inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1855{1856returndo_head_ref(submodule, fn, cb_data);1857}18581859intfor_each_ref(each_ref_fn fn,void*cb_data)1860{1861returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1862}18631864intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1865{1866returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1867}18681869intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1870{1871returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1872}18731874intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1875 each_ref_fn fn,void*cb_data)1876{1877returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1878}18791880intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1881{1882returnfor_each_ref_in("refs/tags/", fn, cb_data);1883}18841885intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1886{1887returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1888}18891890intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1891{1892returnfor_each_ref_in("refs/heads/", fn, cb_data);1893}18941895intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1896{1897returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1898}18991900intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1901{1902returnfor_each_ref_in("refs/remotes/", fn, cb_data);1903}19041905intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1906{1907returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1908}19091910intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1911{1912returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);1913}19141915inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1916{1917struct strbuf buf = STRBUF_INIT;1918int ret =0;1919unsigned char sha1[20];1920int flag;19211922strbuf_addf(&buf,"%sHEAD",get_git_namespace());1923if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))1924 ret =fn(buf.buf, sha1, flag, cb_data);1925strbuf_release(&buf);19261927return ret;1928}19291930intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1931{1932struct strbuf buf = STRBUF_INIT;1933int ret;1934strbuf_addf(&buf,"%srefs/",get_git_namespace());1935 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1936strbuf_release(&buf);1937return ret;1938}19391940intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1941const char*prefix,void*cb_data)1942{1943struct strbuf real_pattern = STRBUF_INIT;1944struct ref_filter filter;1945int ret;19461947if(!prefix && !starts_with(pattern,"refs/"))1948strbuf_addstr(&real_pattern,"refs/");1949else if(prefix)1950strbuf_addstr(&real_pattern, prefix);1951strbuf_addstr(&real_pattern, pattern);19521953if(!has_glob_specials(pattern)) {1954/* Append implied '/' '*' if not present. */1955if(real_pattern.buf[real_pattern.len -1] !='/')1956strbuf_addch(&real_pattern,'/');1957/* No need to check for '*', there is none. */1958strbuf_addch(&real_pattern,'*');1959}19601961 filter.pattern = real_pattern.buf;1962 filter.fn = fn;1963 filter.cb_data = cb_data;1964 ret =for_each_ref(filter_refs, &filter);19651966strbuf_release(&real_pattern);1967return ret;1968}19691970intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1971{1972returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1973}19741975intfor_each_rawref(each_ref_fn fn,void*cb_data)1976{1977returndo_for_each_ref(&ref_cache,"", fn,0,1978 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1979}19801981const char*prettify_refname(const char*name)1982{1983return name + (1984starts_with(name,"refs/heads/") ?11:1985starts_with(name,"refs/tags/") ?10:1986starts_with(name,"refs/remotes/") ?13:19870);1988}19891990static const char*ref_rev_parse_rules[] = {1991"%.*s",1992"refs/%.*s",1993"refs/tags/%.*s",1994"refs/heads/%.*s",1995"refs/remotes/%.*s",1996"refs/remotes/%.*s/HEAD",1997 NULL1998};19992000intrefname_match(const char*abbrev_name,const char*full_name)2001{2002const char**p;2003const int abbrev_name_len =strlen(abbrev_name);20042005for(p = ref_rev_parse_rules; *p; p++) {2006if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2007return1;2008}2009}20102011return0;2012}20132014/* This function should make sure errno is meaningful on error */2015static struct ref_lock *verify_lock(struct ref_lock *lock,2016const unsigned char*old_sha1,int mustexist)2017{2018if(read_ref_full(lock->ref_name,2019 mustexist ? RESOLVE_REF_READING :0,2020 lock->old_sha1, NULL)) {2021int save_errno = errno;2022error("Can't verify ref%s", lock->ref_name);2023unlock_ref(lock);2024 errno = save_errno;2025return NULL;2026}2027if(hashcmp(lock->old_sha1, old_sha1)) {2028error("Ref%sis at%sbut expected%s", lock->ref_name,2029sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2030unlock_ref(lock);2031 errno = EBUSY;2032return NULL;2033}2034return lock;2035}20362037static intremove_empty_directories(const char*file)2038{2039/* we want to create a file but there is a directory there;2040 * if that is an empty directory (or a directory that contains2041 * only empty directories), remove them.2042 */2043struct strbuf path;2044int result, save_errno;20452046strbuf_init(&path,20);2047strbuf_addstr(&path, file);20482049 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2050 save_errno = errno;20512052strbuf_release(&path);2053 errno = save_errno;20542055return result;2056}20572058/*2059 * *string and *len will only be substituted, and *string returned (for2060 * later free()ing) if the string passed in is a magic short-hand form2061 * to name a branch.2062 */2063static char*substitute_branch_name(const char**string,int*len)2064{2065struct strbuf buf = STRBUF_INIT;2066int ret =interpret_branch_name(*string, *len, &buf);20672068if(ret == *len) {2069size_t size;2070*string =strbuf_detach(&buf, &size);2071*len = size;2072return(char*)*string;2073}20742075return NULL;2076}20772078intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2079{2080char*last_branch =substitute_branch_name(&str, &len);2081const char**p, *r;2082int refs_found =0;20832084*ref = NULL;2085for(p = ref_rev_parse_rules; *p; p++) {2086char fullref[PATH_MAX];2087unsigned char sha1_from_ref[20];2088unsigned char*this_result;2089int flag;20902091 this_result = refs_found ? sha1_from_ref : sha1;2092mksnpath(fullref,sizeof(fullref), *p, len, str);2093 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2094 this_result, &flag);2095if(r) {2096if(!refs_found++)2097*ref =xstrdup(r);2098if(!warn_ambiguous_refs)2099break;2100}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2101warning("ignoring dangling symref%s.", fullref);2102}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2103warning("ignoring broken ref%s.", fullref);2104}2105}2106free(last_branch);2107return refs_found;2108}21092110intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2111{2112char*last_branch =substitute_branch_name(&str, &len);2113const char**p;2114int logs_found =0;21152116*log = NULL;2117for(p = ref_rev_parse_rules; *p; p++) {2118unsigned char hash[20];2119char path[PATH_MAX];2120const char*ref, *it;21212122mksnpath(path,sizeof(path), *p, len, str);2123 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2124 hash, NULL);2125if(!ref)2126continue;2127if(reflog_exists(path))2128 it = path;2129else if(strcmp(ref, path) &&reflog_exists(ref))2130 it = ref;2131else2132continue;2133if(!logs_found++) {2134*log =xstrdup(it);2135hashcpy(sha1, hash);2136}2137if(!warn_ambiguous_refs)2138break;2139}2140free(last_branch);2141return logs_found;2142}21432144/*2145 * Locks a ref returning the lock on success and NULL on failure.2146 * On failure errno is set to something meaningful.2147 */2148static struct ref_lock *lock_ref_sha1_basic(const char*refname,2149const unsigned char*old_sha1,2150const struct string_list *skip,2151int flags,int*type_p)2152{2153char*ref_file;2154const char*orig_refname = refname;2155struct ref_lock *lock;2156int last_errno =0;2157int type, lflags;2158int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2159int resolve_flags =0;2160int missing =0;2161int attempts_remaining =3;21622163if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {2164 errno = EINVAL;2165return NULL;2166}21672168 lock =xcalloc(1,sizeof(struct ref_lock));2169 lock->lock_fd = -1;21702171if(mustexist)2172 resolve_flags |= RESOLVE_REF_READING;21732174 refname =resolve_ref_unsafe(refname, resolve_flags,2175 lock->old_sha1, &type);2176if(!refname && errno == EISDIR) {2177/* we are trying to lock foo but we used to2178 * have foo/bar which now does not exist;2179 * it is normal for the empty directory 'foo'2180 * to remain.2181 */2182 ref_file =git_path("%s", orig_refname);2183if(remove_empty_directories(ref_file)) {2184 last_errno = errno;2185error("there are still refs under '%s'", orig_refname);2186goto error_return;2187}2188 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2189 lock->old_sha1, &type);2190}2191if(type_p)2192*type_p = type;2193if(!refname) {2194 last_errno = errno;2195error("unable to resolve reference%s:%s",2196 orig_refname,strerror(errno));2197goto error_return;2198}2199 missing =is_null_sha1(lock->old_sha1);2200/* When the ref did not exist and we are creating it,2201 * make sure there is no existing ref that is packed2202 * whose name begins with our refname, nor a ref whose2203 * name is a proper prefix of our refname.2204 */2205if(missing &&2206!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2207 last_errno = ENOTDIR;2208goto error_return;2209}22102211 lock->lk =xcalloc(1,sizeof(struct lock_file));22122213 lflags =0;2214if(flags & REF_NODEREF) {2215 refname = orig_refname;2216 lflags |= LOCK_NO_DEREF;2217}2218 lock->ref_name =xstrdup(refname);2219 lock->orig_ref_name =xstrdup(orig_refname);2220 ref_file =git_path("%s", refname);2221if(missing)2222 lock->force_write =1;2223if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2224 lock->force_write =1;22252226 retry:2227switch(safe_create_leading_directories(ref_file)) {2228case SCLD_OK:2229break;/* success */2230case SCLD_VANISHED:2231if(--attempts_remaining >0)2232goto retry;2233/* fall through */2234default:2235 last_errno = errno;2236error("unable to create directory for%s", ref_file);2237goto error_return;2238}22392240 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2241if(lock->lock_fd <0) {2242if(errno == ENOENT && --attempts_remaining >0)2243/*2244 * Maybe somebody just deleted one of the2245 * directories leading to ref_file. Try2246 * again:2247 */2248goto retry;2249else2250unable_to_lock_die(ref_file, errno);2251}2252return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;22532254 error_return:2255unlock_ref(lock);2256 errno = last_errno;2257return NULL;2258}22592260struct ref_lock *lock_any_ref_for_update(const char*refname,2261const unsigned char*old_sha1,2262int flags,int*type_p)2263{2264returnlock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);2265}22662267/*2268 * Write an entry to the packed-refs file for the specified refname.2269 * If peeled is non-NULL, write it as the entry's peeled value.2270 */2271static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2272unsigned char*peeled)2273{2274fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2275if(peeled)2276fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2277}22782279/*2280 * An each_ref_entry_fn that writes the entry to a packed-refs file.2281 */2282static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2283{2284enum peel_status peel_status =peel_entry(entry,0);22852286if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2287error("internal error:%sis not a valid packed reference!",2288 entry->name);2289write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2290 peel_status == PEEL_PEELED ?2291 entry->u.value.peeled : NULL);2292return0;2293}22942295/* This should return a meaningful errno on failure */2296intlock_packed_refs(int flags)2297{2298struct packed_ref_cache *packed_ref_cache;22992300if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2301return-1;2302/*2303 * Get the current packed-refs while holding the lock. If the2304 * packed-refs file has been modified since we last read it,2305 * this will automatically invalidate the cache and re-read2306 * the packed-refs file.2307 */2308 packed_ref_cache =get_packed_ref_cache(&ref_cache);2309 packed_ref_cache->lock = &packlock;2310/* Increment the reference count to prevent it from being freed: */2311acquire_packed_ref_cache(packed_ref_cache);2312return0;2313}23142315/*2316 * Commit the packed refs changes.2317 * On error we must make sure that errno contains a meaningful value.2318 */2319intcommit_packed_refs(void)2320{2321struct packed_ref_cache *packed_ref_cache =2322get_packed_ref_cache(&ref_cache);2323int error =0;2324int save_errno =0;2325FILE*out;23262327if(!packed_ref_cache->lock)2328die("internal error: packed-refs not locked");23292330 out =fdopen_lock_file(packed_ref_cache->lock,"w");2331if(!out)2332die_errno("unable to fdopen packed-refs descriptor");23332334fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2335do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),23360, write_packed_entry_fn, out);23372338if(commit_lock_file(packed_ref_cache->lock)) {2339 save_errno = errno;2340 error = -1;2341}2342 packed_ref_cache->lock = NULL;2343release_packed_ref_cache(packed_ref_cache);2344 errno = save_errno;2345return error;2346}23472348voidrollback_packed_refs(void)2349{2350struct packed_ref_cache *packed_ref_cache =2351get_packed_ref_cache(&ref_cache);23522353if(!packed_ref_cache->lock)2354die("internal error: packed-refs not locked");2355rollback_lock_file(packed_ref_cache->lock);2356 packed_ref_cache->lock = NULL;2357release_packed_ref_cache(packed_ref_cache);2358clear_packed_ref_cache(&ref_cache);2359}23602361struct ref_to_prune {2362struct ref_to_prune *next;2363unsigned char sha1[20];2364char name[FLEX_ARRAY];2365};23662367struct pack_refs_cb_data {2368unsigned int flags;2369struct ref_dir *packed_refs;2370struct ref_to_prune *ref_to_prune;2371};23722373/*2374 * An each_ref_entry_fn that is run over loose references only. If2375 * the loose reference can be packed, add an entry in the packed ref2376 * cache. If the reference should be pruned, also add it to2377 * ref_to_prune in the pack_refs_cb_data.2378 */2379static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2380{2381struct pack_refs_cb_data *cb = cb_data;2382enum peel_status peel_status;2383struct ref_entry *packed_entry;2384int is_tag_ref =starts_with(entry->name,"refs/tags/");23852386/* ALWAYS pack tags */2387if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2388return0;23892390/* Do not pack symbolic or broken refs: */2391if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2392return0;23932394/* Add a packed ref cache entry equivalent to the loose entry. */2395 peel_status =peel_entry(entry,1);2396if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2397die("internal error peeling reference%s(%s)",2398 entry->name,sha1_to_hex(entry->u.value.sha1));2399 packed_entry =find_ref(cb->packed_refs, entry->name);2400if(packed_entry) {2401/* Overwrite existing packed entry with info from loose entry */2402 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2403hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2404}else{2405 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2406 REF_ISPACKED | REF_KNOWS_PEELED,0);2407add_ref(cb->packed_refs, packed_entry);2408}2409hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);24102411/* Schedule the loose reference for pruning if requested. */2412if((cb->flags & PACK_REFS_PRUNE)) {2413int namelen =strlen(entry->name) +1;2414struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2415hashcpy(n->sha1, entry->u.value.sha1);2416strcpy(n->name, entry->name);2417 n->next = cb->ref_to_prune;2418 cb->ref_to_prune = n;2419}2420return0;2421}24222423/*2424 * Remove empty parents, but spare refs/ and immediate subdirs.2425 * Note: munges *name.2426 */2427static voidtry_remove_empty_parents(char*name)2428{2429char*p, *q;2430int i;2431 p = name;2432for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2433while(*p && *p !='/')2434 p++;2435/* tolerate duplicate slashes; see check_refname_format() */2436while(*p =='/')2437 p++;2438}2439for(q = p; *q; q++)2440;2441while(1) {2442while(q > p && *q !='/')2443 q--;2444while(q > p && *(q-1) =='/')2445 q--;2446if(q == p)2447break;2448*q ='\0';2449if(rmdir(git_path("%s", name)))2450break;2451}2452}24532454/* make sure nobody touched the ref, and unlink */2455static voidprune_ref(struct ref_to_prune *r)2456{2457struct ref_transaction *transaction;2458struct strbuf err = STRBUF_INIT;24592460if(check_refname_format(r->name,0))2461return;24622463 transaction =ref_transaction_begin(&err);2464if(!transaction ||2465ref_transaction_delete(transaction, r->name, r->sha1,2466 REF_ISPRUNING,1, NULL, &err) ||2467ref_transaction_commit(transaction, &err)) {2468ref_transaction_free(transaction);2469error("%s", err.buf);2470strbuf_release(&err);2471return;2472}2473ref_transaction_free(transaction);2474strbuf_release(&err);2475try_remove_empty_parents(r->name);2476}24772478static voidprune_refs(struct ref_to_prune *r)2479{2480while(r) {2481prune_ref(r);2482 r = r->next;2483}2484}24852486intpack_refs(unsigned int flags)2487{2488struct pack_refs_cb_data cbdata;24892490memset(&cbdata,0,sizeof(cbdata));2491 cbdata.flags = flags;24922493lock_packed_refs(LOCK_DIE_ON_ERROR);2494 cbdata.packed_refs =get_packed_refs(&ref_cache);24952496do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2497 pack_if_possible_fn, &cbdata);24982499if(commit_packed_refs())2500die_errno("unable to overwrite old ref-pack file");25012502prune_refs(cbdata.ref_to_prune);2503return0;2504}25052506/*2507 * If entry is no longer needed in packed-refs, add it to the string2508 * list pointed to by cb_data. Reasons for deleting entries:2509 *2510 * - Entry is broken.2511 * - Entry is overridden by a loose ref.2512 * - Entry does not point at a valid object.2513 *2514 * In the first and third cases, also emit an error message because these2515 * are indications of repository corruption.2516 */2517static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2518{2519struct string_list *refs_to_delete = cb_data;25202521if(entry->flag & REF_ISBROKEN) {2522/* This shouldn't happen to packed refs. */2523error("%sis broken!", entry->name);2524string_list_append(refs_to_delete, entry->name);2525return0;2526}2527if(!has_sha1_file(entry->u.value.sha1)) {2528unsigned char sha1[20];2529int flags;25302531if(read_ref_full(entry->name,0, sha1, &flags))2532/* We should at least have found the packed ref. */2533die("Internal error");2534if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2535/*2536 * This packed reference is overridden by a2537 * loose reference, so it is OK that its value2538 * is no longer valid; for example, it might2539 * refer to an object that has been garbage2540 * collected. For this purpose we don't even2541 * care whether the loose reference itself is2542 * invalid, broken, symbolic, etc. Silently2543 * remove the packed reference.2544 */2545string_list_append(refs_to_delete, entry->name);2546return0;2547}2548/*2549 * There is no overriding loose reference, so the fact2550 * that this reference doesn't refer to a valid object2551 * indicates some kind of repository corruption.2552 * Report the problem, then omit the reference from2553 * the output.2554 */2555error("%sdoes not point to a valid object!", entry->name);2556string_list_append(refs_to_delete, entry->name);2557return0;2558}25592560return0;2561}25622563intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2564{2565struct ref_dir *packed;2566struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2567struct string_list_item *ref_to_delete;2568int i, ret, removed =0;25692570/* Look for a packed ref */2571for(i =0; i < n; i++)2572if(get_packed_ref(refnames[i]))2573break;25742575/* Avoid locking if we have nothing to do */2576if(i == n)2577return0;/* no refname exists in packed refs */25782579if(lock_packed_refs(0)) {2580if(err) {2581unable_to_lock_message(git_path("packed-refs"), errno,2582 err);2583return-1;2584}2585unable_to_lock_error(git_path("packed-refs"), errno);2586returnerror("cannot delete '%s' from packed refs", refnames[i]);2587}2588 packed =get_packed_refs(&ref_cache);25892590/* Remove refnames from the cache */2591for(i =0; i < n; i++)2592if(remove_entry(packed, refnames[i]) != -1)2593 removed =1;2594if(!removed) {2595/*2596 * All packed entries disappeared while we were2597 * acquiring the lock.2598 */2599rollback_packed_refs();2600return0;2601}26022603/* Remove any other accumulated cruft */2604do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2605for_each_string_list_item(ref_to_delete, &refs_to_delete) {2606if(remove_entry(packed, ref_to_delete->string) == -1)2607die("internal error");2608}26092610/* Write what remains */2611 ret =commit_packed_refs();2612if(ret && err)2613strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2614strerror(errno));2615return ret;2616}26172618static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2619{2620if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2621/*2622 * loose. The loose file name is the same as the2623 * lockfile name, minus ".lock":2624 */2625char*loose_filename =get_locked_file_path(lock->lk);2626int res =unlink_or_msg(loose_filename, err);2627free(loose_filename);2628if(res)2629return1;2630}2631return0;2632}26332634intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2635{2636struct ref_transaction *transaction;2637struct strbuf err = STRBUF_INIT;26382639 transaction =ref_transaction_begin(&err);2640if(!transaction ||2641ref_transaction_delete(transaction, refname, sha1, delopt,2642 sha1 && !is_null_sha1(sha1), NULL, &err) ||2643ref_transaction_commit(transaction, &err)) {2644error("%s", err.buf);2645ref_transaction_free(transaction);2646strbuf_release(&err);2647return1;2648}2649ref_transaction_free(transaction);2650strbuf_release(&err);2651return0;2652}26532654/*2655 * People using contrib's git-new-workdir have .git/logs/refs ->2656 * /some/other/path/.git/logs/refs, and that may live on another device.2657 *2658 * IOW, to avoid cross device rename errors, the temporary renamed log must2659 * live into logs/refs.2660 */2661#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"26622663static intrename_tmp_log(const char*newrefname)2664{2665int attempts_remaining =4;26662667 retry:2668switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2669case SCLD_OK:2670break;/* success */2671case SCLD_VANISHED:2672if(--attempts_remaining >0)2673goto retry;2674/* fall through */2675default:2676error("unable to create directory for%s", newrefname);2677return-1;2678}26792680if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2681if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2682/*2683 * rename(a, b) when b is an existing2684 * directory ought to result in ISDIR, but2685 * Solaris 5.8 gives ENOTDIR. Sheesh.2686 */2687if(remove_empty_directories(git_path("logs/%s", newrefname))) {2688error("Directory not empty: logs/%s", newrefname);2689return-1;2690}2691goto retry;2692}else if(errno == ENOENT && --attempts_remaining >0) {2693/*2694 * Maybe another process just deleted one of2695 * the directories in the path to newrefname.2696 * Try again from the beginning.2697 */2698goto retry;2699}else{2700error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2701 newrefname,strerror(errno));2702return-1;2703}2704}2705return0;2706}27072708static intrename_ref_available(const char*oldname,const char*newname)2709{2710struct string_list skip = STRING_LIST_INIT_NODUP;2711int ret;27122713string_list_insert(&skip, oldname);2714 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2715&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2716string_list_clear(&skip,0);2717return ret;2718}27192720static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2721const char*logmsg);27222723intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2724{2725unsigned char sha1[20], orig_sha1[20];2726int flag =0, logmoved =0;2727struct ref_lock *lock;2728struct stat loginfo;2729int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2730const char*symref = NULL;27312732if(log &&S_ISLNK(loginfo.st_mode))2733returnerror("reflog for%sis a symlink", oldrefname);27342735 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2736 orig_sha1, &flag);2737if(flag & REF_ISSYMREF)2738returnerror("refname%sis a symbolic ref, renaming it is not supported",2739 oldrefname);2740if(!symref)2741returnerror("refname%snot found", oldrefname);27422743if(!rename_ref_available(oldrefname, newrefname))2744return1;27452746if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2747returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2748 oldrefname,strerror(errno));27492750if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2751error("unable to delete old%s", oldrefname);2752goto rollback;2753}27542755if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2756delete_ref(newrefname, sha1, REF_NODEREF)) {2757if(errno==EISDIR) {2758if(remove_empty_directories(git_path("%s", newrefname))) {2759error("Directory not empty:%s", newrefname);2760goto rollback;2761}2762}else{2763error("unable to delete existing%s", newrefname);2764goto rollback;2765}2766}27672768if(log &&rename_tmp_log(newrefname))2769goto rollback;27702771 logmoved = log;27722773 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2774if(!lock) {2775error("unable to lock%sfor update", newrefname);2776goto rollback;2777}2778 lock->force_write =1;2779hashcpy(lock->old_sha1, orig_sha1);2780if(write_ref_sha1(lock, orig_sha1, logmsg)) {2781error("unable to write current sha1 into%s", newrefname);2782goto rollback;2783}27842785return0;27862787 rollback:2788 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2789if(!lock) {2790error("unable to lock%sfor rollback", oldrefname);2791goto rollbacklog;2792}27932794 lock->force_write =1;2795 flag = log_all_ref_updates;2796 log_all_ref_updates =0;2797if(write_ref_sha1(lock, orig_sha1, NULL))2798error("unable to write current sha1 into%s", oldrefname);2799 log_all_ref_updates = flag;28002801 rollbacklog:2802if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2803error("unable to restore logfile%sfrom%s:%s",2804 oldrefname, newrefname,strerror(errno));2805if(!logmoved && log &&2806rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2807error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2808 oldrefname,strerror(errno));28092810return1;2811}28122813intclose_ref(struct ref_lock *lock)2814{2815if(close_lock_file(lock->lk))2816return-1;2817 lock->lock_fd = -1;2818return0;2819}28202821intcommit_ref(struct ref_lock *lock)2822{2823if(commit_lock_file(lock->lk))2824return-1;2825 lock->lock_fd = -1;2826return0;2827}28282829voidunlock_ref(struct ref_lock *lock)2830{2831/* Do not free lock->lk -- atexit() still looks at them */2832if(lock->lk)2833rollback_lock_file(lock->lk);2834free(lock->ref_name);2835free(lock->orig_ref_name);2836free(lock);2837}28382839/*2840 * copy the reflog message msg to buf, which has been allocated sufficiently2841 * large, while cleaning up the whitespaces. Especially, convert LF to space,2842 * because reflog file is one line per entry.2843 */2844static intcopy_msg(char*buf,const char*msg)2845{2846char*cp = buf;2847char c;2848int wasspace =1;28492850*cp++ ='\t';2851while((c = *msg++)) {2852if(wasspace &&isspace(c))2853continue;2854 wasspace =isspace(c);2855if(wasspace)2856 c =' ';2857*cp++ = c;2858}2859while(buf < cp &&isspace(cp[-1]))2860 cp--;2861*cp++ ='\n';2862return cp - buf;2863}28642865/* This function must set a meaningful errno on failure */2866intlog_ref_setup(const char*refname,char*logfile,int bufsize)2867{2868int logfd, oflags = O_APPEND | O_WRONLY;28692870git_snpath(logfile, bufsize,"logs/%s", refname);2871if(log_all_ref_updates &&2872(starts_with(refname,"refs/heads/") ||2873starts_with(refname,"refs/remotes/") ||2874starts_with(refname,"refs/notes/") ||2875!strcmp(refname,"HEAD"))) {2876if(safe_create_leading_directories(logfile) <0) {2877int save_errno = errno;2878error("unable to create directory for%s", logfile);2879 errno = save_errno;2880return-1;2881}2882 oflags |= O_CREAT;2883}28842885 logfd =open(logfile, oflags,0666);2886if(logfd <0) {2887if(!(oflags & O_CREAT) && errno == ENOENT)2888return0;28892890if((oflags & O_CREAT) && errno == EISDIR) {2891if(remove_empty_directories(logfile)) {2892int save_errno = errno;2893error("There are still logs under '%s'",2894 logfile);2895 errno = save_errno;2896return-1;2897}2898 logfd =open(logfile, oflags,0666);2899}29002901if(logfd <0) {2902int save_errno = errno;2903error("Unable to append to%s:%s", logfile,2904strerror(errno));2905 errno = save_errno;2906return-1;2907}2908}29092910adjust_shared_perm(logfile);2911close(logfd);2912return0;2913}29142915static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2916const unsigned char*new_sha1,const char*msg)2917{2918int logfd, result, written, oflags = O_APPEND | O_WRONLY;2919unsigned maxlen, len;2920int msglen;2921char log_file[PATH_MAX];2922char*logrec;2923const char*committer;29242925if(log_all_ref_updates <0)2926 log_all_ref_updates = !is_bare_repository();29272928 result =log_ref_setup(refname, log_file,sizeof(log_file));2929if(result)2930return result;29312932 logfd =open(log_file, oflags);2933if(logfd <0)2934return0;2935 msglen = msg ?strlen(msg) :0;2936 committer =git_committer_info(0);2937 maxlen =strlen(committer) + msglen +100;2938 logrec =xmalloc(maxlen);2939 len =sprintf(logrec,"%s %s %s\n",2940sha1_to_hex(old_sha1),2941sha1_to_hex(new_sha1),2942 committer);2943if(msglen)2944 len +=copy_msg(logrec + len -1, msg) -1;2945 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2946free(logrec);2947if(written != len) {2948int save_errno = errno;2949close(logfd);2950error("Unable to append to%s", log_file);2951 errno = save_errno;2952return-1;2953}2954if(close(logfd)) {2955int save_errno = errno;2956error("Unable to append to%s", log_file);2957 errno = save_errno;2958return-1;2959}2960return0;2961}29622963intis_branch(const char*refname)2964{2965return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");2966}29672968/*2969 * Write sha1 into the ref specified by the lock. Make sure that errno2970 * is sane on error.2971 */2972static intwrite_ref_sha1(struct ref_lock *lock,2973const unsigned char*sha1,const char*logmsg)2974{2975static char term ='\n';2976struct object *o;29772978if(!lock) {2979 errno = EINVAL;2980return-1;2981}2982if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2983unlock_ref(lock);2984return0;2985}2986 o =parse_object(sha1);2987if(!o) {2988error("Trying to write ref%swith nonexistent object%s",2989 lock->ref_name,sha1_to_hex(sha1));2990unlock_ref(lock);2991 errno = EINVAL;2992return-1;2993}2994if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2995error("Trying to write non-commit object%sto branch%s",2996sha1_to_hex(sha1), lock->ref_name);2997unlock_ref(lock);2998 errno = EINVAL;2999return-1;3000}3001if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3002write_in_full(lock->lock_fd, &term,1) !=1||3003close_ref(lock) <0) {3004int save_errno = errno;3005error("Couldn't write%s", lock->lk->filename.buf);3006unlock_ref(lock);3007 errno = save_errno;3008return-1;3009}3010clear_loose_ref_cache(&ref_cache);3011if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3012(strcmp(lock->ref_name, lock->orig_ref_name) &&3013log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3014unlock_ref(lock);3015return-1;3016}3017if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3018/*3019 * Special hack: If a branch is updated directly and HEAD3020 * points to it (may happen on the remote side of a push3021 * for example) then logically the HEAD reflog should be3022 * updated too.3023 * A generic solution implies reverse symref information,3024 * but finding all symrefs pointing to the given branch3025 * would be rather costly for this rare event (the direct3026 * update of a branch) to be worth it. So let's cheat and3027 * check with HEAD only which should cover 99% of all usage3028 * scenarios (even 100% of the default ones).3029 */3030unsigned char head_sha1[20];3031int head_flag;3032const char*head_ref;3033 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3034 head_sha1, &head_flag);3035if(head_ref && (head_flag & REF_ISSYMREF) &&3036!strcmp(head_ref, lock->ref_name))3037log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3038}3039if(commit_ref(lock)) {3040error("Couldn't set%s", lock->ref_name);3041unlock_ref(lock);3042return-1;3043}3044unlock_ref(lock);3045return0;3046}30473048intcreate_symref(const char*ref_target,const char*refs_heads_master,3049const char*logmsg)3050{3051const char*lockpath;3052char ref[1000];3053int fd, len, written;3054char*git_HEAD =git_pathdup("%s", ref_target);3055unsigned char old_sha1[20], new_sha1[20];30563057if(logmsg &&read_ref(ref_target, old_sha1))3058hashclr(old_sha1);30593060if(safe_create_leading_directories(git_HEAD) <0)3061returnerror("unable to create directory for%s", git_HEAD);30623063#ifndef NO_SYMLINK_HEAD3064if(prefer_symlink_refs) {3065unlink(git_HEAD);3066if(!symlink(refs_heads_master, git_HEAD))3067goto done;3068fprintf(stderr,"no symlink - falling back to symbolic ref\n");3069}3070#endif30713072 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3073if(sizeof(ref) <= len) {3074error("refname too long:%s", refs_heads_master);3075goto error_free_return;3076}3077 lockpath =mkpath("%s.lock", git_HEAD);3078 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3079if(fd <0) {3080error("Unable to open%sfor writing", lockpath);3081goto error_free_return;3082}3083 written =write_in_full(fd, ref, len);3084if(close(fd) !=0|| written != len) {3085error("Unable to write to%s", lockpath);3086goto error_unlink_return;3087}3088if(rename(lockpath, git_HEAD) <0) {3089error("Unable to create%s", git_HEAD);3090goto error_unlink_return;3091}3092if(adjust_shared_perm(git_HEAD)) {3093error("Unable to fix permissions on%s", lockpath);3094 error_unlink_return:3095unlink_or_warn(lockpath);3096 error_free_return:3097free(git_HEAD);3098return-1;3099}31003101#ifndef NO_SYMLINK_HEAD3102 done:3103#endif3104if(logmsg && !read_ref(refs_heads_master, new_sha1))3105log_ref_write(ref_target, old_sha1, new_sha1, logmsg);31063107free(git_HEAD);3108return0;3109}31103111struct read_ref_at_cb {3112const char*refname;3113unsigned long at_time;3114int cnt;3115int reccnt;3116unsigned char*sha1;3117int found_it;31183119unsigned char osha1[20];3120unsigned char nsha1[20];3121int tz;3122unsigned long date;3123char**msg;3124unsigned long*cutoff_time;3125int*cutoff_tz;3126int*cutoff_cnt;3127};31283129static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3130const char*email,unsigned long timestamp,int tz,3131const char*message,void*cb_data)3132{3133struct read_ref_at_cb *cb = cb_data;31343135 cb->reccnt++;3136 cb->tz = tz;3137 cb->date = timestamp;31383139if(timestamp <= cb->at_time || cb->cnt ==0) {3140if(cb->msg)3141*cb->msg =xstrdup(message);3142if(cb->cutoff_time)3143*cb->cutoff_time = timestamp;3144if(cb->cutoff_tz)3145*cb->cutoff_tz = tz;3146if(cb->cutoff_cnt)3147*cb->cutoff_cnt = cb->reccnt -1;3148/*3149 * we have not yet updated cb->[n|o]sha1 so they still3150 * hold the values for the previous record.3151 */3152if(!is_null_sha1(cb->osha1)) {3153hashcpy(cb->sha1, nsha1);3154if(hashcmp(cb->osha1, nsha1))3155warning("Log for ref%shas gap after%s.",3156 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3157}3158else if(cb->date == cb->at_time)3159hashcpy(cb->sha1, nsha1);3160else if(hashcmp(nsha1, cb->sha1))3161warning("Log for ref%sunexpectedly ended on%s.",3162 cb->refname,show_date(cb->date, cb->tz,3163 DATE_RFC2822));3164hashcpy(cb->osha1, osha1);3165hashcpy(cb->nsha1, nsha1);3166 cb->found_it =1;3167return1;3168}3169hashcpy(cb->osha1, osha1);3170hashcpy(cb->nsha1, nsha1);3171if(cb->cnt >0)3172 cb->cnt--;3173return0;3174}31753176static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3177const char*email,unsigned long timestamp,3178int tz,const char*message,void*cb_data)3179{3180struct read_ref_at_cb *cb = cb_data;31813182if(cb->msg)3183*cb->msg =xstrdup(message);3184if(cb->cutoff_time)3185*cb->cutoff_time = timestamp;3186if(cb->cutoff_tz)3187*cb->cutoff_tz = tz;3188if(cb->cutoff_cnt)3189*cb->cutoff_cnt = cb->reccnt;3190hashcpy(cb->sha1, osha1);3191if(is_null_sha1(cb->sha1))3192hashcpy(cb->sha1, nsha1);3193/* We just want the first entry */3194return1;3195}31963197intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3198unsigned char*sha1,char**msg,3199unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3200{3201struct read_ref_at_cb cb;32023203memset(&cb,0,sizeof(cb));3204 cb.refname = refname;3205 cb.at_time = at_time;3206 cb.cnt = cnt;3207 cb.msg = msg;3208 cb.cutoff_time = cutoff_time;3209 cb.cutoff_tz = cutoff_tz;3210 cb.cutoff_cnt = cutoff_cnt;3211 cb.sha1 = sha1;32123213for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);32143215if(!cb.reccnt) {3216if(flags & GET_SHA1_QUIETLY)3217exit(128);3218else3219die("Log for%sis empty.", refname);3220}3221if(cb.found_it)3222return0;32233224for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);32253226return1;3227}32283229intreflog_exists(const char*refname)3230{3231struct stat st;32323233return!lstat(git_path("logs/%s", refname), &st) &&3234S_ISREG(st.st_mode);3235}32363237intdelete_reflog(const char*refname)3238{3239returnremove_path(git_path("logs/%s", refname));3240}32413242static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3243{3244unsigned char osha1[20], nsha1[20];3245char*email_end, *message;3246unsigned long timestamp;3247int tz;32483249/* old SP new SP name <email> SP time TAB msg LF */3250if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3251get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3252get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3253!(email_end =strchr(sb->buf +82,'>')) ||3254 email_end[1] !=' '||3255!(timestamp =strtoul(email_end +2, &message,10)) ||3256!message || message[0] !=' '||3257(message[1] !='+'&& message[1] !='-') ||3258!isdigit(message[2]) || !isdigit(message[3]) ||3259!isdigit(message[4]) || !isdigit(message[5]))3260return0;/* corrupt? */3261 email_end[1] ='\0';3262 tz =strtol(message +1, NULL,10);3263if(message[6] !='\t')3264 message +=6;3265else3266 message +=7;3267returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3268}32693270static char*find_beginning_of_line(char*bob,char*scan)3271{3272while(bob < scan && *(--scan) !='\n')3273;/* keep scanning backwards */3274/*3275 * Return either beginning of the buffer, or LF at the end of3276 * the previous line.3277 */3278return scan;3279}32803281intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3282{3283struct strbuf sb = STRBUF_INIT;3284FILE*logfp;3285long pos;3286int ret =0, at_tail =1;32873288 logfp =fopen(git_path("logs/%s", refname),"r");3289if(!logfp)3290return-1;32913292/* Jump to the end */3293if(fseek(logfp,0, SEEK_END) <0)3294returnerror("cannot seek back reflog for%s:%s",3295 refname,strerror(errno));3296 pos =ftell(logfp);3297while(!ret &&0< pos) {3298int cnt;3299size_t nread;3300char buf[BUFSIZ];3301char*endp, *scanp;33023303/* Fill next block from the end */3304 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3305if(fseek(logfp, pos - cnt, SEEK_SET))3306returnerror("cannot seek back reflog for%s:%s",3307 refname,strerror(errno));3308 nread =fread(buf, cnt,1, logfp);3309if(nread !=1)3310returnerror("cannot read%dbytes from reflog for%s:%s",3311 cnt, refname,strerror(errno));3312 pos -= cnt;33133314 scanp = endp = buf + cnt;3315if(at_tail && scanp[-1] =='\n')3316/* Looking at the final LF at the end of the file */3317 scanp--;3318 at_tail =0;33193320while(buf < scanp) {3321/*3322 * terminating LF of the previous line, or the beginning3323 * of the buffer.3324 */3325char*bp;33263327 bp =find_beginning_of_line(buf, scanp);33283329if(*bp !='\n') {3330strbuf_splice(&sb,0,0, buf, endp - buf);3331if(pos)3332break;/* need to fill another block */3333 scanp = buf -1;/* leave loop */3334}else{3335/*3336 * (bp + 1) thru endp is the beginning of the3337 * current line we have in sb3338 */3339strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3340 scanp = bp;3341 endp = bp +1;3342}3343 ret =show_one_reflog_ent(&sb, fn, cb_data);3344strbuf_reset(&sb);3345if(ret)3346break;3347}33483349}3350if(!ret && sb.len)3351 ret =show_one_reflog_ent(&sb, fn, cb_data);33523353fclose(logfp);3354strbuf_release(&sb);3355return ret;3356}33573358intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3359{3360FILE*logfp;3361struct strbuf sb = STRBUF_INIT;3362int ret =0;33633364 logfp =fopen(git_path("logs/%s", refname),"r");3365if(!logfp)3366return-1;33673368while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3369 ret =show_one_reflog_ent(&sb, fn, cb_data);3370fclose(logfp);3371strbuf_release(&sb);3372return ret;3373}3374/*3375 * Call fn for each reflog in the namespace indicated by name. name3376 * must be empty or end with '/'. Name will be used as a scratch3377 * space, but its contents will be restored before return.3378 */3379static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3380{3381DIR*d =opendir(git_path("logs/%s", name->buf));3382int retval =0;3383struct dirent *de;3384int oldlen = name->len;33853386if(!d)3387return name->len ? errno :0;33883389while((de =readdir(d)) != NULL) {3390struct stat st;33913392if(de->d_name[0] =='.')3393continue;3394if(ends_with(de->d_name,".lock"))3395continue;3396strbuf_addstr(name, de->d_name);3397if(stat(git_path("logs/%s", name->buf), &st) <0) {3398;/* silently ignore */3399}else{3400if(S_ISDIR(st.st_mode)) {3401strbuf_addch(name,'/');3402 retval =do_for_each_reflog(name, fn, cb_data);3403}else{3404unsigned char sha1[20];3405if(read_ref_full(name->buf,0, sha1, NULL))3406 retval =error("bad ref for%s", name->buf);3407else3408 retval =fn(name->buf, sha1,0, cb_data);3409}3410if(retval)3411break;3412}3413strbuf_setlen(name, oldlen);3414}3415closedir(d);3416return retval;3417}34183419intfor_each_reflog(each_ref_fn fn,void*cb_data)3420{3421int retval;3422struct strbuf name;3423strbuf_init(&name, PATH_MAX);3424 retval =do_for_each_reflog(&name, fn, cb_data);3425strbuf_release(&name);3426return retval;3427}34283429/**3430 * Information needed for a single ref update. Set new_sha1 to the3431 * new value or to zero to delete the ref. To check the old value3432 * while locking the ref, set have_old to 1 and set old_sha1 to the3433 * value or to zero to ensure the ref does not exist before update.3434 */3435struct ref_update {3436unsigned char new_sha1[20];3437unsigned char old_sha1[20];3438int flags;/* REF_NODEREF? */3439int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3440struct ref_lock *lock;3441int type;3442char*msg;3443const char refname[FLEX_ARRAY];3444};34453446/*3447 * Transaction states.3448 * OPEN: The transaction is in a valid state and can accept new updates.3449 * An OPEN transaction can be committed.3450 * CLOSED: A closed transaction is no longer active and no other operations3451 * than free can be used on it in this state.3452 * A transaction can either become closed by successfully committing3453 * an active transaction or if there is a failure while building3454 * the transaction thus rendering it failed/inactive.3455 */3456enum ref_transaction_state {3457 REF_TRANSACTION_OPEN =0,3458 REF_TRANSACTION_CLOSED =13459};34603461/*3462 * Data structure for holding a reference transaction, which can3463 * consist of checks and updates to multiple references, carried out3464 * as atomically as possible. This structure is opaque to callers.3465 */3466struct ref_transaction {3467struct ref_update **updates;3468size_t alloc;3469size_t nr;3470enum ref_transaction_state state;3471};34723473struct ref_transaction *ref_transaction_begin(struct strbuf *err)3474{3475returnxcalloc(1,sizeof(struct ref_transaction));3476}34773478voidref_transaction_free(struct ref_transaction *transaction)3479{3480int i;34813482if(!transaction)3483return;34843485for(i =0; i < transaction->nr; i++) {3486free(transaction->updates[i]->msg);3487free(transaction->updates[i]);3488}3489free(transaction->updates);3490free(transaction);3491}34923493static struct ref_update *add_update(struct ref_transaction *transaction,3494const char*refname)3495{3496size_t len =strlen(refname);3497struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);34983499strcpy((char*)update->refname, refname);3500ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3501 transaction->updates[transaction->nr++] = update;3502return update;3503}35043505intref_transaction_update(struct ref_transaction *transaction,3506const char*refname,3507const unsigned char*new_sha1,3508const unsigned char*old_sha1,3509int flags,int have_old,const char*msg,3510struct strbuf *err)3511{3512struct ref_update *update;35133514if(transaction->state != REF_TRANSACTION_OPEN)3515die("BUG: update called for transaction that is not open");35163517if(have_old && !old_sha1)3518die("BUG: have_old is true but old_sha1 is NULL");35193520 update =add_update(transaction, refname);3521hashcpy(update->new_sha1, new_sha1);3522 update->flags = flags;3523 update->have_old = have_old;3524if(have_old)3525hashcpy(update->old_sha1, old_sha1);3526if(msg)3527 update->msg =xstrdup(msg);3528return0;3529}35303531intref_transaction_create(struct ref_transaction *transaction,3532const char*refname,3533const unsigned char*new_sha1,3534int flags,const char*msg,3535struct strbuf *err)3536{3537struct ref_update *update;35383539if(transaction->state != REF_TRANSACTION_OPEN)3540die("BUG: create called for transaction that is not open");35413542if(!new_sha1 ||is_null_sha1(new_sha1))3543die("BUG: create ref with null new_sha1");35443545 update =add_update(transaction, refname);35463547hashcpy(update->new_sha1, new_sha1);3548hashclr(update->old_sha1);3549 update->flags = flags;3550 update->have_old =1;3551if(msg)3552 update->msg =xstrdup(msg);3553return0;3554}35553556intref_transaction_delete(struct ref_transaction *transaction,3557const char*refname,3558const unsigned char*old_sha1,3559int flags,int have_old,const char*msg,3560struct strbuf *err)3561{3562struct ref_update *update;35633564if(transaction->state != REF_TRANSACTION_OPEN)3565die("BUG: delete called for transaction that is not open");35663567if(have_old && !old_sha1)3568die("BUG: have_old is true but old_sha1 is NULL");35693570 update =add_update(transaction, refname);3571 update->flags = flags;3572 update->have_old = have_old;3573if(have_old) {3574assert(!is_null_sha1(old_sha1));3575hashcpy(update->old_sha1, old_sha1);3576}3577if(msg)3578 update->msg =xstrdup(msg);3579return0;3580}35813582intupdate_ref(const char*action,const char*refname,3583const unsigned char*sha1,const unsigned char*oldval,3584int flags,enum action_on_err onerr)3585{3586struct ref_transaction *t;3587struct strbuf err = STRBUF_INIT;35883589 t =ref_transaction_begin(&err);3590if(!t ||3591ref_transaction_update(t, refname, sha1, oldval, flags,3592!!oldval, action, &err) ||3593ref_transaction_commit(t, &err)) {3594const char*str ="update_ref failed for ref '%s':%s";35953596ref_transaction_free(t);3597switch(onerr) {3598case UPDATE_REFS_MSG_ON_ERR:3599error(str, refname, err.buf);3600break;3601case UPDATE_REFS_DIE_ON_ERR:3602die(str, refname, err.buf);3603break;3604case UPDATE_REFS_QUIET_ON_ERR:3605break;3606}3607strbuf_release(&err);3608return1;3609}3610strbuf_release(&err);3611ref_transaction_free(t);3612return0;3613}36143615static intref_update_compare(const void*r1,const void*r2)3616{3617const struct ref_update *const*u1 = r1;3618const struct ref_update *const*u2 = r2;3619returnstrcmp((*u1)->refname, (*u2)->refname);3620}36213622static intref_update_reject_duplicates(struct ref_update **updates,int n,3623struct strbuf *err)3624{3625int i;3626for(i =1; i < n; i++)3627if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3628const char*str =3629"Multiple updates for ref '%s' not allowed.";3630if(err)3631strbuf_addf(err, str, updates[i]->refname);36323633return1;3634}3635return0;3636}36373638intref_transaction_commit(struct ref_transaction *transaction,3639struct strbuf *err)3640{3641int ret =0, delnum =0, i;3642const char**delnames;3643int n = transaction->nr;3644struct ref_update **updates = transaction->updates;36453646if(transaction->state != REF_TRANSACTION_OPEN)3647die("BUG: commit called for transaction that is not open");36483649if(!n) {3650 transaction->state = REF_TRANSACTION_CLOSED;3651return0;3652}36533654/* Allocate work space */3655 delnames =xmalloc(sizeof(*delnames) * n);36563657/* Copy, sort, and reject duplicate refs */3658qsort(updates, n,sizeof(*updates), ref_update_compare);3659if(ref_update_reject_duplicates(updates, n, err)) {3660 ret = TRANSACTION_GENERIC_ERROR;3661goto cleanup;3662}36633664/* Acquire all locks while verifying old values */3665for(i =0; i < n; i++) {3666struct ref_update *update = updates[i];36673668 update->lock =lock_ref_sha1_basic(update->refname,3669(update->have_old ?3670 update->old_sha1 :3671 NULL),3672 NULL,3673 update->flags,3674&update->type);3675if(!update->lock) {3676 ret = (errno == ENOTDIR)3677? TRANSACTION_NAME_CONFLICT3678: TRANSACTION_GENERIC_ERROR;3679if(err)3680strbuf_addf(err,"Cannot lock the ref '%s'.",3681 update->refname);3682goto cleanup;3683}3684}36853686/* Perform updates first so live commits remain referenced */3687for(i =0; i < n; i++) {3688struct ref_update *update = updates[i];36893690if(!is_null_sha1(update->new_sha1)) {3691if(write_ref_sha1(update->lock, update->new_sha1,3692 update->msg)) {3693 update->lock = NULL;/* freed by write_ref_sha1 */3694if(err)3695strbuf_addf(err,"Cannot update the ref '%s'.",3696 update->refname);3697 ret = TRANSACTION_GENERIC_ERROR;3698goto cleanup;3699}3700 update->lock = NULL;/* freed by write_ref_sha1 */3701}3702}37033704/* Perform deletes now that updates are safely completed */3705for(i =0; i < n; i++) {3706struct ref_update *update = updates[i];37073708if(update->lock) {3709if(delete_ref_loose(update->lock, update->type, err))3710 ret = TRANSACTION_GENERIC_ERROR;37113712if(!(update->flags & REF_ISPRUNING))3713 delnames[delnum++] = update->lock->ref_name;3714}3715}37163717if(repack_without_refs(delnames, delnum, err))3718 ret = TRANSACTION_GENERIC_ERROR;3719for(i =0; i < delnum; i++)3720unlink_or_warn(git_path("logs/%s", delnames[i]));3721clear_loose_ref_cache(&ref_cache);37223723cleanup:3724 transaction->state = REF_TRANSACTION_CLOSED;37253726for(i =0; i < n; i++)3727if(updates[i]->lock)3728unlock_ref(updates[i]->lock);3729free(delnames);3730return ret;3731}37323733char*shorten_unambiguous_ref(const char*refname,int strict)3734{3735int i;3736static char**scanf_fmts;3737static int nr_rules;3738char*short_name;37393740if(!nr_rules) {3741/*3742 * Pre-generate scanf formats from ref_rev_parse_rules[].3743 * Generate a format suitable for scanf from a3744 * ref_rev_parse_rules rule by interpolating "%s" at the3745 * location of the "%.*s".3746 */3747size_t total_len =0;3748size_t offset =0;37493750/* the rule list is NULL terminated, count them first */3751for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3752/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3753 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;37543755 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);37563757 offset =0;3758for(i =0; i < nr_rules; i++) {3759assert(offset < total_len);3760 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3761 offset +=snprintf(scanf_fmts[i], total_len - offset,3762 ref_rev_parse_rules[i],2,"%s") +1;3763}3764}37653766/* bail out if there are no rules */3767if(!nr_rules)3768returnxstrdup(refname);37693770/* buffer for scanf result, at most refname must fit */3771 short_name =xstrdup(refname);37723773/* skip first rule, it will always match */3774for(i = nr_rules -1; i >0; --i) {3775int j;3776int rules_to_fail = i;3777int short_name_len;37783779if(1!=sscanf(refname, scanf_fmts[i], short_name))3780continue;37813782 short_name_len =strlen(short_name);37833784/*3785 * in strict mode, all (except the matched one) rules3786 * must fail to resolve to a valid non-ambiguous ref3787 */3788if(strict)3789 rules_to_fail = nr_rules;37903791/*3792 * check if the short name resolves to a valid ref,3793 * but use only rules prior to the matched one3794 */3795for(j =0; j < rules_to_fail; j++) {3796const char*rule = ref_rev_parse_rules[j];3797char refname[PATH_MAX];37983799/* skip matched rule */3800if(i == j)3801continue;38023803/*3804 * the short name is ambiguous, if it resolves3805 * (with this previous rule) to a valid ref3806 * read_ref() returns 0 on success3807 */3808mksnpath(refname,sizeof(refname),3809 rule, short_name_len, short_name);3810if(ref_exists(refname))3811break;3812}38133814/*3815 * short name is non-ambiguous if all previous rules3816 * haven't resolved to a valid ref3817 */3818if(j == rules_to_fail)3819return short_name;3820}38213822free(short_name);3823returnxstrdup(refname);3824}38253826static struct string_list *hide_refs;38273828intparse_hide_refs_config(const char*var,const char*value,const char*section)3829{3830if(!strcmp("transfer.hiderefs", var) ||3831/* NEEDSWORK: use parse_config_key() once both are merged */3832(starts_with(var, section) && var[strlen(section)] =='.'&&3833!strcmp(var +strlen(section),".hiderefs"))) {3834char*ref;3835int len;38363837if(!value)3838returnconfig_error_nonbool(var);3839 ref =xstrdup(value);3840 len =strlen(ref);3841while(len && ref[len -1] =='/')3842 ref[--len] ='\0';3843if(!hide_refs) {3844 hide_refs =xcalloc(1,sizeof(*hide_refs));3845 hide_refs->strdup_strings =1;3846}3847string_list_append(hide_refs, ref);3848}3849return0;3850}38513852intref_is_hidden(const char*refname)3853{3854struct string_list_item *item;38553856if(!hide_refs)3857return0;3858for_each_string_list_item(item, hide_refs) {3859int len;3860if(!starts_with(refname, item->string))3861continue;3862 len =strlen(item->string);3863if(!refname[len] || refname[len] =='/')3864return1;3865}3866return0;3867}