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] =='.') 74return-1;/* Component starts with '.'. */ 75if(cp - refname >= LOCK_SUFFIX_LEN && 76!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 77return-1;/* Refname ends with ".lock". */ 78return cp - refname; 79} 80 81intcheck_refname_format(const char*refname,int flags) 82{ 83int component_len, component_count =0; 84 85if(!strcmp(refname,"@")) 86/* Refname is a single character '@'. */ 87return-1; 88 89while(1) { 90/* We are at the start of a path component. */ 91 component_len =check_refname_component(refname, flags); 92if(component_len <=0) { 93if((flags & REFNAME_REFSPEC_PATTERN) && 94 refname[0] =='*'&& 95(refname[1] =='\0'|| refname[1] =='/')) { 96/* Accept one wildcard as a full refname component. */ 97 flags &= ~REFNAME_REFSPEC_PATTERN; 98 component_len =1; 99}else{ 100return-1; 101} 102} 103 component_count++; 104if(refname[component_len] =='\0') 105break; 106/* Skip to next component. */ 107 refname += component_len +1; 108} 109 110if(refname[component_len -1] =='.') 111return-1;/* Refname ends with '.'. */ 112if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 113return-1;/* Refname has only one component. */ 114return0; 115} 116 117struct ref_entry; 118 119/* 120 * Information used (along with the information in ref_entry) to 121 * describe a single cached reference. This data structure only 122 * occurs embedded in a union in struct ref_entry, and only when 123 * (ref_entry->flag & REF_DIR) is zero. 124 */ 125struct ref_value { 126/* 127 * The name of the object to which this reference resolves 128 * (which may be a tag object). If REF_ISBROKEN, this is 129 * null. If REF_ISSYMREF, then this is the name of the object 130 * referred to by the last reference in the symlink chain. 131 */ 132unsigned char sha1[20]; 133 134/* 135 * If REF_KNOWS_PEELED, then this field holds the peeled value 136 * of this reference, or null if the reference is known not to 137 * be peelable. See the documentation for peel_ref() for an 138 * exact definition of "peelable". 139 */ 140unsigned char peeled[20]; 141}; 142 143struct ref_cache; 144 145/* 146 * Information used (along with the information in ref_entry) to 147 * describe a level in the hierarchy of references. This data 148 * structure only occurs embedded in a union in struct ref_entry, and 149 * only when (ref_entry.flag & REF_DIR) is set. In that case, 150 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 151 * in the directory have already been read: 152 * 153 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 154 * or packed references, already read. 155 * 156 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 157 * references that hasn't been read yet (nor has any of its 158 * subdirectories). 159 * 160 * Entries within a directory are stored within a growable array of 161 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 162 * sorted are sorted by their component name in strcmp() order and the 163 * remaining entries are unsorted. 164 * 165 * Loose references are read lazily, one directory at a time. When a 166 * directory of loose references is read, then all of the references 167 * in that directory are stored, and REF_INCOMPLETE stubs are created 168 * for any subdirectories, but the subdirectories themselves are not 169 * read. The reading is triggered by get_ref_dir(). 170 */ 171struct ref_dir { 172int nr, alloc; 173 174/* 175 * Entries with index 0 <= i < sorted are sorted by name. New 176 * entries are appended to the list unsorted, and are sorted 177 * only when required; thus we avoid the need to sort the list 178 * after the addition of every reference. 179 */ 180int sorted; 181 182/* A pointer to the ref_cache that contains this ref_dir. */ 183struct ref_cache *ref_cache; 184 185struct ref_entry **entries; 186}; 187 188/* 189 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 190 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 191 * public values; see refs.h. 192 */ 193 194/* 195 * The field ref_entry->u.value.peeled of this value entry contains 196 * the correct peeled value for the reference, which might be 197 * null_sha1 if the reference is not a tag or if it is broken. 198 */ 199#define REF_KNOWS_PEELED 0x10 200 201/* ref_entry represents a directory of references */ 202#define REF_DIR 0x20 203 204/* 205 * Entry has not yet been read from disk (used only for REF_DIR 206 * entries representing loose references) 207 */ 208#define REF_INCOMPLETE 0x40 209 210/* 211 * A ref_entry represents either a reference or a "subdirectory" of 212 * references. 213 * 214 * Each directory in the reference namespace is represented by a 215 * ref_entry with (flags & REF_DIR) set and containing a subdir member 216 * that holds the entries in that directory that have been read so 217 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 218 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 219 * used for loose reference directories. 220 * 221 * References are represented by a ref_entry with (flags & REF_DIR) 222 * unset and a value member that describes the reference's value. The 223 * flag member is at the ref_entry level, but it is also needed to 224 * interpret the contents of the value field (in other words, a 225 * ref_value object is not very much use without the enclosing 226 * ref_entry). 227 * 228 * Reference names cannot end with slash and directories' names are 229 * always stored with a trailing slash (except for the top-level 230 * directory, which is always denoted by ""). This has two nice 231 * consequences: (1) when the entries in each subdir are sorted 232 * lexicographically by name (as they usually are), the references in 233 * a whole tree can be generated in lexicographic order by traversing 234 * the tree in left-to-right, depth-first order; (2) the names of 235 * references and subdirectories cannot conflict, and therefore the 236 * presence of an empty subdirectory does not block the creation of a 237 * similarly-named reference. (The fact that reference names with the 238 * same leading components can conflict *with each other* is a 239 * separate issue that is regulated by is_refname_available().) 240 * 241 * Please note that the name field contains the fully-qualified 242 * reference (or subdirectory) name. Space could be saved by only 243 * storing the relative names. But that would require the full names 244 * to be generated on the fly when iterating in do_for_each_ref(), and 245 * would break callback functions, who have always been able to assume 246 * that the name strings that they are passed will not be freed during 247 * the iteration. 248 */ 249struct ref_entry { 250unsigned char flag;/* ISSYMREF? ISPACKED? */ 251union{ 252struct ref_value value;/* if not (flags&REF_DIR) */ 253struct ref_dir subdir;/* if (flags&REF_DIR) */ 254} u; 255/* 256 * The full name of the reference (e.g., "refs/heads/master") 257 * or the full name of the directory with a trailing slash 258 * (e.g., "refs/heads/"): 259 */ 260char name[FLEX_ARRAY]; 261}; 262 263static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 264 265static struct ref_dir *get_ref_dir(struct ref_entry *entry) 266{ 267struct ref_dir *dir; 268assert(entry->flag & REF_DIR); 269 dir = &entry->u.subdir; 270if(entry->flag & REF_INCOMPLETE) { 271read_loose_refs(entry->name, dir); 272 entry->flag &= ~REF_INCOMPLETE; 273} 274return dir; 275} 276 277/* 278 * Check if a refname is safe. 279 * For refs that start with "refs/" we consider it safe as long they do 280 * not try to resolve to outside of refs/. 281 * 282 * For all other refs we only consider them safe iff they only contain 283 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 284 * "config"). 285 */ 286static intrefname_is_safe(const char*refname) 287{ 288if(starts_with(refname,"refs/")) { 289char*buf; 290int result; 291 292 buf =xmalloc(strlen(refname) +1); 293/* 294 * Does the refname try to escape refs/? 295 * For example: refs/foo/../bar is safe but refs/foo/../../bar 296 * is not. 297 */ 298 result = !normalize_path_copy(buf, refname +strlen("refs/")); 299free(buf); 300return result; 301} 302while(*refname) { 303if(!isupper(*refname) && *refname !='_') 304return0; 305 refname++; 306} 307return1; 308} 309 310static struct ref_entry *create_ref_entry(const char*refname, 311const unsigned char*sha1,int flag, 312int check_name) 313{ 314int len; 315struct ref_entry *ref; 316 317if(check_name && 318check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 319die("Reference has invalid format: '%s'", refname); 320if(!check_name && !refname_is_safe(refname)) 321die("Reference has invalid name: '%s'", refname); 322 len =strlen(refname) +1; 323 ref =xmalloc(sizeof(struct ref_entry) + len); 324hashcpy(ref->u.value.sha1, sha1); 325hashclr(ref->u.value.peeled); 326memcpy(ref->name, refname, len); 327 ref->flag = flag; 328return ref; 329} 330 331static voidclear_ref_dir(struct ref_dir *dir); 332 333static voidfree_ref_entry(struct ref_entry *entry) 334{ 335if(entry->flag & REF_DIR) { 336/* 337 * Do not use get_ref_dir() here, as that might 338 * trigger the reading of loose refs. 339 */ 340clear_ref_dir(&entry->u.subdir); 341} 342free(entry); 343} 344 345/* 346 * Add a ref_entry to the end of dir (unsorted). Entry is always 347 * stored directly in dir; no recursion into subdirectories is 348 * done. 349 */ 350static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 351{ 352ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 353 dir->entries[dir->nr++] = entry; 354/* optimize for the case that entries are added in order */ 355if(dir->nr ==1|| 356(dir->nr == dir->sorted +1&& 357strcmp(dir->entries[dir->nr -2]->name, 358 dir->entries[dir->nr -1]->name) <0)) 359 dir->sorted = dir->nr; 360} 361 362/* 363 * Clear and free all entries in dir, recursively. 364 */ 365static voidclear_ref_dir(struct ref_dir *dir) 366{ 367int i; 368for(i =0; i < dir->nr; i++) 369free_ref_entry(dir->entries[i]); 370free(dir->entries); 371 dir->sorted = dir->nr = dir->alloc =0; 372 dir->entries = NULL; 373} 374 375/* 376 * Create a struct ref_entry object for the specified dirname. 377 * dirname is the name of the directory with a trailing slash (e.g., 378 * "refs/heads/") or "" for the top-level directory. 379 */ 380static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 381const char*dirname,size_t len, 382int incomplete) 383{ 384struct ref_entry *direntry; 385 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 386memcpy(direntry->name, dirname, len); 387 direntry->name[len] ='\0'; 388 direntry->u.subdir.ref_cache = ref_cache; 389 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 390return direntry; 391} 392 393static intref_entry_cmp(const void*a,const void*b) 394{ 395struct ref_entry *one = *(struct ref_entry **)a; 396struct ref_entry *two = *(struct ref_entry **)b; 397returnstrcmp(one->name, two->name); 398} 399 400static voidsort_ref_dir(struct ref_dir *dir); 401 402struct string_slice { 403size_t len; 404const char*str; 405}; 406 407static intref_entry_cmp_sslice(const void*key_,const void*ent_) 408{ 409const struct string_slice *key = key_; 410const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 411int cmp =strncmp(key->str, ent->name, key->len); 412if(cmp) 413return cmp; 414return'\0'- (unsigned char)ent->name[key->len]; 415} 416 417/* 418 * Return the index of the entry with the given refname from the 419 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 420 * no such entry is found. dir must already be complete. 421 */ 422static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 423{ 424struct ref_entry **r; 425struct string_slice key; 426 427if(refname == NULL || !dir->nr) 428return-1; 429 430sort_ref_dir(dir); 431 key.len = len; 432 key.str = refname; 433 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 434 ref_entry_cmp_sslice); 435 436if(r == NULL) 437return-1; 438 439return r - dir->entries; 440} 441 442/* 443 * Search for a directory entry directly within dir (without 444 * recursing). Sort dir if necessary. subdirname must be a directory 445 * name (i.e., end in '/'). If mkdir is set, then create the 446 * directory if it is missing; otherwise, return NULL if the desired 447 * directory cannot be found. dir must already be complete. 448 */ 449static struct ref_dir *search_for_subdir(struct ref_dir *dir, 450const char*subdirname,size_t len, 451int mkdir) 452{ 453int entry_index =search_ref_dir(dir, subdirname, len); 454struct ref_entry *entry; 455if(entry_index == -1) { 456if(!mkdir) 457return NULL; 458/* 459 * Since dir is complete, the absence of a subdir 460 * means that the subdir really doesn't exist; 461 * therefore, create an empty record for it but mark 462 * the record complete. 463 */ 464 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 465add_entry_to_dir(dir, entry); 466}else{ 467 entry = dir->entries[entry_index]; 468} 469returnget_ref_dir(entry); 470} 471 472/* 473 * If refname is a reference name, find the ref_dir within the dir 474 * tree that should hold refname. If refname is a directory name 475 * (i.e., ends in '/'), then return that ref_dir itself. dir must 476 * represent the top-level directory and must already be complete. 477 * Sort ref_dirs and recurse into subdirectories as necessary. If 478 * mkdir is set, then create any missing directories; otherwise, 479 * return NULL if the desired directory cannot be found. 480 */ 481static struct ref_dir *find_containing_dir(struct ref_dir *dir, 482const char*refname,int mkdir) 483{ 484const char*slash; 485for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 486size_t dirnamelen = slash - refname +1; 487struct ref_dir *subdir; 488 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 489if(!subdir) { 490 dir = NULL; 491break; 492} 493 dir = subdir; 494} 495 496return dir; 497} 498 499/* 500 * Find the value entry with the given name in dir, sorting ref_dirs 501 * and recursing into subdirectories as necessary. If the name is not 502 * found or it corresponds to a directory entry, return NULL. 503 */ 504static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 505{ 506int entry_index; 507struct ref_entry *entry; 508 dir =find_containing_dir(dir, refname,0); 509if(!dir) 510return NULL; 511 entry_index =search_ref_dir(dir, refname,strlen(refname)); 512if(entry_index == -1) 513return NULL; 514 entry = dir->entries[entry_index]; 515return(entry->flag & REF_DIR) ? NULL : entry; 516} 517 518/* 519 * Remove the entry with the given name from dir, recursing into 520 * subdirectories as necessary. If refname is the name of a directory 521 * (i.e., ends with '/'), then remove the directory and its contents. 522 * If the removal was successful, return the number of entries 523 * remaining in the directory entry that contained the deleted entry. 524 * If the name was not found, return -1. Please note that this 525 * function only deletes the entry from the cache; it does not delete 526 * it from the filesystem or ensure that other cache entries (which 527 * might be symbolic references to the removed entry) are updated. 528 * Nor does it remove any containing dir entries that might be made 529 * empty by the removal. dir must represent the top-level directory 530 * and must already be complete. 531 */ 532static intremove_entry(struct ref_dir *dir,const char*refname) 533{ 534int refname_len =strlen(refname); 535int entry_index; 536struct ref_entry *entry; 537int is_dir = refname[refname_len -1] =='/'; 538if(is_dir) { 539/* 540 * refname represents a reference directory. Remove 541 * the trailing slash; otherwise we will get the 542 * directory *representing* refname rather than the 543 * one *containing* it. 544 */ 545char*dirname =xmemdupz(refname, refname_len -1); 546 dir =find_containing_dir(dir, dirname,0); 547free(dirname); 548}else{ 549 dir =find_containing_dir(dir, refname,0); 550} 551if(!dir) 552return-1; 553 entry_index =search_ref_dir(dir, refname, refname_len); 554if(entry_index == -1) 555return-1; 556 entry = dir->entries[entry_index]; 557 558memmove(&dir->entries[entry_index], 559&dir->entries[entry_index +1], 560(dir->nr - entry_index -1) *sizeof(*dir->entries) 561); 562 dir->nr--; 563if(dir->sorted > entry_index) 564 dir->sorted--; 565free_ref_entry(entry); 566return dir->nr; 567} 568 569/* 570 * Add a ref_entry to the ref_dir (unsorted), recursing into 571 * subdirectories as necessary. dir must represent the top-level 572 * directory. Return 0 on success. 573 */ 574static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 575{ 576 dir =find_containing_dir(dir, ref->name,1); 577if(!dir) 578return-1; 579add_entry_to_dir(dir, ref); 580return0; 581} 582 583/* 584 * Emit a warning and return true iff ref1 and ref2 have the same name 585 * and the same sha1. Die if they have the same name but different 586 * sha1s. 587 */ 588static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 589{ 590if(strcmp(ref1->name, ref2->name)) 591return0; 592 593/* Duplicate name; make sure that they don't conflict: */ 594 595if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 596/* This is impossible by construction */ 597die("Reference directory conflict:%s", ref1->name); 598 599if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 600die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 601 602warning("Duplicated ref:%s", ref1->name); 603return1; 604} 605 606/* 607 * Sort the entries in dir non-recursively (if they are not already 608 * sorted) and remove any duplicate entries. 609 */ 610static voidsort_ref_dir(struct ref_dir *dir) 611{ 612int i, j; 613struct ref_entry *last = NULL; 614 615/* 616 * This check also prevents passing a zero-length array to qsort(), 617 * which is a problem on some platforms. 618 */ 619if(dir->sorted == dir->nr) 620return; 621 622qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 623 624/* Remove any duplicates: */ 625for(i =0, j =0; j < dir->nr; j++) { 626struct ref_entry *entry = dir->entries[j]; 627if(last &&is_dup_ref(last, entry)) 628free_ref_entry(entry); 629else 630 last = dir->entries[i++] = entry; 631} 632 dir->sorted = dir->nr = i; 633} 634 635/* Include broken references in a do_for_each_ref*() iteration: */ 636#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 637 638/* 639 * Return true iff the reference described by entry can be resolved to 640 * an object in the database. Emit a warning if the referred-to 641 * object does not exist. 642 */ 643static intref_resolves_to_object(struct ref_entry *entry) 644{ 645if(entry->flag & REF_ISBROKEN) 646return0; 647if(!has_sha1_file(entry->u.value.sha1)) { 648error("%sdoes not point to a valid object!", entry->name); 649return0; 650} 651return1; 652} 653 654/* 655 * current_ref is a performance hack: when iterating over references 656 * using the for_each_ref*() functions, current_ref is set to the 657 * current reference's entry before calling the callback function. If 658 * the callback function calls peel_ref(), then peel_ref() first 659 * checks whether the reference to be peeled is the current reference 660 * (it usually is) and if so, returns that reference's peeled version 661 * if it is available. This avoids a refname lookup in a common case. 662 */ 663static struct ref_entry *current_ref; 664 665typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 666 667struct ref_entry_cb { 668const char*base; 669int trim; 670int flags; 671 each_ref_fn *fn; 672void*cb_data; 673}; 674 675/* 676 * Handle one reference in a do_for_each_ref*()-style iteration, 677 * calling an each_ref_fn for each entry. 678 */ 679static intdo_one_ref(struct ref_entry *entry,void*cb_data) 680{ 681struct ref_entry_cb *data = cb_data; 682struct ref_entry *old_current_ref; 683int retval; 684 685if(!starts_with(entry->name, data->base)) 686return0; 687 688if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 689!ref_resolves_to_object(entry)) 690return0; 691 692/* Store the old value, in case this is a recursive call: */ 693 old_current_ref = current_ref; 694 current_ref = entry; 695 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 696 entry->flag, data->cb_data); 697 current_ref = old_current_ref; 698return retval; 699} 700 701/* 702 * Call fn for each reference in dir that has index in the range 703 * offset <= index < dir->nr. Recurse into subdirectories that are in 704 * that index range, sorting them before iterating. This function 705 * does not sort dir itself; it should be sorted beforehand. fn is 706 * called for all references, including broken ones. 707 */ 708static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 709 each_ref_entry_fn fn,void*cb_data) 710{ 711int i; 712assert(dir->sorted == dir->nr); 713for(i = offset; i < dir->nr; i++) { 714struct ref_entry *entry = dir->entries[i]; 715int retval; 716if(entry->flag & REF_DIR) { 717struct ref_dir *subdir =get_ref_dir(entry); 718sort_ref_dir(subdir); 719 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 720}else{ 721 retval =fn(entry, cb_data); 722} 723if(retval) 724return retval; 725} 726return0; 727} 728 729/* 730 * Call fn for each reference in the union of dir1 and dir2, in order 731 * by refname. Recurse into subdirectories. If a value entry appears 732 * in both dir1 and dir2, then only process the version that is in 733 * dir2. The input dirs must already be sorted, but subdirs will be 734 * sorted as needed. fn is called for all references, including 735 * broken ones. 736 */ 737static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 738struct ref_dir *dir2, 739 each_ref_entry_fn fn,void*cb_data) 740{ 741int retval; 742int i1 =0, i2 =0; 743 744assert(dir1->sorted == dir1->nr); 745assert(dir2->sorted == dir2->nr); 746while(1) { 747struct ref_entry *e1, *e2; 748int cmp; 749if(i1 == dir1->nr) { 750returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 751} 752if(i2 == dir2->nr) { 753returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 754} 755 e1 = dir1->entries[i1]; 756 e2 = dir2->entries[i2]; 757 cmp =strcmp(e1->name, e2->name); 758if(cmp ==0) { 759if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 760/* Both are directories; descend them in parallel. */ 761struct ref_dir *subdir1 =get_ref_dir(e1); 762struct ref_dir *subdir2 =get_ref_dir(e2); 763sort_ref_dir(subdir1); 764sort_ref_dir(subdir2); 765 retval =do_for_each_entry_in_dirs( 766 subdir1, subdir2, fn, cb_data); 767 i1++; 768 i2++; 769}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 770/* Both are references; ignore the one from dir1. */ 771 retval =fn(e2, cb_data); 772 i1++; 773 i2++; 774}else{ 775die("conflict between reference and directory:%s", 776 e1->name); 777} 778}else{ 779struct ref_entry *e; 780if(cmp <0) { 781 e = e1; 782 i1++; 783}else{ 784 e = e2; 785 i2++; 786} 787if(e->flag & REF_DIR) { 788struct ref_dir *subdir =get_ref_dir(e); 789sort_ref_dir(subdir); 790 retval =do_for_each_entry_in_dir( 791 subdir,0, fn, cb_data); 792}else{ 793 retval =fn(e, cb_data); 794} 795} 796if(retval) 797return retval; 798} 799} 800 801/* 802 * Load all of the refs from the dir into our in-memory cache. The hard work 803 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 804 * through all of the sub-directories. We do not even need to care about 805 * sorting, as traversal order does not matter to us. 806 */ 807static voidprime_ref_dir(struct ref_dir *dir) 808{ 809int i; 810for(i =0; i < dir->nr; i++) { 811struct ref_entry *entry = dir->entries[i]; 812if(entry->flag & REF_DIR) 813prime_ref_dir(get_ref_dir(entry)); 814} 815} 816 817static intentry_matches(struct ref_entry *entry,const struct string_list *list) 818{ 819return list &&string_list_has_string(list, entry->name); 820} 821 822struct nonmatching_ref_data { 823const struct string_list *skip; 824struct ref_entry *found; 825}; 826 827static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 828{ 829struct nonmatching_ref_data *data = vdata; 830 831if(entry_matches(entry, data->skip)) 832return0; 833 834 data->found = entry; 835return1; 836} 837 838static voidreport_refname_conflict(struct ref_entry *entry, 839const char*refname) 840{ 841error("'%s' exists; cannot create '%s'", entry->name, refname); 842} 843 844/* 845 * Return true iff a reference named refname could be created without 846 * conflicting with the name of an existing reference in dir. If 847 * skip is non-NULL, ignore potential conflicts with refs in skip 848 * (e.g., because they are scheduled for deletion in the same 849 * operation). 850 * 851 * Two reference names conflict if one of them exactly matches the 852 * leading components of the other; e.g., "foo/bar" conflicts with 853 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 854 * "foo/barbados". 855 * 856 * skip must be sorted. 857 */ 858static intis_refname_available(const char*refname, 859const struct string_list *skip, 860struct ref_dir *dir) 861{ 862const char*slash; 863size_t len; 864int pos; 865char*dirname; 866 867for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 868/* 869 * We are still at a leading dir of the refname; we are 870 * looking for a conflict with a leaf entry. 871 * 872 * If we find one, we still must make sure it is 873 * not in "skip". 874 */ 875 pos =search_ref_dir(dir, refname, slash - refname); 876if(pos >=0) { 877struct ref_entry *entry = dir->entries[pos]; 878if(entry_matches(entry, skip)) 879return1; 880report_refname_conflict(entry, refname); 881return0; 882} 883 884 885/* 886 * Otherwise, we can try to continue our search with 887 * the next component; if we come up empty, we know 888 * there is nothing under this whole prefix. 889 */ 890 pos =search_ref_dir(dir, refname, slash +1- refname); 891if(pos <0) 892return1; 893 894 dir =get_ref_dir(dir->entries[pos]); 895} 896 897/* 898 * We are at the leaf of our refname; we want to 899 * make sure there are no directories which match it. 900 */ 901 len =strlen(refname); 902 dirname =xmallocz(len +1); 903sprintf(dirname,"%s/", refname); 904 pos =search_ref_dir(dir, dirname, len +1); 905free(dirname); 906 907if(pos >=0) { 908/* 909 * We found a directory named "refname". It is a 910 * problem iff it contains any ref that is not 911 * in "skip". 912 */ 913struct ref_entry *entry = dir->entries[pos]; 914struct ref_dir *dir =get_ref_dir(entry); 915struct nonmatching_ref_data data; 916 917 data.skip = skip; 918sort_ref_dir(dir); 919if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 920return1; 921 922report_refname_conflict(data.found, refname); 923return0; 924} 925 926/* 927 * There is no point in searching for another leaf 928 * node which matches it; such an entry would be the 929 * ref we are looking for, not a conflict. 930 */ 931return1; 932} 933 934struct packed_ref_cache { 935struct ref_entry *root; 936 937/* 938 * Count of references to the data structure in this instance, 939 * including the pointer from ref_cache::packed if any. The 940 * data will not be freed as long as the reference count is 941 * nonzero. 942 */ 943unsigned int referrers; 944 945/* 946 * Iff the packed-refs file associated with this instance is 947 * currently locked for writing, this points at the associated 948 * lock (which is owned by somebody else). The referrer count 949 * is also incremented when the file is locked and decremented 950 * when it is unlocked. 951 */ 952struct lock_file *lock; 953 954/* The metadata from when this packed-refs cache was read */ 955struct stat_validity validity; 956}; 957 958/* 959 * Future: need to be in "struct repository" 960 * when doing a full libification. 961 */ 962static struct ref_cache { 963struct ref_cache *next; 964struct ref_entry *loose; 965struct packed_ref_cache *packed; 966/* 967 * The submodule name, or "" for the main repo. We allocate 968 * length 1 rather than FLEX_ARRAY so that the main ref_cache 969 * is initialized correctly. 970 */ 971char name[1]; 972} ref_cache, *submodule_ref_caches; 973 974/* Lock used for the main packed-refs file: */ 975static struct lock_file packlock; 976 977/* 978 * Increment the reference count of *packed_refs. 979 */ 980static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 981{ 982 packed_refs->referrers++; 983} 984 985/* 986 * Decrease the reference count of *packed_refs. If it goes to zero, 987 * free *packed_refs and return true; otherwise return false. 988 */ 989static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 990{ 991if(!--packed_refs->referrers) { 992free_ref_entry(packed_refs->root); 993stat_validity_clear(&packed_refs->validity); 994free(packed_refs); 995return1; 996}else{ 997return0; 998} 999}10001001static voidclear_packed_ref_cache(struct ref_cache *refs)1002{1003if(refs->packed) {1004struct packed_ref_cache *packed_refs = refs->packed;10051006if(packed_refs->lock)1007die("internal error: packed-ref cache cleared while locked");1008 refs->packed = NULL;1009release_packed_ref_cache(packed_refs);1010}1011}10121013static voidclear_loose_ref_cache(struct ref_cache *refs)1014{1015if(refs->loose) {1016free_ref_entry(refs->loose);1017 refs->loose = NULL;1018}1019}10201021static struct ref_cache *create_ref_cache(const char*submodule)1022{1023int len;1024struct ref_cache *refs;1025if(!submodule)1026 submodule ="";1027 len =strlen(submodule) +1;1028 refs =xcalloc(1,sizeof(struct ref_cache) + len);1029memcpy(refs->name, submodule, len);1030return refs;1031}10321033/*1034 * Return a pointer to a ref_cache for the specified submodule. For1035 * the main repository, use submodule==NULL. The returned structure1036 * will be allocated and initialized but not necessarily populated; it1037 * should not be freed.1038 */1039static struct ref_cache *get_ref_cache(const char*submodule)1040{1041struct ref_cache *refs;10421043if(!submodule || !*submodule)1044return&ref_cache;10451046for(refs = submodule_ref_caches; refs; refs = refs->next)1047if(!strcmp(submodule, refs->name))1048return refs;10491050 refs =create_ref_cache(submodule);1051 refs->next = submodule_ref_caches;1052 submodule_ref_caches = refs;1053return refs;1054}10551056/* The length of a peeled reference line in packed-refs, including EOL: */1057#define PEELED_LINE_LENGTH 4210581059/*1060 * The packed-refs header line that we write out. Perhaps other1061 * traits will be added later. The trailing space is required.1062 */1063static const char PACKED_REFS_HEADER[] =1064"# pack-refs with: peeled fully-peeled\n";10651066/*1067 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1068 * Return a pointer to the refname within the line (null-terminated),1069 * or NULL if there was a problem.1070 */1071static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1072{1073const char*ref;10741075/*1076 * 42: the answer to everything.1077 *1078 * In this case, it happens to be the answer to1079 * 40 (length of sha1 hex representation)1080 * +1 (space in between hex and name)1081 * +1 (newline at the end of the line)1082 */1083if(line->len <=42)1084return NULL;10851086if(get_sha1_hex(line->buf, sha1) <0)1087return NULL;1088if(!isspace(line->buf[40]))1089return NULL;10901091 ref = line->buf +41;1092if(isspace(*ref))1093return NULL;10941095if(line->buf[line->len -1] !='\n')1096return NULL;1097 line->buf[--line->len] =0;10981099return ref;1100}11011102/*1103 * Read f, which is a packed-refs file, into dir.1104 *1105 * A comment line of the form "# pack-refs with: " may contain zero or1106 * more traits. We interpret the traits as follows:1107 *1108 * No traits:1109 *1110 * Probably no references are peeled. But if the file contains a1111 * peeled value for a reference, we will use it.1112 *1113 * peeled:1114 *1115 * References under "refs/tags/", if they *can* be peeled, *are*1116 * peeled in this file. References outside of "refs/tags/" are1117 * probably not peeled even if they could have been, but if we find1118 * a peeled value for such a reference we will use it.1119 *1120 * fully-peeled:1121 *1122 * All references in the file that can be peeled are peeled.1123 * Inversely (and this is more important), any references in the1124 * file for which no peeled value is recorded is not peelable. This1125 * trait should typically be written alongside "peeled" for1126 * compatibility with older clients, but we do not require it1127 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1128 */1129static voidread_packed_refs(FILE*f,struct ref_dir *dir)1130{1131struct ref_entry *last = NULL;1132struct strbuf line = STRBUF_INIT;1133enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11341135while(strbuf_getwholeline(&line, f,'\n') != EOF) {1136unsigned char sha1[20];1137const char*refname;1138const char*traits;11391140if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1141if(strstr(traits," fully-peeled "))1142 peeled = PEELED_FULLY;1143else if(strstr(traits," peeled "))1144 peeled = PEELED_TAGS;1145/* perhaps other traits later as well */1146continue;1147}11481149 refname =parse_ref_line(&line, sha1);1150if(refname) {1151int flag = REF_ISPACKED;11521153if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1154hashclr(sha1);1155 flag |= REF_BAD_NAME | REF_ISBROKEN;1156}1157 last =create_ref_entry(refname, sha1, flag,0);1158if(peeled == PEELED_FULLY ||1159(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1160 last->flag |= REF_KNOWS_PEELED;1161add_ref(dir, last);1162continue;1163}1164if(last &&1165 line.buf[0] =='^'&&1166 line.len == PEELED_LINE_LENGTH &&1167 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1168!get_sha1_hex(line.buf +1, sha1)) {1169hashcpy(last->u.value.peeled, sha1);1170/*1171 * Regardless of what the file header said,1172 * we definitely know the value of *this*1173 * reference:1174 */1175 last->flag |= REF_KNOWS_PEELED;1176}1177}11781179strbuf_release(&line);1180}11811182/*1183 * Get the packed_ref_cache for the specified ref_cache, creating it1184 * if necessary.1185 */1186static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1187{1188const char*packed_refs_file;11891190if(*refs->name)1191 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1192else1193 packed_refs_file =git_path("packed-refs");11941195if(refs->packed &&1196!stat_validity_check(&refs->packed->validity, packed_refs_file))1197clear_packed_ref_cache(refs);11981199if(!refs->packed) {1200FILE*f;12011202 refs->packed =xcalloc(1,sizeof(*refs->packed));1203acquire_packed_ref_cache(refs->packed);1204 refs->packed->root =create_dir_entry(refs,"",0,0);1205 f =fopen(packed_refs_file,"r");1206if(f) {1207stat_validity_update(&refs->packed->validity,fileno(f));1208read_packed_refs(f,get_ref_dir(refs->packed->root));1209fclose(f);1210}1211}1212return refs->packed;1213}12141215static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1216{1217returnget_ref_dir(packed_ref_cache->root);1218}12191220static struct ref_dir *get_packed_refs(struct ref_cache *refs)1221{1222returnget_packed_ref_dir(get_packed_ref_cache(refs));1223}12241225voidadd_packed_ref(const char*refname,const unsigned char*sha1)1226{1227struct packed_ref_cache *packed_ref_cache =1228get_packed_ref_cache(&ref_cache);12291230if(!packed_ref_cache->lock)1231die("internal error: packed refs not locked");1232add_ref(get_packed_ref_dir(packed_ref_cache),1233create_ref_entry(refname, sha1, REF_ISPACKED,1));1234}12351236/*1237 * Read the loose references from the namespace dirname into dir1238 * (without recursing). dirname must end with '/'. dir must be the1239 * directory entry corresponding to dirname.1240 */1241static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1242{1243struct ref_cache *refs = dir->ref_cache;1244DIR*d;1245const char*path;1246struct dirent *de;1247int dirnamelen =strlen(dirname);1248struct strbuf refname;12491250if(*refs->name)1251 path =git_path_submodule(refs->name,"%s", dirname);1252else1253 path =git_path("%s", dirname);12541255 d =opendir(path);1256if(!d)1257return;12581259strbuf_init(&refname, dirnamelen +257);1260strbuf_add(&refname, dirname, dirnamelen);12611262while((de =readdir(d)) != NULL) {1263unsigned char sha1[20];1264struct stat st;1265int flag;1266const char*refdir;12671268if(de->d_name[0] =='.')1269continue;1270if(ends_with(de->d_name,".lock"))1271continue;1272strbuf_addstr(&refname, de->d_name);1273 refdir = *refs->name1274?git_path_submodule(refs->name,"%s", refname.buf)1275:git_path("%s", refname.buf);1276if(stat(refdir, &st) <0) {1277;/* silently ignore */1278}else if(S_ISDIR(st.st_mode)) {1279strbuf_addch(&refname,'/');1280add_entry_to_dir(dir,1281create_dir_entry(refs, refname.buf,1282 refname.len,1));1283}else{1284if(*refs->name) {1285hashclr(sha1);1286 flag =0;1287if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1288hashclr(sha1);1289 flag |= REF_ISBROKEN;1290}1291}else if(read_ref_full(refname.buf,1292 RESOLVE_REF_READING,1293 sha1, &flag)) {1294hashclr(sha1);1295 flag |= REF_ISBROKEN;1296}1297if(check_refname_format(refname.buf,1298 REFNAME_ALLOW_ONELEVEL)) {1299hashclr(sha1);1300 flag |= REF_BAD_NAME | REF_ISBROKEN;1301}1302add_entry_to_dir(dir,1303create_ref_entry(refname.buf, sha1, flag,0));1304}1305strbuf_setlen(&refname, dirnamelen);1306}1307strbuf_release(&refname);1308closedir(d);1309}13101311static struct ref_dir *get_loose_refs(struct ref_cache *refs)1312{1313if(!refs->loose) {1314/*1315 * Mark the top-level directory complete because we1316 * are about to read the only subdirectory that can1317 * hold references:1318 */1319 refs->loose =create_dir_entry(refs,"",0,0);1320/*1321 * Create an incomplete entry for "refs/":1322 */1323add_entry_to_dir(get_ref_dir(refs->loose),1324create_dir_entry(refs,"refs/",5,1));1325}1326returnget_ref_dir(refs->loose);1327}13281329/* We allow "recursive" symbolic refs. Only within reason, though */1330#define MAXDEPTH 51331#define MAXREFLEN (1024)13321333/*1334 * Called by resolve_gitlink_ref_recursive() after it failed to read1335 * from the loose refs in ref_cache refs. Find <refname> in the1336 * packed-refs file for the submodule.1337 */1338static intresolve_gitlink_packed_ref(struct ref_cache *refs,1339const char*refname,unsigned char*sha1)1340{1341struct ref_entry *ref;1342struct ref_dir *dir =get_packed_refs(refs);13431344 ref =find_ref(dir, refname);1345if(ref == NULL)1346return-1;13471348hashcpy(sha1, ref->u.value.sha1);1349return0;1350}13511352static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1353const char*refname,unsigned char*sha1,1354int recursion)1355{1356int fd, len;1357char buffer[128], *p;1358char*path;13591360if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1361return-1;1362 path = *refs->name1363?git_path_submodule(refs->name,"%s", refname)1364:git_path("%s", refname);1365 fd =open(path, O_RDONLY);1366if(fd <0)1367returnresolve_gitlink_packed_ref(refs, refname, sha1);13681369 len =read(fd, buffer,sizeof(buffer)-1);1370close(fd);1371if(len <0)1372return-1;1373while(len &&isspace(buffer[len-1]))1374 len--;1375 buffer[len] =0;13761377/* Was it a detached head or an old-fashioned symlink? */1378if(!get_sha1_hex(buffer, sha1))1379return0;13801381/* Symref? */1382if(strncmp(buffer,"ref:",4))1383return-1;1384 p = buffer +4;1385while(isspace(*p))1386 p++;13871388returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1389}13901391intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1392{1393int len =strlen(path), retval;1394char*submodule;1395struct ref_cache *refs;13961397while(len && path[len-1] =='/')1398 len--;1399if(!len)1400return-1;1401 submodule =xstrndup(path, len);1402 refs =get_ref_cache(submodule);1403free(submodule);14041405 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1406return retval;1407}14081409/*1410 * Return the ref_entry for the given refname from the packed1411 * references. If it does not exist, return NULL.1412 */1413static struct ref_entry *get_packed_ref(const char*refname)1414{1415returnfind_ref(get_packed_refs(&ref_cache), refname);1416}14171418/*1419 * A loose ref file doesn't exist; check for a packed ref. The1420 * options are forwarded from resolve_safe_unsafe().1421 */1422static intresolve_missing_loose_ref(const char*refname,1423int resolve_flags,1424unsigned char*sha1,1425int*flags)1426{1427struct ref_entry *entry;14281429/*1430 * The loose reference file does not exist; check for a packed1431 * reference.1432 */1433 entry =get_packed_ref(refname);1434if(entry) {1435hashcpy(sha1, entry->u.value.sha1);1436if(flags)1437*flags |= REF_ISPACKED;1438return0;1439}1440/* The reference is not a packed reference, either. */1441if(resolve_flags & RESOLVE_REF_READING) {1442 errno = ENOENT;1443return-1;1444}else{1445hashclr(sha1);1446return0;1447}1448}14491450/* This function needs to return a meaningful errno on failure */1451const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1452{1453int depth = MAXDEPTH;1454 ssize_t len;1455char buffer[256];1456static char refname_buffer[256];1457int bad_name =0;14581459if(flags)1460*flags =0;14611462if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1463if(flags)1464*flags |= REF_BAD_NAME;14651466if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1467!refname_is_safe(refname)) {1468 errno = EINVAL;1469return NULL;1470}1471/*1472 * dwim_ref() uses REF_ISBROKEN to distinguish between1473 * missing refs and refs that were present but invalid,1474 * to complain about the latter to stderr.1475 *1476 * We don't know whether the ref exists, so don't set1477 * REF_ISBROKEN yet.1478 */1479 bad_name =1;1480}1481for(;;) {1482char path[PATH_MAX];1483struct stat st;1484char*buf;1485int fd;14861487if(--depth <0) {1488 errno = ELOOP;1489return NULL;1490}14911492git_snpath(path,sizeof(path),"%s", refname);14931494/*1495 * We might have to loop back here to avoid a race1496 * condition: first we lstat() the file, then we try1497 * to read it as a link or as a file. But if somebody1498 * changes the type of the file (file <-> directory1499 * <-> symlink) between the lstat() and reading, then1500 * we don't want to report that as an error but rather1501 * try again starting with the lstat().1502 */1503 stat_ref:1504if(lstat(path, &st) <0) {1505if(errno != ENOENT)1506return NULL;1507if(resolve_missing_loose_ref(refname, resolve_flags,1508 sha1, flags))1509return NULL;1510if(bad_name) {1511hashclr(sha1);1512if(flags)1513*flags |= REF_ISBROKEN;1514}1515return refname;1516}15171518/* Follow "normalized" - ie "refs/.." symlinks by hand */1519if(S_ISLNK(st.st_mode)) {1520 len =readlink(path, buffer,sizeof(buffer)-1);1521if(len <0) {1522if(errno == ENOENT || errno == EINVAL)1523/* inconsistent with lstat; retry */1524goto stat_ref;1525else1526return NULL;1527}1528 buffer[len] =0;1529if(starts_with(buffer,"refs/") &&1530!check_refname_format(buffer,0)) {1531strcpy(refname_buffer, buffer);1532 refname = refname_buffer;1533if(flags)1534*flags |= REF_ISSYMREF;1535if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1536hashclr(sha1);1537return refname;1538}1539continue;1540}1541}15421543/* Is it a directory? */1544if(S_ISDIR(st.st_mode)) {1545 errno = EISDIR;1546return NULL;1547}15481549/*1550 * Anything else, just open it and try to use it as1551 * a ref1552 */1553 fd =open(path, O_RDONLY);1554if(fd <0) {1555if(errno == ENOENT)1556/* inconsistent with lstat; retry */1557goto stat_ref;1558else1559return NULL;1560}1561 len =read_in_full(fd, buffer,sizeof(buffer)-1);1562if(len <0) {1563int save_errno = errno;1564close(fd);1565 errno = save_errno;1566return NULL;1567}1568close(fd);1569while(len &&isspace(buffer[len-1]))1570 len--;1571 buffer[len] ='\0';15721573/*1574 * Is it a symbolic ref?1575 */1576if(!starts_with(buffer,"ref:")) {1577/*1578 * Please note that FETCH_HEAD has a second1579 * line containing other data.1580 */1581if(get_sha1_hex(buffer, sha1) ||1582(buffer[40] !='\0'&& !isspace(buffer[40]))) {1583if(flags)1584*flags |= REF_ISBROKEN;1585 errno = EINVAL;1586return NULL;1587}1588if(bad_name) {1589hashclr(sha1);1590if(flags)1591*flags |= REF_ISBROKEN;1592}1593return refname;1594}1595if(flags)1596*flags |= REF_ISSYMREF;1597 buf = buffer +4;1598while(isspace(*buf))1599 buf++;1600 refname =strcpy(refname_buffer, buf);1601if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1602hashclr(sha1);1603return refname;1604}1605if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1606if(flags)1607*flags |= REF_ISBROKEN;16081609if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1610!refname_is_safe(buf)) {1611 errno = EINVAL;1612return NULL;1613}1614 bad_name =1;1615}1616}1617}16181619char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1620{1621returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1622}16231624/* The argument to filter_refs */1625struct ref_filter {1626const char*pattern;1627 each_ref_fn *fn;1628void*cb_data;1629};16301631intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1632{1633if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1634return0;1635return-1;1636}16371638intread_ref(const char*refname,unsigned char*sha1)1639{1640returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1641}16421643intref_exists(const char*refname)1644{1645unsigned char sha1[20];1646return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1647}16481649static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1650void*data)1651{1652struct ref_filter *filter = (struct ref_filter *)data;1653if(wildmatch(filter->pattern, refname,0, NULL))1654return0;1655return filter->fn(refname, sha1, flags, filter->cb_data);1656}16571658enum peel_status {1659/* object was peeled successfully: */1660 PEEL_PEELED =0,16611662/*1663 * object cannot be peeled because the named object (or an1664 * object referred to by a tag in the peel chain), does not1665 * exist.1666 */1667 PEEL_INVALID = -1,16681669/* object cannot be peeled because it is not a tag: */1670 PEEL_NON_TAG = -2,16711672/* ref_entry contains no peeled value because it is a symref: */1673 PEEL_IS_SYMREF = -3,16741675/*1676 * ref_entry cannot be peeled because it is broken (i.e., the1677 * symbolic reference cannot even be resolved to an object1678 * name):1679 */1680 PEEL_BROKEN = -41681};16821683/*1684 * Peel the named object; i.e., if the object is a tag, resolve the1685 * tag recursively until a non-tag is found. If successful, store the1686 * result to sha1 and return PEEL_PEELED. If the object is not a tag1687 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1688 * and leave sha1 unchanged.1689 */1690static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1691{1692struct object *o =lookup_unknown_object(name);16931694if(o->type == OBJ_NONE) {1695int type =sha1_object_info(name, NULL);1696if(type <0|| !object_as_type(o, type,0))1697return PEEL_INVALID;1698}16991700if(o->type != OBJ_TAG)1701return PEEL_NON_TAG;17021703 o =deref_tag_noverify(o);1704if(!o)1705return PEEL_INVALID;17061707hashcpy(sha1, o->sha1);1708return PEEL_PEELED;1709}17101711/*1712 * Peel the entry (if possible) and return its new peel_status. If1713 * repeel is true, re-peel the entry even if there is an old peeled1714 * value that is already stored in it.1715 *1716 * It is OK to call this function with a packed reference entry that1717 * might be stale and might even refer to an object that has since1718 * been garbage-collected. In such a case, if the entry has1719 * REF_KNOWS_PEELED then leave the status unchanged and return1720 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1721 */1722static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1723{1724enum peel_status status;17251726if(entry->flag & REF_KNOWS_PEELED) {1727if(repeel) {1728 entry->flag &= ~REF_KNOWS_PEELED;1729hashclr(entry->u.value.peeled);1730}else{1731returnis_null_sha1(entry->u.value.peeled) ?1732 PEEL_NON_TAG : PEEL_PEELED;1733}1734}1735if(entry->flag & REF_ISBROKEN)1736return PEEL_BROKEN;1737if(entry->flag & REF_ISSYMREF)1738return PEEL_IS_SYMREF;17391740 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1741if(status == PEEL_PEELED || status == PEEL_NON_TAG)1742 entry->flag |= REF_KNOWS_PEELED;1743return status;1744}17451746intpeel_ref(const char*refname,unsigned char*sha1)1747{1748int flag;1749unsigned char base[20];17501751if(current_ref && (current_ref->name == refname1752|| !strcmp(current_ref->name, refname))) {1753if(peel_entry(current_ref,0))1754return-1;1755hashcpy(sha1, current_ref->u.value.peeled);1756return0;1757}17581759if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1760return-1;17611762/*1763 * If the reference is packed, read its ref_entry from the1764 * cache in the hope that we already know its peeled value.1765 * We only try this optimization on packed references because1766 * (a) forcing the filling of the loose reference cache could1767 * be expensive and (b) loose references anyway usually do not1768 * have REF_KNOWS_PEELED.1769 */1770if(flag & REF_ISPACKED) {1771struct ref_entry *r =get_packed_ref(refname);1772if(r) {1773if(peel_entry(r,0))1774return-1;1775hashcpy(sha1, r->u.value.peeled);1776return0;1777}1778}17791780returnpeel_object(base, sha1);1781}17821783struct warn_if_dangling_data {1784FILE*fp;1785const char*refname;1786const struct string_list *refnames;1787const char*msg_fmt;1788};17891790static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1791int flags,void*cb_data)1792{1793struct warn_if_dangling_data *d = cb_data;1794const char*resolves_to;1795unsigned char junk[20];17961797if(!(flags & REF_ISSYMREF))1798return0;17991800 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1801if(!resolves_to1802|| (d->refname1803?strcmp(resolves_to, d->refname)1804: !string_list_has_string(d->refnames, resolves_to))) {1805return0;1806}18071808fprintf(d->fp, d->msg_fmt, refname);1809fputc('\n', d->fp);1810return0;1811}18121813voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1814{1815struct warn_if_dangling_data data;18161817 data.fp = fp;1818 data.refname = refname;1819 data.refnames = NULL;1820 data.msg_fmt = msg_fmt;1821for_each_rawref(warn_if_dangling_symref, &data);1822}18231824voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1825{1826struct warn_if_dangling_data data;18271828 data.fp = fp;1829 data.refname = NULL;1830 data.refnames = refnames;1831 data.msg_fmt = msg_fmt;1832for_each_rawref(warn_if_dangling_symref, &data);1833}18341835/*1836 * Call fn for each reference in the specified ref_cache, omitting1837 * references not in the containing_dir of base. fn is called for all1838 * references, including broken ones. If fn ever returns a non-zero1839 * value, stop the iteration and return that value; otherwise, return1840 * 0.1841 */1842static intdo_for_each_entry(struct ref_cache *refs,const char*base,1843 each_ref_entry_fn fn,void*cb_data)1844{1845struct packed_ref_cache *packed_ref_cache;1846struct ref_dir *loose_dir;1847struct ref_dir *packed_dir;1848int retval =0;18491850/*1851 * We must make sure that all loose refs are read before accessing the1852 * packed-refs file; this avoids a race condition in which loose refs1853 * are migrated to the packed-refs file by a simultaneous process, but1854 * our in-memory view is from before the migration. get_packed_ref_cache()1855 * takes care of making sure our view is up to date with what is on1856 * disk.1857 */1858 loose_dir =get_loose_refs(refs);1859if(base && *base) {1860 loose_dir =find_containing_dir(loose_dir, base,0);1861}1862if(loose_dir)1863prime_ref_dir(loose_dir);18641865 packed_ref_cache =get_packed_ref_cache(refs);1866acquire_packed_ref_cache(packed_ref_cache);1867 packed_dir =get_packed_ref_dir(packed_ref_cache);1868if(base && *base) {1869 packed_dir =find_containing_dir(packed_dir, base,0);1870}18711872if(packed_dir && loose_dir) {1873sort_ref_dir(packed_dir);1874sort_ref_dir(loose_dir);1875 retval =do_for_each_entry_in_dirs(1876 packed_dir, loose_dir, fn, cb_data);1877}else if(packed_dir) {1878sort_ref_dir(packed_dir);1879 retval =do_for_each_entry_in_dir(1880 packed_dir,0, fn, cb_data);1881}else if(loose_dir) {1882sort_ref_dir(loose_dir);1883 retval =do_for_each_entry_in_dir(1884 loose_dir,0, fn, cb_data);1885}18861887release_packed_ref_cache(packed_ref_cache);1888return retval;1889}18901891/*1892 * Call fn for each reference in the specified ref_cache for which the1893 * refname begins with base. If trim is non-zero, then trim that many1894 * characters off the beginning of each refname before passing the1895 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1896 * broken references in the iteration. If fn ever returns a non-zero1897 * value, stop the iteration and return that value; otherwise, return1898 * 0.1899 */1900static intdo_for_each_ref(struct ref_cache *refs,const char*base,1901 each_ref_fn fn,int trim,int flags,void*cb_data)1902{1903struct ref_entry_cb data;1904 data.base = base;1905 data.trim = trim;1906 data.flags = flags;1907 data.fn = fn;1908 data.cb_data = cb_data;19091910if(ref_paranoia <0)1911 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1912if(ref_paranoia)1913 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;19141915returndo_for_each_entry(refs, base, do_one_ref, &data);1916}19171918static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1919{1920unsigned char sha1[20];1921int flag;19221923if(submodule) {1924if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1925returnfn("HEAD", sha1,0, cb_data);19261927return0;1928}19291930if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1931returnfn("HEAD", sha1, flag, cb_data);19321933return0;1934}19351936inthead_ref(each_ref_fn fn,void*cb_data)1937{1938returndo_head_ref(NULL, fn, cb_data);1939}19401941inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1942{1943returndo_head_ref(submodule, fn, cb_data);1944}19451946intfor_each_ref(each_ref_fn fn,void*cb_data)1947{1948returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1949}19501951intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1952{1953returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1954}19551956intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1957{1958returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1959}19601961intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1962 each_ref_fn fn,void*cb_data)1963{1964returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1965}19661967intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1968{1969returnfor_each_ref_in("refs/tags/", fn, cb_data);1970}19711972intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1973{1974returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1975}19761977intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1978{1979returnfor_each_ref_in("refs/heads/", fn, cb_data);1980}19811982intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1983{1984returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1985}19861987intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1988{1989returnfor_each_ref_in("refs/remotes/", fn, cb_data);1990}19911992intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1993{1994returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1995}19961997intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1998{1999returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2000}20012002inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2003{2004struct strbuf buf = STRBUF_INIT;2005int ret =0;2006unsigned char sha1[20];2007int flag;20082009strbuf_addf(&buf,"%sHEAD",get_git_namespace());2010if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2011 ret =fn(buf.buf, sha1, flag, cb_data);2012strbuf_release(&buf);20132014return ret;2015}20162017intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2018{2019struct strbuf buf = STRBUF_INIT;2020int ret;2021strbuf_addf(&buf,"%srefs/",get_git_namespace());2022 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2023strbuf_release(&buf);2024return ret;2025}20262027intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2028const char*prefix,void*cb_data)2029{2030struct strbuf real_pattern = STRBUF_INIT;2031struct ref_filter filter;2032int ret;20332034if(!prefix && !starts_with(pattern,"refs/"))2035strbuf_addstr(&real_pattern,"refs/");2036else if(prefix)2037strbuf_addstr(&real_pattern, prefix);2038strbuf_addstr(&real_pattern, pattern);20392040if(!has_glob_specials(pattern)) {2041/* Append implied '/' '*' if not present. */2042if(real_pattern.buf[real_pattern.len -1] !='/')2043strbuf_addch(&real_pattern,'/');2044/* No need to check for '*', there is none. */2045strbuf_addch(&real_pattern,'*');2046}20472048 filter.pattern = real_pattern.buf;2049 filter.fn = fn;2050 filter.cb_data = cb_data;2051 ret =for_each_ref(filter_refs, &filter);20522053strbuf_release(&real_pattern);2054return ret;2055}20562057intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2058{2059returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2060}20612062intfor_each_rawref(each_ref_fn fn,void*cb_data)2063{2064returndo_for_each_ref(&ref_cache,"", fn,0,2065 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2066}20672068const char*prettify_refname(const char*name)2069{2070return name + (2071starts_with(name,"refs/heads/") ?11:2072starts_with(name,"refs/tags/") ?10:2073starts_with(name,"refs/remotes/") ?13:20740);2075}20762077static const char*ref_rev_parse_rules[] = {2078"%.*s",2079"refs/%.*s",2080"refs/tags/%.*s",2081"refs/heads/%.*s",2082"refs/remotes/%.*s",2083"refs/remotes/%.*s/HEAD",2084 NULL2085};20862087intrefname_match(const char*abbrev_name,const char*full_name)2088{2089const char**p;2090const int abbrev_name_len =strlen(abbrev_name);20912092for(p = ref_rev_parse_rules; *p; p++) {2093if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2094return1;2095}2096}20972098return0;2099}21002101/* This function should make sure errno is meaningful on error */2102static struct ref_lock *verify_lock(struct ref_lock *lock,2103const unsigned char*old_sha1,int mustexist)2104{2105if(read_ref_full(lock->ref_name,2106 mustexist ? RESOLVE_REF_READING :0,2107 lock->old_sha1, NULL)) {2108int save_errno = errno;2109error("Can't verify ref%s", lock->ref_name);2110unlock_ref(lock);2111 errno = save_errno;2112return NULL;2113}2114if(hashcmp(lock->old_sha1, old_sha1)) {2115error("Ref%sis at%sbut expected%s", lock->ref_name,2116sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2117unlock_ref(lock);2118 errno = EBUSY;2119return NULL;2120}2121return lock;2122}21232124static intremove_empty_directories(const char*file)2125{2126/* we want to create a file but there is a directory there;2127 * if that is an empty directory (or a directory that contains2128 * only empty directories), remove them.2129 */2130struct strbuf path;2131int result, save_errno;21322133strbuf_init(&path,20);2134strbuf_addstr(&path, file);21352136 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2137 save_errno = errno;21382139strbuf_release(&path);2140 errno = save_errno;21412142return result;2143}21442145/*2146 * *string and *len will only be substituted, and *string returned (for2147 * later free()ing) if the string passed in is a magic short-hand form2148 * to name a branch.2149 */2150static char*substitute_branch_name(const char**string,int*len)2151{2152struct strbuf buf = STRBUF_INIT;2153int ret =interpret_branch_name(*string, *len, &buf);21542155if(ret == *len) {2156size_t size;2157*string =strbuf_detach(&buf, &size);2158*len = size;2159return(char*)*string;2160}21612162return NULL;2163}21642165intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2166{2167char*last_branch =substitute_branch_name(&str, &len);2168const char**p, *r;2169int refs_found =0;21702171*ref = NULL;2172for(p = ref_rev_parse_rules; *p; p++) {2173char fullref[PATH_MAX];2174unsigned char sha1_from_ref[20];2175unsigned char*this_result;2176int flag;21772178 this_result = refs_found ? sha1_from_ref : sha1;2179mksnpath(fullref,sizeof(fullref), *p, len, str);2180 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2181 this_result, &flag);2182if(r) {2183if(!refs_found++)2184*ref =xstrdup(r);2185if(!warn_ambiguous_refs)2186break;2187}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2188warning("ignoring dangling symref%s.", fullref);2189}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2190warning("ignoring broken ref%s.", fullref);2191}2192}2193free(last_branch);2194return refs_found;2195}21962197intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2198{2199char*last_branch =substitute_branch_name(&str, &len);2200const char**p;2201int logs_found =0;22022203*log = NULL;2204for(p = ref_rev_parse_rules; *p; p++) {2205unsigned char hash[20];2206char path[PATH_MAX];2207const char*ref, *it;22082209mksnpath(path,sizeof(path), *p, len, str);2210 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2211 hash, NULL);2212if(!ref)2213continue;2214if(reflog_exists(path))2215 it = path;2216else if(strcmp(ref, path) &&reflog_exists(ref))2217 it = ref;2218else2219continue;2220if(!logs_found++) {2221*log =xstrdup(it);2222hashcpy(sha1, hash);2223}2224if(!warn_ambiguous_refs)2225break;2226}2227free(last_branch);2228return logs_found;2229}22302231/*2232 * Locks a ref returning the lock on success and NULL on failure.2233 * On failure errno is set to something meaningful.2234 */2235static struct ref_lock *lock_ref_sha1_basic(const char*refname,2236const unsigned char*old_sha1,2237const struct string_list *skip,2238int flags,int*type_p)2239{2240char*ref_file;2241const char*orig_refname = refname;2242struct ref_lock *lock;2243int last_errno =0;2244int type, lflags;2245int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2246int resolve_flags =0;2247int missing =0;2248int attempts_remaining =3;22492250 lock =xcalloc(1,sizeof(struct ref_lock));2251 lock->lock_fd = -1;22522253if(mustexist)2254 resolve_flags |= RESOLVE_REF_READING;2255if(flags & REF_DELETING) {2256 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2257if(flags & REF_NODEREF)2258 resolve_flags |= RESOLVE_REF_NO_RECURSE;2259}22602261 refname =resolve_ref_unsafe(refname, resolve_flags,2262 lock->old_sha1, &type);2263if(!refname && errno == EISDIR) {2264/* we are trying to lock foo but we used to2265 * have foo/bar which now does not exist;2266 * it is normal for the empty directory 'foo'2267 * to remain.2268 */2269 ref_file =git_path("%s", orig_refname);2270if(remove_empty_directories(ref_file)) {2271 last_errno = errno;2272error("there are still refs under '%s'", orig_refname);2273goto error_return;2274}2275 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2276 lock->old_sha1, &type);2277}2278if(type_p)2279*type_p = type;2280if(!refname) {2281 last_errno = errno;2282error("unable to resolve reference%s:%s",2283 orig_refname,strerror(errno));2284goto error_return;2285}2286 missing =is_null_sha1(lock->old_sha1);2287/* When the ref did not exist and we are creating it,2288 * make sure there is no existing ref that is packed2289 * whose name begins with our refname, nor a ref whose2290 * name is a proper prefix of our refname.2291 */2292if(missing &&2293!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2294 last_errno = ENOTDIR;2295goto error_return;2296}22972298 lock->lk =xcalloc(1,sizeof(struct lock_file));22992300 lflags =0;2301if(flags & REF_NODEREF) {2302 refname = orig_refname;2303 lflags |= LOCK_NO_DEREF;2304}2305 lock->ref_name =xstrdup(refname);2306 lock->orig_ref_name =xstrdup(orig_refname);2307 ref_file =git_path("%s", refname);2308if(missing)2309 lock->force_write =1;2310if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2311 lock->force_write =1;23122313 retry:2314switch(safe_create_leading_directories(ref_file)) {2315case SCLD_OK:2316break;/* success */2317case SCLD_VANISHED:2318if(--attempts_remaining >0)2319goto retry;2320/* fall through */2321default:2322 last_errno = errno;2323error("unable to create directory for%s", ref_file);2324goto error_return;2325}23262327 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2328if(lock->lock_fd <0) {2329 last_errno = errno;2330if(errno == ENOENT && --attempts_remaining >0)2331/*2332 * Maybe somebody just deleted one of the2333 * directories leading to ref_file. Try2334 * again:2335 */2336goto retry;2337else{2338struct strbuf err = STRBUF_INIT;2339unable_to_lock_message(ref_file, errno, &err);2340error("%s", err.buf);2341strbuf_release(&err);2342goto error_return;2343}2344}2345return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23462347 error_return:2348unlock_ref(lock);2349 errno = last_errno;2350return NULL;2351}23522353struct ref_lock *lock_any_ref_for_update(const char*refname,2354const unsigned char*old_sha1,2355int flags,int*type_p)2356{2357returnlock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);2358}23592360/*2361 * Write an entry to the packed-refs file for the specified refname.2362 * If peeled is non-NULL, write it as the entry's peeled value.2363 */2364static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2365unsigned char*peeled)2366{2367fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2368if(peeled)2369fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2370}23712372/*2373 * An each_ref_entry_fn that writes the entry to a packed-refs file.2374 */2375static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2376{2377enum peel_status peel_status =peel_entry(entry,0);23782379if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2380error("internal error:%sis not a valid packed reference!",2381 entry->name);2382write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2383 peel_status == PEEL_PEELED ?2384 entry->u.value.peeled : NULL);2385return0;2386}23872388/* This should return a meaningful errno on failure */2389intlock_packed_refs(int flags)2390{2391struct packed_ref_cache *packed_ref_cache;23922393if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2394return-1;2395/*2396 * Get the current packed-refs while holding the lock. If the2397 * packed-refs file has been modified since we last read it,2398 * this will automatically invalidate the cache and re-read2399 * the packed-refs file.2400 */2401 packed_ref_cache =get_packed_ref_cache(&ref_cache);2402 packed_ref_cache->lock = &packlock;2403/* Increment the reference count to prevent it from being freed: */2404acquire_packed_ref_cache(packed_ref_cache);2405return0;2406}24072408/*2409 * Commit the packed refs changes.2410 * On error we must make sure that errno contains a meaningful value.2411 */2412intcommit_packed_refs(void)2413{2414struct packed_ref_cache *packed_ref_cache =2415get_packed_ref_cache(&ref_cache);2416int error =0;2417int save_errno =0;2418FILE*out;24192420if(!packed_ref_cache->lock)2421die("internal error: packed-refs not locked");24222423 out =fdopen_lock_file(packed_ref_cache->lock,"w");2424if(!out)2425die_errno("unable to fdopen packed-refs descriptor");24262427fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2428do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24290, write_packed_entry_fn, out);24302431if(commit_lock_file(packed_ref_cache->lock)) {2432 save_errno = errno;2433 error = -1;2434}2435 packed_ref_cache->lock = NULL;2436release_packed_ref_cache(packed_ref_cache);2437 errno = save_errno;2438return error;2439}24402441voidrollback_packed_refs(void)2442{2443struct packed_ref_cache *packed_ref_cache =2444get_packed_ref_cache(&ref_cache);24452446if(!packed_ref_cache->lock)2447die("internal error: packed-refs not locked");2448rollback_lock_file(packed_ref_cache->lock);2449 packed_ref_cache->lock = NULL;2450release_packed_ref_cache(packed_ref_cache);2451clear_packed_ref_cache(&ref_cache);2452}24532454struct ref_to_prune {2455struct ref_to_prune *next;2456unsigned char sha1[20];2457char name[FLEX_ARRAY];2458};24592460struct pack_refs_cb_data {2461unsigned int flags;2462struct ref_dir *packed_refs;2463struct ref_to_prune *ref_to_prune;2464};24652466/*2467 * An each_ref_entry_fn that is run over loose references only. If2468 * the loose reference can be packed, add an entry in the packed ref2469 * cache. If the reference should be pruned, also add it to2470 * ref_to_prune in the pack_refs_cb_data.2471 */2472static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2473{2474struct pack_refs_cb_data *cb = cb_data;2475enum peel_status peel_status;2476struct ref_entry *packed_entry;2477int is_tag_ref =starts_with(entry->name,"refs/tags/");24782479/* ALWAYS pack tags */2480if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2481return0;24822483/* Do not pack symbolic or broken refs: */2484if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2485return0;24862487/* Add a packed ref cache entry equivalent to the loose entry. */2488 peel_status =peel_entry(entry,1);2489if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2490die("internal error peeling reference%s(%s)",2491 entry->name,sha1_to_hex(entry->u.value.sha1));2492 packed_entry =find_ref(cb->packed_refs, entry->name);2493if(packed_entry) {2494/* Overwrite existing packed entry with info from loose entry */2495 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2496hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2497}else{2498 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2499 REF_ISPACKED | REF_KNOWS_PEELED,0);2500add_ref(cb->packed_refs, packed_entry);2501}2502hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25032504/* Schedule the loose reference for pruning if requested. */2505if((cb->flags & PACK_REFS_PRUNE)) {2506int namelen =strlen(entry->name) +1;2507struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2508hashcpy(n->sha1, entry->u.value.sha1);2509strcpy(n->name, entry->name);2510 n->next = cb->ref_to_prune;2511 cb->ref_to_prune = n;2512}2513return0;2514}25152516/*2517 * Remove empty parents, but spare refs/ and immediate subdirs.2518 * Note: munges *name.2519 */2520static voidtry_remove_empty_parents(char*name)2521{2522char*p, *q;2523int i;2524 p = name;2525for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2526while(*p && *p !='/')2527 p++;2528/* tolerate duplicate slashes; see check_refname_format() */2529while(*p =='/')2530 p++;2531}2532for(q = p; *q; q++)2533;2534while(1) {2535while(q > p && *q !='/')2536 q--;2537while(q > p && *(q-1) =='/')2538 q--;2539if(q == p)2540break;2541*q ='\0';2542if(rmdir(git_path("%s", name)))2543break;2544}2545}25462547/* make sure nobody touched the ref, and unlink */2548static voidprune_ref(struct ref_to_prune *r)2549{2550struct ref_transaction *transaction;2551struct strbuf err = STRBUF_INIT;25522553if(check_refname_format(r->name,0))2554return;25552556 transaction =ref_transaction_begin(&err);2557if(!transaction ||2558ref_transaction_delete(transaction, r->name, r->sha1,2559 REF_ISPRUNING,1, NULL, &err) ||2560ref_transaction_commit(transaction, &err)) {2561ref_transaction_free(transaction);2562error("%s", err.buf);2563strbuf_release(&err);2564return;2565}2566ref_transaction_free(transaction);2567strbuf_release(&err);2568try_remove_empty_parents(r->name);2569}25702571static voidprune_refs(struct ref_to_prune *r)2572{2573while(r) {2574prune_ref(r);2575 r = r->next;2576}2577}25782579intpack_refs(unsigned int flags)2580{2581struct pack_refs_cb_data cbdata;25822583memset(&cbdata,0,sizeof(cbdata));2584 cbdata.flags = flags;25852586lock_packed_refs(LOCK_DIE_ON_ERROR);2587 cbdata.packed_refs =get_packed_refs(&ref_cache);25882589do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2590 pack_if_possible_fn, &cbdata);25912592if(commit_packed_refs())2593die_errno("unable to overwrite old ref-pack file");25942595prune_refs(cbdata.ref_to_prune);2596return0;2597}25982599intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2600{2601struct ref_dir *packed;2602struct string_list_item *refname;2603int ret, needs_repacking =0, removed =0;26042605assert(err);26062607/* Look for a packed ref */2608for_each_string_list_item(refname, refnames) {2609if(get_packed_ref(refname->string)) {2610 needs_repacking =1;2611break;2612}2613}26142615/* Avoid locking if we have nothing to do */2616if(!needs_repacking)2617return0;/* no refname exists in packed refs */26182619if(lock_packed_refs(0)) {2620unable_to_lock_message(git_path("packed-refs"), errno, err);2621return-1;2622}2623 packed =get_packed_refs(&ref_cache);26242625/* Remove refnames from the cache */2626for_each_string_list_item(refname, refnames)2627if(remove_entry(packed, refname->string) != -1)2628 removed =1;2629if(!removed) {2630/*2631 * All packed entries disappeared while we were2632 * acquiring the lock.2633 */2634rollback_packed_refs();2635return0;2636}26372638/* Write what remains */2639 ret =commit_packed_refs();2640if(ret)2641strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2642strerror(errno));2643return ret;2644}26452646static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2647{2648assert(err);26492650if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2651/*2652 * loose. The loose file name is the same as the2653 * lockfile name, minus ".lock":2654 */2655char*loose_filename =get_locked_file_path(lock->lk);2656int res =unlink_or_msg(loose_filename, err);2657free(loose_filename);2658if(res)2659return1;2660}2661return0;2662}26632664intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2665{2666struct ref_transaction *transaction;2667struct strbuf err = STRBUF_INIT;26682669 transaction =ref_transaction_begin(&err);2670if(!transaction ||2671ref_transaction_delete(transaction, refname, sha1, delopt,2672 sha1 && !is_null_sha1(sha1), NULL, &err) ||2673ref_transaction_commit(transaction, &err)) {2674error("%s", err.buf);2675ref_transaction_free(transaction);2676strbuf_release(&err);2677return1;2678}2679ref_transaction_free(transaction);2680strbuf_release(&err);2681return0;2682}26832684/*2685 * People using contrib's git-new-workdir have .git/logs/refs ->2686 * /some/other/path/.git/logs/refs, and that may live on another device.2687 *2688 * IOW, to avoid cross device rename errors, the temporary renamed log must2689 * live into logs/refs.2690 */2691#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"26922693static intrename_tmp_log(const char*newrefname)2694{2695int attempts_remaining =4;26962697 retry:2698switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2699case SCLD_OK:2700break;/* success */2701case SCLD_VANISHED:2702if(--attempts_remaining >0)2703goto retry;2704/* fall through */2705default:2706error("unable to create directory for%s", newrefname);2707return-1;2708}27092710if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2711if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2712/*2713 * rename(a, b) when b is an existing2714 * directory ought to result in ISDIR, but2715 * Solaris 5.8 gives ENOTDIR. Sheesh.2716 */2717if(remove_empty_directories(git_path("logs/%s", newrefname))) {2718error("Directory not empty: logs/%s", newrefname);2719return-1;2720}2721goto retry;2722}else if(errno == ENOENT && --attempts_remaining >0) {2723/*2724 * Maybe another process just deleted one of2725 * the directories in the path to newrefname.2726 * Try again from the beginning.2727 */2728goto retry;2729}else{2730error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2731 newrefname,strerror(errno));2732return-1;2733}2734}2735return0;2736}27372738static intrename_ref_available(const char*oldname,const char*newname)2739{2740struct string_list skip = STRING_LIST_INIT_NODUP;2741int ret;27422743string_list_insert(&skip, oldname);2744 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2745&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2746string_list_clear(&skip,0);2747return ret;2748}27492750static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2751const char*logmsg);27522753intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2754{2755unsigned char sha1[20], orig_sha1[20];2756int flag =0, logmoved =0;2757struct ref_lock *lock;2758struct stat loginfo;2759int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2760const char*symref = NULL;27612762if(log &&S_ISLNK(loginfo.st_mode))2763returnerror("reflog for%sis a symlink", oldrefname);27642765 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2766 orig_sha1, &flag);2767if(flag & REF_ISSYMREF)2768returnerror("refname%sis a symbolic ref, renaming it is not supported",2769 oldrefname);2770if(!symref)2771returnerror("refname%snot found", oldrefname);27722773if(!rename_ref_available(oldrefname, newrefname))2774return1;27752776if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2777returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2778 oldrefname,strerror(errno));27792780if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2781error("unable to delete old%s", oldrefname);2782goto rollback;2783}27842785if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2786delete_ref(newrefname, sha1, REF_NODEREF)) {2787if(errno==EISDIR) {2788if(remove_empty_directories(git_path("%s", newrefname))) {2789error("Directory not empty:%s", newrefname);2790goto rollback;2791}2792}else{2793error("unable to delete existing%s", newrefname);2794goto rollback;2795}2796}27972798if(log &&rename_tmp_log(newrefname))2799goto rollback;28002801 logmoved = log;28022803 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2804if(!lock) {2805error("unable to lock%sfor update", newrefname);2806goto rollback;2807}2808 lock->force_write =1;2809hashcpy(lock->old_sha1, orig_sha1);2810if(write_ref_sha1(lock, orig_sha1, logmsg)) {2811error("unable to write current sha1 into%s", newrefname);2812goto rollback;2813}28142815return0;28162817 rollback:2818 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2819if(!lock) {2820error("unable to lock%sfor rollback", oldrefname);2821goto rollbacklog;2822}28232824 lock->force_write =1;2825 flag = log_all_ref_updates;2826 log_all_ref_updates =0;2827if(write_ref_sha1(lock, orig_sha1, NULL))2828error("unable to write current sha1 into%s", oldrefname);2829 log_all_ref_updates = flag;28302831 rollbacklog:2832if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2833error("unable to restore logfile%sfrom%s:%s",2834 oldrefname, newrefname,strerror(errno));2835if(!logmoved && log &&2836rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2837error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2838 oldrefname,strerror(errno));28392840return1;2841}28422843intclose_ref(struct ref_lock *lock)2844{2845if(close_lock_file(lock->lk))2846return-1;2847 lock->lock_fd = -1;2848return0;2849}28502851intcommit_ref(struct ref_lock *lock)2852{2853if(commit_lock_file(lock->lk))2854return-1;2855 lock->lock_fd = -1;2856return0;2857}28582859voidunlock_ref(struct ref_lock *lock)2860{2861/* Do not free lock->lk -- atexit() still looks at them */2862if(lock->lk)2863rollback_lock_file(lock->lk);2864free(lock->ref_name);2865free(lock->orig_ref_name);2866free(lock);2867}28682869/*2870 * copy the reflog message msg to buf, which has been allocated sufficiently2871 * large, while cleaning up the whitespaces. Especially, convert LF to space,2872 * because reflog file is one line per entry.2873 */2874static intcopy_msg(char*buf,const char*msg)2875{2876char*cp = buf;2877char c;2878int wasspace =1;28792880*cp++ ='\t';2881while((c = *msg++)) {2882if(wasspace &&isspace(c))2883continue;2884 wasspace =isspace(c);2885if(wasspace)2886 c =' ';2887*cp++ = c;2888}2889while(buf < cp &&isspace(cp[-1]))2890 cp--;2891*cp++ ='\n';2892return cp - buf;2893}28942895/* This function must set a meaningful errno on failure */2896intlog_ref_setup(const char*refname,char*logfile,int bufsize)2897{2898int logfd, oflags = O_APPEND | O_WRONLY;28992900git_snpath(logfile, bufsize,"logs/%s", refname);2901if(log_all_ref_updates &&2902(starts_with(refname,"refs/heads/") ||2903starts_with(refname,"refs/remotes/") ||2904starts_with(refname,"refs/notes/") ||2905!strcmp(refname,"HEAD"))) {2906if(safe_create_leading_directories(logfile) <0) {2907int save_errno = errno;2908error("unable to create directory for%s", logfile);2909 errno = save_errno;2910return-1;2911}2912 oflags |= O_CREAT;2913}29142915 logfd =open(logfile, oflags,0666);2916if(logfd <0) {2917if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2918return0;29192920if(errno == EISDIR) {2921if(remove_empty_directories(logfile)) {2922int save_errno = errno;2923error("There are still logs under '%s'",2924 logfile);2925 errno = save_errno;2926return-1;2927}2928 logfd =open(logfile, oflags,0666);2929}29302931if(logfd <0) {2932int save_errno = errno;2933error("Unable to append to%s:%s", logfile,2934strerror(errno));2935 errno = save_errno;2936return-1;2937}2938}29392940adjust_shared_perm(logfile);2941close(logfd);2942return0;2943}29442945static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2946const unsigned char*new_sha1,const char*msg)2947{2948int logfd, result, written, oflags = O_APPEND | O_WRONLY;2949unsigned maxlen, len;2950int msglen;2951char log_file[PATH_MAX];2952char*logrec;2953const char*committer;29542955if(log_all_ref_updates <0)2956 log_all_ref_updates = !is_bare_repository();29572958 result =log_ref_setup(refname, log_file,sizeof(log_file));2959if(result)2960return result;29612962 logfd =open(log_file, oflags);2963if(logfd <0)2964return0;2965 msglen = msg ?strlen(msg) :0;2966 committer =git_committer_info(0);2967 maxlen =strlen(committer) + msglen +100;2968 logrec =xmalloc(maxlen);2969 len =sprintf(logrec,"%s %s %s\n",2970sha1_to_hex(old_sha1),2971sha1_to_hex(new_sha1),2972 committer);2973if(msglen)2974 len +=copy_msg(logrec + len -1, msg) -1;2975 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2976free(logrec);2977if(written != len) {2978int save_errno = errno;2979close(logfd);2980error("Unable to append to%s", log_file);2981 errno = save_errno;2982return-1;2983}2984if(close(logfd)) {2985int save_errno = errno;2986error("Unable to append to%s", log_file);2987 errno = save_errno;2988return-1;2989}2990return0;2991}29922993intis_branch(const char*refname)2994{2995return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");2996}29972998/*2999 * Write sha1 into the ref specified by the lock. Make sure that errno3000 * is sane on error.3001 */3002static intwrite_ref_sha1(struct ref_lock *lock,3003const unsigned char*sha1,const char*logmsg)3004{3005static char term ='\n';3006struct object *o;30073008if(!lock) {3009 errno = EINVAL;3010return-1;3011}3012if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3013unlock_ref(lock);3014return0;3015}3016 o =parse_object(sha1);3017if(!o) {3018error("Trying to write ref%swith nonexistent object%s",3019 lock->ref_name,sha1_to_hex(sha1));3020unlock_ref(lock);3021 errno = EINVAL;3022return-1;3023}3024if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3025error("Trying to write non-commit object%sto branch%s",3026sha1_to_hex(sha1), lock->ref_name);3027unlock_ref(lock);3028 errno = EINVAL;3029return-1;3030}3031if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3032write_in_full(lock->lock_fd, &term,1) !=1||3033close_ref(lock) <0) {3034int save_errno = errno;3035error("Couldn't write%s", lock->lk->filename.buf);3036unlock_ref(lock);3037 errno = save_errno;3038return-1;3039}3040clear_loose_ref_cache(&ref_cache);3041if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3042(strcmp(lock->ref_name, lock->orig_ref_name) &&3043log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3044unlock_ref(lock);3045return-1;3046}3047if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3048/*3049 * Special hack: If a branch is updated directly and HEAD3050 * points to it (may happen on the remote side of a push3051 * for example) then logically the HEAD reflog should be3052 * updated too.3053 * A generic solution implies reverse symref information,3054 * but finding all symrefs pointing to the given branch3055 * would be rather costly for this rare event (the direct3056 * update of a branch) to be worth it. So let's cheat and3057 * check with HEAD only which should cover 99% of all usage3058 * scenarios (even 100% of the default ones).3059 */3060unsigned char head_sha1[20];3061int head_flag;3062const char*head_ref;3063 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3064 head_sha1, &head_flag);3065if(head_ref && (head_flag & REF_ISSYMREF) &&3066!strcmp(head_ref, lock->ref_name))3067log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3068}3069if(commit_ref(lock)) {3070error("Couldn't set%s", lock->ref_name);3071unlock_ref(lock);3072return-1;3073}3074unlock_ref(lock);3075return0;3076}30773078intcreate_symref(const char*ref_target,const char*refs_heads_master,3079const char*logmsg)3080{3081const char*lockpath;3082char ref[1000];3083int fd, len, written;3084char*git_HEAD =git_pathdup("%s", ref_target);3085unsigned char old_sha1[20], new_sha1[20];30863087if(logmsg &&read_ref(ref_target, old_sha1))3088hashclr(old_sha1);30893090if(safe_create_leading_directories(git_HEAD) <0)3091returnerror("unable to create directory for%s", git_HEAD);30923093#ifndef NO_SYMLINK_HEAD3094if(prefer_symlink_refs) {3095unlink(git_HEAD);3096if(!symlink(refs_heads_master, git_HEAD))3097goto done;3098fprintf(stderr,"no symlink - falling back to symbolic ref\n");3099}3100#endif31013102 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3103if(sizeof(ref) <= len) {3104error("refname too long:%s", refs_heads_master);3105goto error_free_return;3106}3107 lockpath =mkpath("%s.lock", git_HEAD);3108 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3109if(fd <0) {3110error("Unable to open%sfor writing", lockpath);3111goto error_free_return;3112}3113 written =write_in_full(fd, ref, len);3114if(close(fd) !=0|| written != len) {3115error("Unable to write to%s", lockpath);3116goto error_unlink_return;3117}3118if(rename(lockpath, git_HEAD) <0) {3119error("Unable to create%s", git_HEAD);3120goto error_unlink_return;3121}3122if(adjust_shared_perm(git_HEAD)) {3123error("Unable to fix permissions on%s", lockpath);3124 error_unlink_return:3125unlink_or_warn(lockpath);3126 error_free_return:3127free(git_HEAD);3128return-1;3129}31303131#ifndef NO_SYMLINK_HEAD3132 done:3133#endif3134if(logmsg && !read_ref(refs_heads_master, new_sha1))3135log_ref_write(ref_target, old_sha1, new_sha1, logmsg);31363137free(git_HEAD);3138return0;3139}31403141struct read_ref_at_cb {3142const char*refname;3143unsigned long at_time;3144int cnt;3145int reccnt;3146unsigned char*sha1;3147int found_it;31483149unsigned char osha1[20];3150unsigned char nsha1[20];3151int tz;3152unsigned long date;3153char**msg;3154unsigned long*cutoff_time;3155int*cutoff_tz;3156int*cutoff_cnt;3157};31583159static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3160const char*email,unsigned long timestamp,int tz,3161const char*message,void*cb_data)3162{3163struct read_ref_at_cb *cb = cb_data;31643165 cb->reccnt++;3166 cb->tz = tz;3167 cb->date = timestamp;31683169if(timestamp <= cb->at_time || cb->cnt ==0) {3170if(cb->msg)3171*cb->msg =xstrdup(message);3172if(cb->cutoff_time)3173*cb->cutoff_time = timestamp;3174if(cb->cutoff_tz)3175*cb->cutoff_tz = tz;3176if(cb->cutoff_cnt)3177*cb->cutoff_cnt = cb->reccnt -1;3178/*3179 * we have not yet updated cb->[n|o]sha1 so they still3180 * hold the values for the previous record.3181 */3182if(!is_null_sha1(cb->osha1)) {3183hashcpy(cb->sha1, nsha1);3184if(hashcmp(cb->osha1, nsha1))3185warning("Log for ref%shas gap after%s.",3186 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3187}3188else if(cb->date == cb->at_time)3189hashcpy(cb->sha1, nsha1);3190else if(hashcmp(nsha1, cb->sha1))3191warning("Log for ref%sunexpectedly ended on%s.",3192 cb->refname,show_date(cb->date, cb->tz,3193 DATE_RFC2822));3194hashcpy(cb->osha1, osha1);3195hashcpy(cb->nsha1, nsha1);3196 cb->found_it =1;3197return1;3198}3199hashcpy(cb->osha1, osha1);3200hashcpy(cb->nsha1, nsha1);3201if(cb->cnt >0)3202 cb->cnt--;3203return0;3204}32053206static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3207const char*email,unsigned long timestamp,3208int tz,const char*message,void*cb_data)3209{3210struct read_ref_at_cb *cb = cb_data;32113212if(cb->msg)3213*cb->msg =xstrdup(message);3214if(cb->cutoff_time)3215*cb->cutoff_time = timestamp;3216if(cb->cutoff_tz)3217*cb->cutoff_tz = tz;3218if(cb->cutoff_cnt)3219*cb->cutoff_cnt = cb->reccnt;3220hashcpy(cb->sha1, osha1);3221if(is_null_sha1(cb->sha1))3222hashcpy(cb->sha1, nsha1);3223/* We just want the first entry */3224return1;3225}32263227intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3228unsigned char*sha1,char**msg,3229unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3230{3231struct read_ref_at_cb cb;32323233memset(&cb,0,sizeof(cb));3234 cb.refname = refname;3235 cb.at_time = at_time;3236 cb.cnt = cnt;3237 cb.msg = msg;3238 cb.cutoff_time = cutoff_time;3239 cb.cutoff_tz = cutoff_tz;3240 cb.cutoff_cnt = cutoff_cnt;3241 cb.sha1 = sha1;32423243for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);32443245if(!cb.reccnt) {3246if(flags & GET_SHA1_QUIETLY)3247exit(128);3248else3249die("Log for%sis empty.", refname);3250}3251if(cb.found_it)3252return0;32533254for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);32553256return1;3257}32583259intreflog_exists(const char*refname)3260{3261struct stat st;32623263return!lstat(git_path("logs/%s", refname), &st) &&3264S_ISREG(st.st_mode);3265}32663267intdelete_reflog(const char*refname)3268{3269returnremove_path(git_path("logs/%s", refname));3270}32713272static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3273{3274unsigned char osha1[20], nsha1[20];3275char*email_end, *message;3276unsigned long timestamp;3277int tz;32783279/* old SP new SP name <email> SP time TAB msg LF */3280if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3281get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3282get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3283!(email_end =strchr(sb->buf +82,'>')) ||3284 email_end[1] !=' '||3285!(timestamp =strtoul(email_end +2, &message,10)) ||3286!message || message[0] !=' '||3287(message[1] !='+'&& message[1] !='-') ||3288!isdigit(message[2]) || !isdigit(message[3]) ||3289!isdigit(message[4]) || !isdigit(message[5]))3290return0;/* corrupt? */3291 email_end[1] ='\0';3292 tz =strtol(message +1, NULL,10);3293if(message[6] !='\t')3294 message +=6;3295else3296 message +=7;3297returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3298}32993300static char*find_beginning_of_line(char*bob,char*scan)3301{3302while(bob < scan && *(--scan) !='\n')3303;/* keep scanning backwards */3304/*3305 * Return either beginning of the buffer, or LF at the end of3306 * the previous line.3307 */3308return scan;3309}33103311intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3312{3313struct strbuf sb = STRBUF_INIT;3314FILE*logfp;3315long pos;3316int ret =0, at_tail =1;33173318 logfp =fopen(git_path("logs/%s", refname),"r");3319if(!logfp)3320return-1;33213322/* Jump to the end */3323if(fseek(logfp,0, SEEK_END) <0)3324returnerror("cannot seek back reflog for%s:%s",3325 refname,strerror(errno));3326 pos =ftell(logfp);3327while(!ret &&0< pos) {3328int cnt;3329size_t nread;3330char buf[BUFSIZ];3331char*endp, *scanp;33323333/* Fill next block from the end */3334 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3335if(fseek(logfp, pos - cnt, SEEK_SET))3336returnerror("cannot seek back reflog for%s:%s",3337 refname,strerror(errno));3338 nread =fread(buf, cnt,1, logfp);3339if(nread !=1)3340returnerror("cannot read%dbytes from reflog for%s:%s",3341 cnt, refname,strerror(errno));3342 pos -= cnt;33433344 scanp = endp = buf + cnt;3345if(at_tail && scanp[-1] =='\n')3346/* Looking at the final LF at the end of the file */3347 scanp--;3348 at_tail =0;33493350while(buf < scanp) {3351/*3352 * terminating LF of the previous line, or the beginning3353 * of the buffer.3354 */3355char*bp;33563357 bp =find_beginning_of_line(buf, scanp);33583359if(*bp =='\n') {3360/*3361 * The newline is the end of the previous line,3362 * so we know we have complete line starting3363 * at (bp + 1). Prefix it onto any prior data3364 * we collected for the line and process it.3365 */3366strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3367 scanp = bp;3368 endp = bp +1;3369 ret =show_one_reflog_ent(&sb, fn, cb_data);3370strbuf_reset(&sb);3371if(ret)3372break;3373}else if(!pos) {3374/*3375 * We are at the start of the buffer, and the3376 * start of the file; there is no previous3377 * line, and we have everything for this one.3378 * Process it, and we can end the loop.3379 */3380strbuf_splice(&sb,0,0, buf, endp - buf);3381 ret =show_one_reflog_ent(&sb, fn, cb_data);3382strbuf_reset(&sb);3383break;3384}33853386if(bp == buf) {3387/*3388 * We are at the start of the buffer, and there3389 * is more file to read backwards. Which means3390 * we are in the middle of a line. Note that we3391 * may get here even if *bp was a newline; that3392 * just means we are at the exact end of the3393 * previous line, rather than some spot in the3394 * middle.3395 *3396 * Save away what we have to be combined with3397 * the data from the next read.3398 */3399strbuf_splice(&sb,0,0, buf, endp - buf);3400break;3401}3402}34033404}3405if(!ret && sb.len)3406die("BUG: reverse reflog parser had leftover data");34073408fclose(logfp);3409strbuf_release(&sb);3410return ret;3411}34123413intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3414{3415FILE*logfp;3416struct strbuf sb = STRBUF_INIT;3417int ret =0;34183419 logfp =fopen(git_path("logs/%s", refname),"r");3420if(!logfp)3421return-1;34223423while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3424 ret =show_one_reflog_ent(&sb, fn, cb_data);3425fclose(logfp);3426strbuf_release(&sb);3427return ret;3428}3429/*3430 * Call fn for each reflog in the namespace indicated by name. name3431 * must be empty or end with '/'. Name will be used as a scratch3432 * space, but its contents will be restored before return.3433 */3434static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3435{3436DIR*d =opendir(git_path("logs/%s", name->buf));3437int retval =0;3438struct dirent *de;3439int oldlen = name->len;34403441if(!d)3442return name->len ? errno :0;34433444while((de =readdir(d)) != NULL) {3445struct stat st;34463447if(de->d_name[0] =='.')3448continue;3449if(ends_with(de->d_name,".lock"))3450continue;3451strbuf_addstr(name, de->d_name);3452if(stat(git_path("logs/%s", name->buf), &st) <0) {3453;/* silently ignore */3454}else{3455if(S_ISDIR(st.st_mode)) {3456strbuf_addch(name,'/');3457 retval =do_for_each_reflog(name, fn, cb_data);3458}else{3459unsigned char sha1[20];3460if(read_ref_full(name->buf,0, sha1, NULL))3461 retval =error("bad ref for%s", name->buf);3462else3463 retval =fn(name->buf, sha1,0, cb_data);3464}3465if(retval)3466break;3467}3468strbuf_setlen(name, oldlen);3469}3470closedir(d);3471return retval;3472}34733474intfor_each_reflog(each_ref_fn fn,void*cb_data)3475{3476int retval;3477struct strbuf name;3478strbuf_init(&name, PATH_MAX);3479 retval =do_for_each_reflog(&name, fn, cb_data);3480strbuf_release(&name);3481return retval;3482}34833484/**3485 * Information needed for a single ref update. Set new_sha1 to the3486 * new value or to zero to delete the ref. To check the old value3487 * while locking the ref, set have_old to 1 and set old_sha1 to the3488 * value or to zero to ensure the ref does not exist before update.3489 */3490struct ref_update {3491unsigned char new_sha1[20];3492unsigned char old_sha1[20];3493int flags;/* REF_NODEREF? */3494int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3495struct ref_lock *lock;3496int type;3497char*msg;3498const char refname[FLEX_ARRAY];3499};35003501/*3502 * Transaction states.3503 * OPEN: The transaction is in a valid state and can accept new updates.3504 * An OPEN transaction can be committed.3505 * CLOSED: A closed transaction is no longer active and no other operations3506 * than free can be used on it in this state.3507 * A transaction can either become closed by successfully committing3508 * an active transaction or if there is a failure while building3509 * the transaction thus rendering it failed/inactive.3510 */3511enum ref_transaction_state {3512 REF_TRANSACTION_OPEN =0,3513 REF_TRANSACTION_CLOSED =13514};35153516/*3517 * Data structure for holding a reference transaction, which can3518 * consist of checks and updates to multiple references, carried out3519 * as atomically as possible. This structure is opaque to callers.3520 */3521struct ref_transaction {3522struct ref_update **updates;3523size_t alloc;3524size_t nr;3525enum ref_transaction_state state;3526};35273528struct ref_transaction *ref_transaction_begin(struct strbuf *err)3529{3530assert(err);35313532returnxcalloc(1,sizeof(struct ref_transaction));3533}35343535voidref_transaction_free(struct ref_transaction *transaction)3536{3537int i;35383539if(!transaction)3540return;35413542for(i =0; i < transaction->nr; i++) {3543free(transaction->updates[i]->msg);3544free(transaction->updates[i]);3545}3546free(transaction->updates);3547free(transaction);3548}35493550static struct ref_update *add_update(struct ref_transaction *transaction,3551const char*refname)3552{3553size_t len =strlen(refname);3554struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);35553556strcpy((char*)update->refname, refname);3557ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3558 transaction->updates[transaction->nr++] = update;3559return update;3560}35613562intref_transaction_update(struct ref_transaction *transaction,3563const char*refname,3564const unsigned char*new_sha1,3565const unsigned char*old_sha1,3566int flags,int have_old,const char*msg,3567struct strbuf *err)3568{3569struct ref_update *update;35703571assert(err);35723573if(transaction->state != REF_TRANSACTION_OPEN)3574die("BUG: update called for transaction that is not open");35753576if(have_old && !old_sha1)3577die("BUG: have_old is true but old_sha1 is NULL");35783579if(!is_null_sha1(new_sha1) &&3580check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3581strbuf_addf(err,"refusing to update ref with bad name%s",3582 refname);3583return-1;3584}35853586 update =add_update(transaction, refname);3587hashcpy(update->new_sha1, new_sha1);3588 update->flags = flags;3589 update->have_old = have_old;3590if(have_old)3591hashcpy(update->old_sha1, old_sha1);3592if(msg)3593 update->msg =xstrdup(msg);3594return0;3595}35963597intref_transaction_create(struct ref_transaction *transaction,3598const char*refname,3599const unsigned char*new_sha1,3600int flags,const char*msg,3601struct strbuf *err)3602{3603struct ref_update *update;36043605assert(err);36063607if(transaction->state != REF_TRANSACTION_OPEN)3608die("BUG: create called for transaction that is not open");36093610if(!new_sha1 ||is_null_sha1(new_sha1))3611die("BUG: create ref with null new_sha1");36123613if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3614strbuf_addf(err,"refusing to create ref with bad name%s",3615 refname);3616return-1;3617}36183619 update =add_update(transaction, refname);36203621hashcpy(update->new_sha1, new_sha1);3622hashclr(update->old_sha1);3623 update->flags = flags;3624 update->have_old =1;3625if(msg)3626 update->msg =xstrdup(msg);3627return0;3628}36293630intref_transaction_delete(struct ref_transaction *transaction,3631const char*refname,3632const unsigned char*old_sha1,3633int flags,int have_old,const char*msg,3634struct strbuf *err)3635{3636struct ref_update *update;36373638assert(err);36393640if(transaction->state != REF_TRANSACTION_OPEN)3641die("BUG: delete called for transaction that is not open");36423643if(have_old && !old_sha1)3644die("BUG: have_old is true but old_sha1 is NULL");36453646 update =add_update(transaction, refname);3647 update->flags = flags;3648 update->have_old = have_old;3649if(have_old) {3650assert(!is_null_sha1(old_sha1));3651hashcpy(update->old_sha1, old_sha1);3652}3653if(msg)3654 update->msg =xstrdup(msg);3655return0;3656}36573658intupdate_ref(const char*action,const char*refname,3659const unsigned char*sha1,const unsigned char*oldval,3660int flags,enum action_on_err onerr)3661{3662struct ref_transaction *t;3663struct strbuf err = STRBUF_INIT;36643665 t =ref_transaction_begin(&err);3666if(!t ||3667ref_transaction_update(t, refname, sha1, oldval, flags,3668!!oldval, action, &err) ||3669ref_transaction_commit(t, &err)) {3670const char*str ="update_ref failed for ref '%s':%s";36713672ref_transaction_free(t);3673switch(onerr) {3674case UPDATE_REFS_MSG_ON_ERR:3675error(str, refname, err.buf);3676break;3677case UPDATE_REFS_DIE_ON_ERR:3678die(str, refname, err.buf);3679break;3680case UPDATE_REFS_QUIET_ON_ERR:3681break;3682}3683strbuf_release(&err);3684return1;3685}3686strbuf_release(&err);3687ref_transaction_free(t);3688return0;3689}36903691static intref_update_compare(const void*r1,const void*r2)3692{3693const struct ref_update *const*u1 = r1;3694const struct ref_update *const*u2 = r2;3695returnstrcmp((*u1)->refname, (*u2)->refname);3696}36973698static intref_update_reject_duplicates(struct ref_update **updates,int n,3699struct strbuf *err)3700{3701int i;37023703assert(err);37043705for(i =1; i < n; i++)3706if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3707strbuf_addf(err,3708"Multiple updates for ref '%s' not allowed.",3709 updates[i]->refname);3710return1;3711}3712return0;3713}37143715intref_transaction_commit(struct ref_transaction *transaction,3716struct strbuf *err)3717{3718int ret =0, i;3719int n = transaction->nr;3720struct ref_update **updates = transaction->updates;3721struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3722struct string_list_item *ref_to_delete;37233724assert(err);37253726if(transaction->state != REF_TRANSACTION_OPEN)3727die("BUG: commit called for transaction that is not open");37283729if(!n) {3730 transaction->state = REF_TRANSACTION_CLOSED;3731return0;3732}37333734/* Copy, sort, and reject duplicate refs */3735qsort(updates, n,sizeof(*updates), ref_update_compare);3736if(ref_update_reject_duplicates(updates, n, err)) {3737 ret = TRANSACTION_GENERIC_ERROR;3738goto cleanup;3739}37403741/* Acquire all locks while verifying old values */3742for(i =0; i < n; i++) {3743struct ref_update *update = updates[i];3744int flags = update->flags;37453746if(is_null_sha1(update->new_sha1))3747 flags |= REF_DELETING;3748 update->lock =lock_ref_sha1_basic(update->refname,3749(update->have_old ?3750 update->old_sha1 :3751 NULL),3752 NULL,3753 flags,3754&update->type);3755if(!update->lock) {3756 ret = (errno == ENOTDIR)3757? TRANSACTION_NAME_CONFLICT3758: TRANSACTION_GENERIC_ERROR;3759strbuf_addf(err,"Cannot lock the ref '%s'.",3760 update->refname);3761goto cleanup;3762}3763}37643765/* Perform updates first so live commits remain referenced */3766for(i =0; i < n; i++) {3767struct ref_update *update = updates[i];37683769if(!is_null_sha1(update->new_sha1)) {3770if(write_ref_sha1(update->lock, update->new_sha1,3771 update->msg)) {3772 update->lock = NULL;/* freed by write_ref_sha1 */3773strbuf_addf(err,"Cannot update the ref '%s'.",3774 update->refname);3775 ret = TRANSACTION_GENERIC_ERROR;3776goto cleanup;3777}3778 update->lock = NULL;/* freed by write_ref_sha1 */3779}3780}37813782/* Perform deletes now that updates are safely completed */3783for(i =0; i < n; i++) {3784struct ref_update *update = updates[i];37853786if(update->lock) {3787if(delete_ref_loose(update->lock, update->type, err)) {3788 ret = TRANSACTION_GENERIC_ERROR;3789goto cleanup;3790}37913792if(!(update->flags & REF_ISPRUNING))3793string_list_append(&refs_to_delete,3794 update->lock->ref_name);3795}3796}37973798if(repack_without_refs(&refs_to_delete, err)) {3799 ret = TRANSACTION_GENERIC_ERROR;3800goto cleanup;3801}3802for_each_string_list_item(ref_to_delete, &refs_to_delete)3803unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3804clear_loose_ref_cache(&ref_cache);38053806cleanup:3807 transaction->state = REF_TRANSACTION_CLOSED;38083809for(i =0; i < n; i++)3810if(updates[i]->lock)3811unlock_ref(updates[i]->lock);3812string_list_clear(&refs_to_delete,0);3813return ret;3814}38153816char*shorten_unambiguous_ref(const char*refname,int strict)3817{3818int i;3819static char**scanf_fmts;3820static int nr_rules;3821char*short_name;38223823if(!nr_rules) {3824/*3825 * Pre-generate scanf formats from ref_rev_parse_rules[].3826 * Generate a format suitable for scanf from a3827 * ref_rev_parse_rules rule by interpolating "%s" at the3828 * location of the "%.*s".3829 */3830size_t total_len =0;3831size_t offset =0;38323833/* the rule list is NULL terminated, count them first */3834for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3835/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3836 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38373838 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38393840 offset =0;3841for(i =0; i < nr_rules; i++) {3842assert(offset < total_len);3843 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3844 offset +=snprintf(scanf_fmts[i], total_len - offset,3845 ref_rev_parse_rules[i],2,"%s") +1;3846}3847}38483849/* bail out if there are no rules */3850if(!nr_rules)3851returnxstrdup(refname);38523853/* buffer for scanf result, at most refname must fit */3854 short_name =xstrdup(refname);38553856/* skip first rule, it will always match */3857for(i = nr_rules -1; i >0; --i) {3858int j;3859int rules_to_fail = i;3860int short_name_len;38613862if(1!=sscanf(refname, scanf_fmts[i], short_name))3863continue;38643865 short_name_len =strlen(short_name);38663867/*3868 * in strict mode, all (except the matched one) rules3869 * must fail to resolve to a valid non-ambiguous ref3870 */3871if(strict)3872 rules_to_fail = nr_rules;38733874/*3875 * check if the short name resolves to a valid ref,3876 * but use only rules prior to the matched one3877 */3878for(j =0; j < rules_to_fail; j++) {3879const char*rule = ref_rev_parse_rules[j];3880char refname[PATH_MAX];38813882/* skip matched rule */3883if(i == j)3884continue;38853886/*3887 * the short name is ambiguous, if it resolves3888 * (with this previous rule) to a valid ref3889 * read_ref() returns 0 on success3890 */3891mksnpath(refname,sizeof(refname),3892 rule, short_name_len, short_name);3893if(ref_exists(refname))3894break;3895}38963897/*3898 * short name is non-ambiguous if all previous rules3899 * haven't resolved to a valid ref3900 */3901if(j == rules_to_fail)3902return short_name;3903}39043905free(short_name);3906returnxstrdup(refname);3907}39083909static struct string_list *hide_refs;39103911intparse_hide_refs_config(const char*var,const char*value,const char*section)3912{3913if(!strcmp("transfer.hiderefs", var) ||3914/* NEEDSWORK: use parse_config_key() once both are merged */3915(starts_with(var, section) && var[strlen(section)] =='.'&&3916!strcmp(var +strlen(section),".hiderefs"))) {3917char*ref;3918int len;39193920if(!value)3921returnconfig_error_nonbool(var);3922 ref =xstrdup(value);3923 len =strlen(ref);3924while(len && ref[len -1] =='/')3925 ref[--len] ='\0';3926if(!hide_refs) {3927 hide_refs =xcalloc(1,sizeof(*hide_refs));3928 hide_refs->strdup_strings =1;3929}3930string_list_append(hide_refs, ref);3931}3932return0;3933}39343935intref_is_hidden(const char*refname)3936{3937struct string_list_item *item;39383939if(!hide_refs)3940return0;3941for_each_string_list_item(item, hide_refs) {3942int len;3943if(!starts_with(refname, item->string))3944continue;3945 len =strlen(item->string);3946if(!refname[len] || refname[len] =='/')3947return1;3948}3949return0;3950}