1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9struct ref_lock { 10char*ref_name; 11char*orig_ref_name; 12struct lock_file *lk; 13unsigned char old_sha1[20]; 14int lock_fd; 15int force_write; 16}; 17 18/* 19 * How to handle various characters in refnames: 20 * 0: An acceptable character for refs 21 * 1: End-of-component 22 * 2: ., look for a preceding . to reject .. in refs 23 * 3: {, look for a preceding @ to reject @{ in refs 24 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag in ref_update::flags when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Used as a flag in ref_update::flags when the reference should be 51 * updated to new_sha1. 52 */ 53#define REF_HAVE_NEW 0x08 54 55/* 56 * Used as a flag in ref_update::flags when old_sha1 should be 57 * checked. 58 */ 59#define REF_HAVE_OLD 0x10 60 61/* 62 * Try to read one refname component from the front of refname. 63 * Return the length of the component found, or -1 if the component is 64 * not legal. It is legal if it is something reasonable to have under 65 * ".git/refs/"; We do not like it if: 66 * 67 * - any path component of it begins with ".", or 68 * - it has double dots "..", or 69 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 70 * - it ends with a "/". 71 * - it ends with ".lock" 72 * - it contains a "\" (backslash) 73 */ 74static intcheck_refname_component(const char*refname,int flags) 75{ 76const char*cp; 77char last ='\0'; 78 79for(cp = refname; ; cp++) { 80int ch = *cp &255; 81unsigned char disp = refname_disposition[ch]; 82switch(disp) { 83case1: 84goto out; 85case2: 86if(last =='.') 87return-1;/* Refname contains "..". */ 88break; 89case3: 90if(last =='@') 91return-1;/* Refname contains "@{". */ 92break; 93case4: 94return-1; 95} 96 last = ch; 97} 98out: 99if(cp == refname) 100return0;/* Component has zero length. */ 101if(refname[0] =='.') 102return-1;/* Component starts with '.'. */ 103if(cp - refname >= LOCK_SUFFIX_LEN && 104!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 105return-1;/* Refname ends with ".lock". */ 106return cp - refname; 107} 108 109intcheck_refname_format(const char*refname,int flags) 110{ 111int component_len, component_count =0; 112 113if(!strcmp(refname,"@")) 114/* Refname is a single character '@'. */ 115return-1; 116 117while(1) { 118/* We are at the start of a path component. */ 119 component_len =check_refname_component(refname, flags); 120if(component_len <=0) { 121if((flags & REFNAME_REFSPEC_PATTERN) && 122 refname[0] =='*'&& 123(refname[1] =='\0'|| refname[1] =='/')) { 124/* Accept one wildcard as a full refname component. */ 125 flags &= ~REFNAME_REFSPEC_PATTERN; 126 component_len =1; 127}else{ 128return-1; 129} 130} 131 component_count++; 132if(refname[component_len] =='\0') 133break; 134/* Skip to next component. */ 135 refname += component_len +1; 136} 137 138if(refname[component_len -1] =='.') 139return-1;/* Refname ends with '.'. */ 140if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 141return-1;/* Refname has only one component. */ 142return0; 143} 144 145struct ref_entry; 146 147/* 148 * Information used (along with the information in ref_entry) to 149 * describe a single cached reference. This data structure only 150 * occurs embedded in a union in struct ref_entry, and only when 151 * (ref_entry->flag & REF_DIR) is zero. 152 */ 153struct ref_value { 154/* 155 * The name of the object to which this reference resolves 156 * (which may be a tag object). If REF_ISBROKEN, this is 157 * null. If REF_ISSYMREF, then this is the name of the object 158 * referred to by the last reference in the symlink chain. 159 */ 160unsigned char sha1[20]; 161 162/* 163 * If REF_KNOWS_PEELED, then this field holds the peeled value 164 * of this reference, or null if the reference is known not to 165 * be peelable. See the documentation for peel_ref() for an 166 * exact definition of "peelable". 167 */ 168unsigned char peeled[20]; 169}; 170 171struct ref_cache; 172 173/* 174 * Information used (along with the information in ref_entry) to 175 * describe a level in the hierarchy of references. This data 176 * structure only occurs embedded in a union in struct ref_entry, and 177 * only when (ref_entry.flag & REF_DIR) is set. In that case, 178 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 179 * in the directory have already been read: 180 * 181 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 182 * or packed references, already read. 183 * 184 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 185 * references that hasn't been read yet (nor has any of its 186 * subdirectories). 187 * 188 * Entries within a directory are stored within a growable array of 189 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 190 * sorted are sorted by their component name in strcmp() order and the 191 * remaining entries are unsorted. 192 * 193 * Loose references are read lazily, one directory at a time. When a 194 * directory of loose references is read, then all of the references 195 * in that directory are stored, and REF_INCOMPLETE stubs are created 196 * for any subdirectories, but the subdirectories themselves are not 197 * read. The reading is triggered by get_ref_dir(). 198 */ 199struct ref_dir { 200int nr, alloc; 201 202/* 203 * Entries with index 0 <= i < sorted are sorted by name. New 204 * entries are appended to the list unsorted, and are sorted 205 * only when required; thus we avoid the need to sort the list 206 * after the addition of every reference. 207 */ 208int sorted; 209 210/* A pointer to the ref_cache that contains this ref_dir. */ 211struct ref_cache *ref_cache; 212 213struct ref_entry **entries; 214}; 215 216/* 217 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 218 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 219 * public values; see refs.h. 220 */ 221 222/* 223 * The field ref_entry->u.value.peeled of this value entry contains 224 * the correct peeled value for the reference, which might be 225 * null_sha1 if the reference is not a tag or if it is broken. 226 */ 227#define REF_KNOWS_PEELED 0x10 228 229/* ref_entry represents a directory of references */ 230#define REF_DIR 0x20 231 232/* 233 * Entry has not yet been read from disk (used only for REF_DIR 234 * entries representing loose references) 235 */ 236#define REF_INCOMPLETE 0x40 237 238/* 239 * A ref_entry represents either a reference or a "subdirectory" of 240 * references. 241 * 242 * Each directory in the reference namespace is represented by a 243 * ref_entry with (flags & REF_DIR) set and containing a subdir member 244 * that holds the entries in that directory that have been read so 245 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 246 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 247 * used for loose reference directories. 248 * 249 * References are represented by a ref_entry with (flags & REF_DIR) 250 * unset and a value member that describes the reference's value. The 251 * flag member is at the ref_entry level, but it is also needed to 252 * interpret the contents of the value field (in other words, a 253 * ref_value object is not very much use without the enclosing 254 * ref_entry). 255 * 256 * Reference names cannot end with slash and directories' names are 257 * always stored with a trailing slash (except for the top-level 258 * directory, which is always denoted by ""). This has two nice 259 * consequences: (1) when the entries in each subdir are sorted 260 * lexicographically by name (as they usually are), the references in 261 * a whole tree can be generated in lexicographic order by traversing 262 * the tree in left-to-right, depth-first order; (2) the names of 263 * references and subdirectories cannot conflict, and therefore the 264 * presence of an empty subdirectory does not block the creation of a 265 * similarly-named reference. (The fact that reference names with the 266 * same leading components can conflict *with each other* is a 267 * separate issue that is regulated by is_refname_available().) 268 * 269 * Please note that the name field contains the fully-qualified 270 * reference (or subdirectory) name. Space could be saved by only 271 * storing the relative names. But that would require the full names 272 * to be generated on the fly when iterating in do_for_each_ref(), and 273 * would break callback functions, who have always been able to assume 274 * that the name strings that they are passed will not be freed during 275 * the iteration. 276 */ 277struct ref_entry { 278unsigned char flag;/* ISSYMREF? ISPACKED? */ 279union{ 280struct ref_value value;/* if not (flags&REF_DIR) */ 281struct ref_dir subdir;/* if (flags&REF_DIR) */ 282} u; 283/* 284 * The full name of the reference (e.g., "refs/heads/master") 285 * or the full name of the directory with a trailing slash 286 * (e.g., "refs/heads/"): 287 */ 288char name[FLEX_ARRAY]; 289}; 290 291static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 292 293static struct ref_dir *get_ref_dir(struct ref_entry *entry) 294{ 295struct ref_dir *dir; 296assert(entry->flag & REF_DIR); 297 dir = &entry->u.subdir; 298if(entry->flag & REF_INCOMPLETE) { 299read_loose_refs(entry->name, dir); 300 entry->flag &= ~REF_INCOMPLETE; 301} 302return dir; 303} 304 305/* 306 * Check if a refname is safe. 307 * For refs that start with "refs/" we consider it safe as long they do 308 * not try to resolve to outside of refs/. 309 * 310 * For all other refs we only consider them safe iff they only contain 311 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 312 * "config"). 313 */ 314static intrefname_is_safe(const char*refname) 315{ 316if(starts_with(refname,"refs/")) { 317char*buf; 318int result; 319 320 buf =xmalloc(strlen(refname) +1); 321/* 322 * Does the refname try to escape refs/? 323 * For example: refs/foo/../bar is safe but refs/foo/../../bar 324 * is not. 325 */ 326 result = !normalize_path_copy(buf, refname +strlen("refs/")); 327free(buf); 328return result; 329} 330while(*refname) { 331if(!isupper(*refname) && *refname !='_') 332return0; 333 refname++; 334} 335return1; 336} 337 338static struct ref_entry *create_ref_entry(const char*refname, 339const unsigned char*sha1,int flag, 340int check_name) 341{ 342int len; 343struct ref_entry *ref; 344 345if(check_name && 346check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 347die("Reference has invalid format: '%s'", refname); 348if(!check_name && !refname_is_safe(refname)) 349die("Reference has invalid name: '%s'", refname); 350 len =strlen(refname) +1; 351 ref =xmalloc(sizeof(struct ref_entry) + len); 352hashcpy(ref->u.value.sha1, sha1); 353hashclr(ref->u.value.peeled); 354memcpy(ref->name, refname, len); 355 ref->flag = flag; 356return ref; 357} 358 359static voidclear_ref_dir(struct ref_dir *dir); 360 361static voidfree_ref_entry(struct ref_entry *entry) 362{ 363if(entry->flag & REF_DIR) { 364/* 365 * Do not use get_ref_dir() here, as that might 366 * trigger the reading of loose refs. 367 */ 368clear_ref_dir(&entry->u.subdir); 369} 370free(entry); 371} 372 373/* 374 * Add a ref_entry to the end of dir (unsorted). Entry is always 375 * stored directly in dir; no recursion into subdirectories is 376 * done. 377 */ 378static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 379{ 380ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 381 dir->entries[dir->nr++] = entry; 382/* optimize for the case that entries are added in order */ 383if(dir->nr ==1|| 384(dir->nr == dir->sorted +1&& 385strcmp(dir->entries[dir->nr -2]->name, 386 dir->entries[dir->nr -1]->name) <0)) 387 dir->sorted = dir->nr; 388} 389 390/* 391 * Clear and free all entries in dir, recursively. 392 */ 393static voidclear_ref_dir(struct ref_dir *dir) 394{ 395int i; 396for(i =0; i < dir->nr; i++) 397free_ref_entry(dir->entries[i]); 398free(dir->entries); 399 dir->sorted = dir->nr = dir->alloc =0; 400 dir->entries = NULL; 401} 402 403/* 404 * Create a struct ref_entry object for the specified dirname. 405 * dirname is the name of the directory with a trailing slash (e.g., 406 * "refs/heads/") or "" for the top-level directory. 407 */ 408static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 409const char*dirname,size_t len, 410int incomplete) 411{ 412struct ref_entry *direntry; 413 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 414memcpy(direntry->name, dirname, len); 415 direntry->name[len] ='\0'; 416 direntry->u.subdir.ref_cache = ref_cache; 417 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 418return direntry; 419} 420 421static intref_entry_cmp(const void*a,const void*b) 422{ 423struct ref_entry *one = *(struct ref_entry **)a; 424struct ref_entry *two = *(struct ref_entry **)b; 425returnstrcmp(one->name, two->name); 426} 427 428static voidsort_ref_dir(struct ref_dir *dir); 429 430struct string_slice { 431size_t len; 432const char*str; 433}; 434 435static intref_entry_cmp_sslice(const void*key_,const void*ent_) 436{ 437const struct string_slice *key = key_; 438const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 439int cmp =strncmp(key->str, ent->name, key->len); 440if(cmp) 441return cmp; 442return'\0'- (unsigned char)ent->name[key->len]; 443} 444 445/* 446 * Return the index of the entry with the given refname from the 447 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 448 * no such entry is found. dir must already be complete. 449 */ 450static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 451{ 452struct ref_entry **r; 453struct string_slice key; 454 455if(refname == NULL || !dir->nr) 456return-1; 457 458sort_ref_dir(dir); 459 key.len = len; 460 key.str = refname; 461 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 462 ref_entry_cmp_sslice); 463 464if(r == NULL) 465return-1; 466 467return r - dir->entries; 468} 469 470/* 471 * Search for a directory entry directly within dir (without 472 * recursing). Sort dir if necessary. subdirname must be a directory 473 * name (i.e., end in '/'). If mkdir is set, then create the 474 * directory if it is missing; otherwise, return NULL if the desired 475 * directory cannot be found. dir must already be complete. 476 */ 477static struct ref_dir *search_for_subdir(struct ref_dir *dir, 478const char*subdirname,size_t len, 479int mkdir) 480{ 481int entry_index =search_ref_dir(dir, subdirname, len); 482struct ref_entry *entry; 483if(entry_index == -1) { 484if(!mkdir) 485return NULL; 486/* 487 * Since dir is complete, the absence of a subdir 488 * means that the subdir really doesn't exist; 489 * therefore, create an empty record for it but mark 490 * the record complete. 491 */ 492 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 493add_entry_to_dir(dir, entry); 494}else{ 495 entry = dir->entries[entry_index]; 496} 497returnget_ref_dir(entry); 498} 499 500/* 501 * If refname is a reference name, find the ref_dir within the dir 502 * tree that should hold refname. If refname is a directory name 503 * (i.e., ends in '/'), then return that ref_dir itself. dir must 504 * represent the top-level directory and must already be complete. 505 * Sort ref_dirs and recurse into subdirectories as necessary. If 506 * mkdir is set, then create any missing directories; otherwise, 507 * return NULL if the desired directory cannot be found. 508 */ 509static struct ref_dir *find_containing_dir(struct ref_dir *dir, 510const char*refname,int mkdir) 511{ 512const char*slash; 513for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 514size_t dirnamelen = slash - refname +1; 515struct ref_dir *subdir; 516 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 517if(!subdir) { 518 dir = NULL; 519break; 520} 521 dir = subdir; 522} 523 524return dir; 525} 526 527/* 528 * Find the value entry with the given name in dir, sorting ref_dirs 529 * and recursing into subdirectories as necessary. If the name is not 530 * found or it corresponds to a directory entry, return NULL. 531 */ 532static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 533{ 534int entry_index; 535struct ref_entry *entry; 536 dir =find_containing_dir(dir, refname,0); 537if(!dir) 538return NULL; 539 entry_index =search_ref_dir(dir, refname,strlen(refname)); 540if(entry_index == -1) 541return NULL; 542 entry = dir->entries[entry_index]; 543return(entry->flag & REF_DIR) ? NULL : entry; 544} 545 546/* 547 * Remove the entry with the given name from dir, recursing into 548 * subdirectories as necessary. If refname is the name of a directory 549 * (i.e., ends with '/'), then remove the directory and its contents. 550 * If the removal was successful, return the number of entries 551 * remaining in the directory entry that contained the deleted entry. 552 * If the name was not found, return -1. Please note that this 553 * function only deletes the entry from the cache; it does not delete 554 * it from the filesystem or ensure that other cache entries (which 555 * might be symbolic references to the removed entry) are updated. 556 * Nor does it remove any containing dir entries that might be made 557 * empty by the removal. dir must represent the top-level directory 558 * and must already be complete. 559 */ 560static intremove_entry(struct ref_dir *dir,const char*refname) 561{ 562int refname_len =strlen(refname); 563int entry_index; 564struct ref_entry *entry; 565int is_dir = refname[refname_len -1] =='/'; 566if(is_dir) { 567/* 568 * refname represents a reference directory. Remove 569 * the trailing slash; otherwise we will get the 570 * directory *representing* refname rather than the 571 * one *containing* it. 572 */ 573char*dirname =xmemdupz(refname, refname_len -1); 574 dir =find_containing_dir(dir, dirname,0); 575free(dirname); 576}else{ 577 dir =find_containing_dir(dir, refname,0); 578} 579if(!dir) 580return-1; 581 entry_index =search_ref_dir(dir, refname, refname_len); 582if(entry_index == -1) 583return-1; 584 entry = dir->entries[entry_index]; 585 586memmove(&dir->entries[entry_index], 587&dir->entries[entry_index +1], 588(dir->nr - entry_index -1) *sizeof(*dir->entries) 589); 590 dir->nr--; 591if(dir->sorted > entry_index) 592 dir->sorted--; 593free_ref_entry(entry); 594return dir->nr; 595} 596 597/* 598 * Add a ref_entry to the ref_dir (unsorted), recursing into 599 * subdirectories as necessary. dir must represent the top-level 600 * directory. Return 0 on success. 601 */ 602static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 603{ 604 dir =find_containing_dir(dir, ref->name,1); 605if(!dir) 606return-1; 607add_entry_to_dir(dir, ref); 608return0; 609} 610 611/* 612 * Emit a warning and return true iff ref1 and ref2 have the same name 613 * and the same sha1. Die if they have the same name but different 614 * sha1s. 615 */ 616static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 617{ 618if(strcmp(ref1->name, ref2->name)) 619return0; 620 621/* Duplicate name; make sure that they don't conflict: */ 622 623if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 624/* This is impossible by construction */ 625die("Reference directory conflict:%s", ref1->name); 626 627if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 628die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 629 630warning("Duplicated ref:%s", ref1->name); 631return1; 632} 633 634/* 635 * Sort the entries in dir non-recursively (if they are not already 636 * sorted) and remove any duplicate entries. 637 */ 638static voidsort_ref_dir(struct ref_dir *dir) 639{ 640int i, j; 641struct ref_entry *last = NULL; 642 643/* 644 * This check also prevents passing a zero-length array to qsort(), 645 * which is a problem on some platforms. 646 */ 647if(dir->sorted == dir->nr) 648return; 649 650qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 651 652/* Remove any duplicates: */ 653for(i =0, j =0; j < dir->nr; j++) { 654struct ref_entry *entry = dir->entries[j]; 655if(last &&is_dup_ref(last, entry)) 656free_ref_entry(entry); 657else 658 last = dir->entries[i++] = entry; 659} 660 dir->sorted = dir->nr = i; 661} 662 663/* Include broken references in a do_for_each_ref*() iteration: */ 664#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 665 666/* 667 * Return true iff the reference described by entry can be resolved to 668 * an object in the database. Emit a warning if the referred-to 669 * object does not exist. 670 */ 671static intref_resolves_to_object(struct ref_entry *entry) 672{ 673if(entry->flag & REF_ISBROKEN) 674return0; 675if(!has_sha1_file(entry->u.value.sha1)) { 676error("%sdoes not point to a valid object!", entry->name); 677return0; 678} 679return1; 680} 681 682/* 683 * current_ref is a performance hack: when iterating over references 684 * using the for_each_ref*() functions, current_ref is set to the 685 * current reference's entry before calling the callback function. If 686 * the callback function calls peel_ref(), then peel_ref() first 687 * checks whether the reference to be peeled is the current reference 688 * (it usually is) and if so, returns that reference's peeled version 689 * if it is available. This avoids a refname lookup in a common case. 690 */ 691static struct ref_entry *current_ref; 692 693typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 694 695struct ref_entry_cb { 696const char*base; 697int trim; 698int flags; 699 each_ref_fn *fn; 700void*cb_data; 701}; 702 703/* 704 * Handle one reference in a do_for_each_ref*()-style iteration, 705 * calling an each_ref_fn for each entry. 706 */ 707static intdo_one_ref(struct ref_entry *entry,void*cb_data) 708{ 709struct ref_entry_cb *data = cb_data; 710struct ref_entry *old_current_ref; 711int retval; 712 713if(!starts_with(entry->name, data->base)) 714return0; 715 716if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 717!ref_resolves_to_object(entry)) 718return0; 719 720/* Store the old value, in case this is a recursive call: */ 721 old_current_ref = current_ref; 722 current_ref = entry; 723 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 724 entry->flag, data->cb_data); 725 current_ref = old_current_ref; 726return retval; 727} 728 729/* 730 * Call fn for each reference in dir that has index in the range 731 * offset <= index < dir->nr. Recurse into subdirectories that are in 732 * that index range, sorting them before iterating. This function 733 * does not sort dir itself; it should be sorted beforehand. fn is 734 * called for all references, including broken ones. 735 */ 736static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 737 each_ref_entry_fn fn,void*cb_data) 738{ 739int i; 740assert(dir->sorted == dir->nr); 741for(i = offset; i < dir->nr; i++) { 742struct ref_entry *entry = dir->entries[i]; 743int retval; 744if(entry->flag & REF_DIR) { 745struct ref_dir *subdir =get_ref_dir(entry); 746sort_ref_dir(subdir); 747 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 748}else{ 749 retval =fn(entry, cb_data); 750} 751if(retval) 752return retval; 753} 754return0; 755} 756 757/* 758 * Call fn for each reference in the union of dir1 and dir2, in order 759 * by refname. Recurse into subdirectories. If a value entry appears 760 * in both dir1 and dir2, then only process the version that is in 761 * dir2. The input dirs must already be sorted, but subdirs will be 762 * sorted as needed. fn is called for all references, including 763 * broken ones. 764 */ 765static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 766struct ref_dir *dir2, 767 each_ref_entry_fn fn,void*cb_data) 768{ 769int retval; 770int i1 =0, i2 =0; 771 772assert(dir1->sorted == dir1->nr); 773assert(dir2->sorted == dir2->nr); 774while(1) { 775struct ref_entry *e1, *e2; 776int cmp; 777if(i1 == dir1->nr) { 778returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 779} 780if(i2 == dir2->nr) { 781returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 782} 783 e1 = dir1->entries[i1]; 784 e2 = dir2->entries[i2]; 785 cmp =strcmp(e1->name, e2->name); 786if(cmp ==0) { 787if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 788/* Both are directories; descend them in parallel. */ 789struct ref_dir *subdir1 =get_ref_dir(e1); 790struct ref_dir *subdir2 =get_ref_dir(e2); 791sort_ref_dir(subdir1); 792sort_ref_dir(subdir2); 793 retval =do_for_each_entry_in_dirs( 794 subdir1, subdir2, fn, cb_data); 795 i1++; 796 i2++; 797}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 798/* Both are references; ignore the one from dir1. */ 799 retval =fn(e2, cb_data); 800 i1++; 801 i2++; 802}else{ 803die("conflict between reference and directory:%s", 804 e1->name); 805} 806}else{ 807struct ref_entry *e; 808if(cmp <0) { 809 e = e1; 810 i1++; 811}else{ 812 e = e2; 813 i2++; 814} 815if(e->flag & REF_DIR) { 816struct ref_dir *subdir =get_ref_dir(e); 817sort_ref_dir(subdir); 818 retval =do_for_each_entry_in_dir( 819 subdir,0, fn, cb_data); 820}else{ 821 retval =fn(e, cb_data); 822} 823} 824if(retval) 825return retval; 826} 827} 828 829/* 830 * Load all of the refs from the dir into our in-memory cache. The hard work 831 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 832 * through all of the sub-directories. We do not even need to care about 833 * sorting, as traversal order does not matter to us. 834 */ 835static voidprime_ref_dir(struct ref_dir *dir) 836{ 837int i; 838for(i =0; i < dir->nr; i++) { 839struct ref_entry *entry = dir->entries[i]; 840if(entry->flag & REF_DIR) 841prime_ref_dir(get_ref_dir(entry)); 842} 843} 844 845static intentry_matches(struct ref_entry *entry,const struct string_list *list) 846{ 847return list &&string_list_has_string(list, entry->name); 848} 849 850struct nonmatching_ref_data { 851const struct string_list *skip; 852struct ref_entry *found; 853}; 854 855static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 856{ 857struct nonmatching_ref_data *data = vdata; 858 859if(entry_matches(entry, data->skip)) 860return0; 861 862 data->found = entry; 863return1; 864} 865 866static voidreport_refname_conflict(struct ref_entry *entry, 867const char*refname) 868{ 869error("'%s' exists; cannot create '%s'", entry->name, refname); 870} 871 872/* 873 * Return true iff a reference named refname could be created without 874 * conflicting with the name of an existing reference in dir. If 875 * skip is non-NULL, ignore potential conflicts with refs in skip 876 * (e.g., because they are scheduled for deletion in the same 877 * operation). 878 * 879 * Two reference names conflict if one of them exactly matches the 880 * leading components of the other; e.g., "foo/bar" conflicts with 881 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 882 * "foo/barbados". 883 * 884 * skip must be sorted. 885 */ 886static intis_refname_available(const char*refname, 887const struct string_list *skip, 888struct ref_dir *dir) 889{ 890const char*slash; 891size_t len; 892int pos; 893char*dirname; 894 895for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 896/* 897 * We are still at a leading dir of the refname; we are 898 * looking for a conflict with a leaf entry. 899 * 900 * If we find one, we still must make sure it is 901 * not in "skip". 902 */ 903 pos =search_ref_dir(dir, refname, slash - refname); 904if(pos >=0) { 905struct ref_entry *entry = dir->entries[pos]; 906if(entry_matches(entry, skip)) 907return1; 908report_refname_conflict(entry, refname); 909return0; 910} 911 912 913/* 914 * Otherwise, we can try to continue our search with 915 * the next component; if we come up empty, we know 916 * there is nothing under this whole prefix. 917 */ 918 pos =search_ref_dir(dir, refname, slash +1- refname); 919if(pos <0) 920return1; 921 922 dir =get_ref_dir(dir->entries[pos]); 923} 924 925/* 926 * We are at the leaf of our refname; we want to 927 * make sure there are no directories which match it. 928 */ 929 len =strlen(refname); 930 dirname =xmallocz(len +1); 931sprintf(dirname,"%s/", refname); 932 pos =search_ref_dir(dir, dirname, len +1); 933free(dirname); 934 935if(pos >=0) { 936/* 937 * We found a directory named "refname". It is a 938 * problem iff it contains any ref that is not 939 * in "skip". 940 */ 941struct ref_entry *entry = dir->entries[pos]; 942struct ref_dir *dir =get_ref_dir(entry); 943struct nonmatching_ref_data data; 944 945 data.skip = skip; 946sort_ref_dir(dir); 947if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 948return1; 949 950report_refname_conflict(data.found, refname); 951return0; 952} 953 954/* 955 * There is no point in searching for another leaf 956 * node which matches it; such an entry would be the 957 * ref we are looking for, not a conflict. 958 */ 959return1; 960} 961 962struct packed_ref_cache { 963struct ref_entry *root; 964 965/* 966 * Count of references to the data structure in this instance, 967 * including the pointer from ref_cache::packed if any. The 968 * data will not be freed as long as the reference count is 969 * nonzero. 970 */ 971unsigned int referrers; 972 973/* 974 * Iff the packed-refs file associated with this instance is 975 * currently locked for writing, this points at the associated 976 * lock (which is owned by somebody else). The referrer count 977 * is also incremented when the file is locked and decremented 978 * when it is unlocked. 979 */ 980struct lock_file *lock; 981 982/* The metadata from when this packed-refs cache was read */ 983struct stat_validity validity; 984}; 985 986/* 987 * Future: need to be in "struct repository" 988 * when doing a full libification. 989 */ 990static struct ref_cache { 991struct ref_cache *next; 992struct ref_entry *loose; 993struct packed_ref_cache *packed; 994/* 995 * The submodule name, or "" for the main repo. We allocate 996 * length 1 rather than FLEX_ARRAY so that the main ref_cache 997 * is initialized correctly. 998 */ 999char name[1];1000} ref_cache, *submodule_ref_caches;10011002/* Lock used for the main packed-refs file: */1003static struct lock_file packlock;10041005/*1006 * Increment the reference count of *packed_refs.1007 */1008static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1009{1010 packed_refs->referrers++;1011}10121013/*1014 * Decrease the reference count of *packed_refs. If it goes to zero,1015 * free *packed_refs and return true; otherwise return false.1016 */1017static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1018{1019if(!--packed_refs->referrers) {1020free_ref_entry(packed_refs->root);1021stat_validity_clear(&packed_refs->validity);1022free(packed_refs);1023return1;1024}else{1025return0;1026}1027}10281029static voidclear_packed_ref_cache(struct ref_cache *refs)1030{1031if(refs->packed) {1032struct packed_ref_cache *packed_refs = refs->packed;10331034if(packed_refs->lock)1035die("internal error: packed-ref cache cleared while locked");1036 refs->packed = NULL;1037release_packed_ref_cache(packed_refs);1038}1039}10401041static voidclear_loose_ref_cache(struct ref_cache *refs)1042{1043if(refs->loose) {1044free_ref_entry(refs->loose);1045 refs->loose = NULL;1046}1047}10481049static struct ref_cache *create_ref_cache(const char*submodule)1050{1051int len;1052struct ref_cache *refs;1053if(!submodule)1054 submodule ="";1055 len =strlen(submodule) +1;1056 refs =xcalloc(1,sizeof(struct ref_cache) + len);1057memcpy(refs->name, submodule, len);1058return refs;1059}10601061/*1062 * Return a pointer to a ref_cache for the specified submodule. For1063 * the main repository, use submodule==NULL. The returned structure1064 * will be allocated and initialized but not necessarily populated; it1065 * should not be freed.1066 */1067static struct ref_cache *get_ref_cache(const char*submodule)1068{1069struct ref_cache *refs;10701071if(!submodule || !*submodule)1072return&ref_cache;10731074for(refs = submodule_ref_caches; refs; refs = refs->next)1075if(!strcmp(submodule, refs->name))1076return refs;10771078 refs =create_ref_cache(submodule);1079 refs->next = submodule_ref_caches;1080 submodule_ref_caches = refs;1081return refs;1082}10831084/* The length of a peeled reference line in packed-refs, including EOL: */1085#define PEELED_LINE_LENGTH 4210861087/*1088 * The packed-refs header line that we write out. Perhaps other1089 * traits will be added later. The trailing space is required.1090 */1091static const char PACKED_REFS_HEADER[] =1092"# pack-refs with: peeled fully-peeled\n";10931094/*1095 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1096 * Return a pointer to the refname within the line (null-terminated),1097 * or NULL if there was a problem.1098 */1099static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1100{1101const char*ref;11021103/*1104 * 42: the answer to everything.1105 *1106 * In this case, it happens to be the answer to1107 * 40 (length of sha1 hex representation)1108 * +1 (space in between hex and name)1109 * +1 (newline at the end of the line)1110 */1111if(line->len <=42)1112return NULL;11131114if(get_sha1_hex(line->buf, sha1) <0)1115return NULL;1116if(!isspace(line->buf[40]))1117return NULL;11181119 ref = line->buf +41;1120if(isspace(*ref))1121return NULL;11221123if(line->buf[line->len -1] !='\n')1124return NULL;1125 line->buf[--line->len] =0;11261127return ref;1128}11291130/*1131 * Read f, which is a packed-refs file, into dir.1132 *1133 * A comment line of the form "# pack-refs with: " may contain zero or1134 * more traits. We interpret the traits as follows:1135 *1136 * No traits:1137 *1138 * Probably no references are peeled. But if the file contains a1139 * peeled value for a reference, we will use it.1140 *1141 * peeled:1142 *1143 * References under "refs/tags/", if they *can* be peeled, *are*1144 * peeled in this file. References outside of "refs/tags/" are1145 * probably not peeled even if they could have been, but if we find1146 * a peeled value for such a reference we will use it.1147 *1148 * fully-peeled:1149 *1150 * All references in the file that can be peeled are peeled.1151 * Inversely (and this is more important), any references in the1152 * file for which no peeled value is recorded is not peelable. This1153 * trait should typically be written alongside "peeled" for1154 * compatibility with older clients, but we do not require it1155 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1156 */1157static voidread_packed_refs(FILE*f,struct ref_dir *dir)1158{1159struct ref_entry *last = NULL;1160struct strbuf line = STRBUF_INIT;1161enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11621163while(strbuf_getwholeline(&line, f,'\n') != EOF) {1164unsigned char sha1[20];1165const char*refname;1166const char*traits;11671168if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1169if(strstr(traits," fully-peeled "))1170 peeled = PEELED_FULLY;1171else if(strstr(traits," peeled "))1172 peeled = PEELED_TAGS;1173/* perhaps other traits later as well */1174continue;1175}11761177 refname =parse_ref_line(&line, sha1);1178if(refname) {1179int flag = REF_ISPACKED;11801181if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1182hashclr(sha1);1183 flag |= REF_BAD_NAME | REF_ISBROKEN;1184}1185 last =create_ref_entry(refname, sha1, flag,0);1186if(peeled == PEELED_FULLY ||1187(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1188 last->flag |= REF_KNOWS_PEELED;1189add_ref(dir, last);1190continue;1191}1192if(last &&1193 line.buf[0] =='^'&&1194 line.len == PEELED_LINE_LENGTH &&1195 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1196!get_sha1_hex(line.buf +1, sha1)) {1197hashcpy(last->u.value.peeled, sha1);1198/*1199 * Regardless of what the file header said,1200 * we definitely know the value of *this*1201 * reference:1202 */1203 last->flag |= REF_KNOWS_PEELED;1204}1205}12061207strbuf_release(&line);1208}12091210/*1211 * Get the packed_ref_cache for the specified ref_cache, creating it1212 * if necessary.1213 */1214static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1215{1216const char*packed_refs_file;12171218if(*refs->name)1219 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1220else1221 packed_refs_file =git_path("packed-refs");12221223if(refs->packed &&1224!stat_validity_check(&refs->packed->validity, packed_refs_file))1225clear_packed_ref_cache(refs);12261227if(!refs->packed) {1228FILE*f;12291230 refs->packed =xcalloc(1,sizeof(*refs->packed));1231acquire_packed_ref_cache(refs->packed);1232 refs->packed->root =create_dir_entry(refs,"",0,0);1233 f =fopen(packed_refs_file,"r");1234if(f) {1235stat_validity_update(&refs->packed->validity,fileno(f));1236read_packed_refs(f,get_ref_dir(refs->packed->root));1237fclose(f);1238}1239}1240return refs->packed;1241}12421243static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1244{1245returnget_ref_dir(packed_ref_cache->root);1246}12471248static struct ref_dir *get_packed_refs(struct ref_cache *refs)1249{1250returnget_packed_ref_dir(get_packed_ref_cache(refs));1251}12521253voidadd_packed_ref(const char*refname,const unsigned char*sha1)1254{1255struct packed_ref_cache *packed_ref_cache =1256get_packed_ref_cache(&ref_cache);12571258if(!packed_ref_cache->lock)1259die("internal error: packed refs not locked");1260add_ref(get_packed_ref_dir(packed_ref_cache),1261create_ref_entry(refname, sha1, REF_ISPACKED,1));1262}12631264/*1265 * Read the loose references from the namespace dirname into dir1266 * (without recursing). dirname must end with '/'. dir must be the1267 * directory entry corresponding to dirname.1268 */1269static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1270{1271struct ref_cache *refs = dir->ref_cache;1272DIR*d;1273const char*path;1274struct dirent *de;1275int dirnamelen =strlen(dirname);1276struct strbuf refname;12771278if(*refs->name)1279 path =git_path_submodule(refs->name,"%s", dirname);1280else1281 path =git_path("%s", dirname);12821283 d =opendir(path);1284if(!d)1285return;12861287strbuf_init(&refname, dirnamelen +257);1288strbuf_add(&refname, dirname, dirnamelen);12891290while((de =readdir(d)) != NULL) {1291unsigned char sha1[20];1292struct stat st;1293int flag;1294const char*refdir;12951296if(de->d_name[0] =='.')1297continue;1298if(ends_with(de->d_name,".lock"))1299continue;1300strbuf_addstr(&refname, de->d_name);1301 refdir = *refs->name1302?git_path_submodule(refs->name,"%s", refname.buf)1303:git_path("%s", refname.buf);1304if(stat(refdir, &st) <0) {1305;/* silently ignore */1306}else if(S_ISDIR(st.st_mode)) {1307strbuf_addch(&refname,'/');1308add_entry_to_dir(dir,1309create_dir_entry(refs, refname.buf,1310 refname.len,1));1311}else{1312if(*refs->name) {1313hashclr(sha1);1314 flag =0;1315if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1316hashclr(sha1);1317 flag |= REF_ISBROKEN;1318}1319}else if(read_ref_full(refname.buf,1320 RESOLVE_REF_READING,1321 sha1, &flag)) {1322hashclr(sha1);1323 flag |= REF_ISBROKEN;1324}1325if(check_refname_format(refname.buf,1326 REFNAME_ALLOW_ONELEVEL)) {1327hashclr(sha1);1328 flag |= REF_BAD_NAME | REF_ISBROKEN;1329}1330add_entry_to_dir(dir,1331create_ref_entry(refname.buf, sha1, flag,0));1332}1333strbuf_setlen(&refname, dirnamelen);1334}1335strbuf_release(&refname);1336closedir(d);1337}13381339static struct ref_dir *get_loose_refs(struct ref_cache *refs)1340{1341if(!refs->loose) {1342/*1343 * Mark the top-level directory complete because we1344 * are about to read the only subdirectory that can1345 * hold references:1346 */1347 refs->loose =create_dir_entry(refs,"",0,0);1348/*1349 * Create an incomplete entry for "refs/":1350 */1351add_entry_to_dir(get_ref_dir(refs->loose),1352create_dir_entry(refs,"refs/",5,1));1353}1354returnget_ref_dir(refs->loose);1355}13561357/* We allow "recursive" symbolic refs. Only within reason, though */1358#define MAXDEPTH 51359#define MAXREFLEN (1024)13601361/*1362 * Called by resolve_gitlink_ref_recursive() after it failed to read1363 * from the loose refs in ref_cache refs. Find <refname> in the1364 * packed-refs file for the submodule.1365 */1366static intresolve_gitlink_packed_ref(struct ref_cache *refs,1367const char*refname,unsigned char*sha1)1368{1369struct ref_entry *ref;1370struct ref_dir *dir =get_packed_refs(refs);13711372 ref =find_ref(dir, refname);1373if(ref == NULL)1374return-1;13751376hashcpy(sha1, ref->u.value.sha1);1377return0;1378}13791380static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1381const char*refname,unsigned char*sha1,1382int recursion)1383{1384int fd, len;1385char buffer[128], *p;1386char*path;13871388if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1389return-1;1390 path = *refs->name1391?git_path_submodule(refs->name,"%s", refname)1392:git_path("%s", refname);1393 fd =open(path, O_RDONLY);1394if(fd <0)1395returnresolve_gitlink_packed_ref(refs, refname, sha1);13961397 len =read(fd, buffer,sizeof(buffer)-1);1398close(fd);1399if(len <0)1400return-1;1401while(len &&isspace(buffer[len-1]))1402 len--;1403 buffer[len] =0;14041405/* Was it a detached head or an old-fashioned symlink? */1406if(!get_sha1_hex(buffer, sha1))1407return0;14081409/* Symref? */1410if(strncmp(buffer,"ref:",4))1411return-1;1412 p = buffer +4;1413while(isspace(*p))1414 p++;14151416returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1417}14181419intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1420{1421int len =strlen(path), retval;1422char*submodule;1423struct ref_cache *refs;14241425while(len && path[len-1] =='/')1426 len--;1427if(!len)1428return-1;1429 submodule =xstrndup(path, len);1430 refs =get_ref_cache(submodule);1431free(submodule);14321433 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1434return retval;1435}14361437/*1438 * Return the ref_entry for the given refname from the packed1439 * references. If it does not exist, return NULL.1440 */1441static struct ref_entry *get_packed_ref(const char*refname)1442{1443returnfind_ref(get_packed_refs(&ref_cache), refname);1444}14451446/*1447 * A loose ref file doesn't exist; check for a packed ref. The1448 * options are forwarded from resolve_safe_unsafe().1449 */1450static intresolve_missing_loose_ref(const char*refname,1451int resolve_flags,1452unsigned char*sha1,1453int*flags)1454{1455struct ref_entry *entry;14561457/*1458 * The loose reference file does not exist; check for a packed1459 * reference.1460 */1461 entry =get_packed_ref(refname);1462if(entry) {1463hashcpy(sha1, entry->u.value.sha1);1464if(flags)1465*flags |= REF_ISPACKED;1466return0;1467}1468/* The reference is not a packed reference, either. */1469if(resolve_flags & RESOLVE_REF_READING) {1470 errno = ENOENT;1471return-1;1472}else{1473hashclr(sha1);1474return0;1475}1476}14771478/* This function needs to return a meaningful errno on failure */1479const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1480{1481int depth = MAXDEPTH;1482 ssize_t len;1483char buffer[256];1484static char refname_buffer[256];1485int bad_name =0;14861487if(flags)1488*flags =0;14891490if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1491if(flags)1492*flags |= REF_BAD_NAME;14931494if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1495!refname_is_safe(refname)) {1496 errno = EINVAL;1497return NULL;1498}1499/*1500 * dwim_ref() uses REF_ISBROKEN to distinguish between1501 * missing refs and refs that were present but invalid,1502 * to complain about the latter to stderr.1503 *1504 * We don't know whether the ref exists, so don't set1505 * REF_ISBROKEN yet.1506 */1507 bad_name =1;1508}1509for(;;) {1510char path[PATH_MAX];1511struct stat st;1512char*buf;1513int fd;15141515if(--depth <0) {1516 errno = ELOOP;1517return NULL;1518}15191520git_snpath(path,sizeof(path),"%s", refname);15211522/*1523 * We might have to loop back here to avoid a race1524 * condition: first we lstat() the file, then we try1525 * to read it as a link or as a file. But if somebody1526 * changes the type of the file (file <-> directory1527 * <-> symlink) between the lstat() and reading, then1528 * we don't want to report that as an error but rather1529 * try again starting with the lstat().1530 */1531 stat_ref:1532if(lstat(path, &st) <0) {1533if(errno != ENOENT)1534return NULL;1535if(resolve_missing_loose_ref(refname, resolve_flags,1536 sha1, flags))1537return NULL;1538if(bad_name) {1539hashclr(sha1);1540if(flags)1541*flags |= REF_ISBROKEN;1542}1543return refname;1544}15451546/* Follow "normalized" - ie "refs/.." symlinks by hand */1547if(S_ISLNK(st.st_mode)) {1548 len =readlink(path, buffer,sizeof(buffer)-1);1549if(len <0) {1550if(errno == ENOENT || errno == EINVAL)1551/* inconsistent with lstat; retry */1552goto stat_ref;1553else1554return NULL;1555}1556 buffer[len] =0;1557if(starts_with(buffer,"refs/") &&1558!check_refname_format(buffer,0)) {1559strcpy(refname_buffer, buffer);1560 refname = refname_buffer;1561if(flags)1562*flags |= REF_ISSYMREF;1563if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1564hashclr(sha1);1565return refname;1566}1567continue;1568}1569}15701571/* Is it a directory? */1572if(S_ISDIR(st.st_mode)) {1573 errno = EISDIR;1574return NULL;1575}15761577/*1578 * Anything else, just open it and try to use it as1579 * a ref1580 */1581 fd =open(path, O_RDONLY);1582if(fd <0) {1583if(errno == ENOENT)1584/* inconsistent with lstat; retry */1585goto stat_ref;1586else1587return NULL;1588}1589 len =read_in_full(fd, buffer,sizeof(buffer)-1);1590if(len <0) {1591int save_errno = errno;1592close(fd);1593 errno = save_errno;1594return NULL;1595}1596close(fd);1597while(len &&isspace(buffer[len-1]))1598 len--;1599 buffer[len] ='\0';16001601/*1602 * Is it a symbolic ref?1603 */1604if(!starts_with(buffer,"ref:")) {1605/*1606 * Please note that FETCH_HEAD has a second1607 * line containing other data.1608 */1609if(get_sha1_hex(buffer, sha1) ||1610(buffer[40] !='\0'&& !isspace(buffer[40]))) {1611if(flags)1612*flags |= REF_ISBROKEN;1613 errno = EINVAL;1614return NULL;1615}1616if(bad_name) {1617hashclr(sha1);1618if(flags)1619*flags |= REF_ISBROKEN;1620}1621return refname;1622}1623if(flags)1624*flags |= REF_ISSYMREF;1625 buf = buffer +4;1626while(isspace(*buf))1627 buf++;1628 refname =strcpy(refname_buffer, buf);1629if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1630hashclr(sha1);1631return refname;1632}1633if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1634if(flags)1635*flags |= REF_ISBROKEN;16361637if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1638!refname_is_safe(buf)) {1639 errno = EINVAL;1640return NULL;1641}1642 bad_name =1;1643}1644}1645}16461647char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1648{1649returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1650}16511652/* The argument to filter_refs */1653struct ref_filter {1654const char*pattern;1655 each_ref_fn *fn;1656void*cb_data;1657};16581659intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1660{1661if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1662return0;1663return-1;1664}16651666intread_ref(const char*refname,unsigned char*sha1)1667{1668returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1669}16701671intref_exists(const char*refname)1672{1673unsigned char sha1[20];1674return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1675}16761677static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1678void*data)1679{1680struct ref_filter *filter = (struct ref_filter *)data;1681if(wildmatch(filter->pattern, refname,0, NULL))1682return0;1683return filter->fn(refname, sha1, flags, filter->cb_data);1684}16851686enum peel_status {1687/* object was peeled successfully: */1688 PEEL_PEELED =0,16891690/*1691 * object cannot be peeled because the named object (or an1692 * object referred to by a tag in the peel chain), does not1693 * exist.1694 */1695 PEEL_INVALID = -1,16961697/* object cannot be peeled because it is not a tag: */1698 PEEL_NON_TAG = -2,16991700/* ref_entry contains no peeled value because it is a symref: */1701 PEEL_IS_SYMREF = -3,17021703/*1704 * ref_entry cannot be peeled because it is broken (i.e., the1705 * symbolic reference cannot even be resolved to an object1706 * name):1707 */1708 PEEL_BROKEN = -41709};17101711/*1712 * Peel the named object; i.e., if the object is a tag, resolve the1713 * tag recursively until a non-tag is found. If successful, store the1714 * result to sha1 and return PEEL_PEELED. If the object is not a tag1715 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1716 * and leave sha1 unchanged.1717 */1718static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1719{1720struct object *o =lookup_unknown_object(name);17211722if(o->type == OBJ_NONE) {1723int type =sha1_object_info(name, NULL);1724if(type <0|| !object_as_type(o, type,0))1725return PEEL_INVALID;1726}17271728if(o->type != OBJ_TAG)1729return PEEL_NON_TAG;17301731 o =deref_tag_noverify(o);1732if(!o)1733return PEEL_INVALID;17341735hashcpy(sha1, o->sha1);1736return PEEL_PEELED;1737}17381739/*1740 * Peel the entry (if possible) and return its new peel_status. If1741 * repeel is true, re-peel the entry even if there is an old peeled1742 * value that is already stored in it.1743 *1744 * It is OK to call this function with a packed reference entry that1745 * might be stale and might even refer to an object that has since1746 * been garbage-collected. In such a case, if the entry has1747 * REF_KNOWS_PEELED then leave the status unchanged and return1748 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1749 */1750static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1751{1752enum peel_status status;17531754if(entry->flag & REF_KNOWS_PEELED) {1755if(repeel) {1756 entry->flag &= ~REF_KNOWS_PEELED;1757hashclr(entry->u.value.peeled);1758}else{1759returnis_null_sha1(entry->u.value.peeled) ?1760 PEEL_NON_TAG : PEEL_PEELED;1761}1762}1763if(entry->flag & REF_ISBROKEN)1764return PEEL_BROKEN;1765if(entry->flag & REF_ISSYMREF)1766return PEEL_IS_SYMREF;17671768 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1769if(status == PEEL_PEELED || status == PEEL_NON_TAG)1770 entry->flag |= REF_KNOWS_PEELED;1771return status;1772}17731774intpeel_ref(const char*refname,unsigned char*sha1)1775{1776int flag;1777unsigned char base[20];17781779if(current_ref && (current_ref->name == refname1780|| !strcmp(current_ref->name, refname))) {1781if(peel_entry(current_ref,0))1782return-1;1783hashcpy(sha1, current_ref->u.value.peeled);1784return0;1785}17861787if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1788return-1;17891790/*1791 * If the reference is packed, read its ref_entry from the1792 * cache in the hope that we already know its peeled value.1793 * We only try this optimization on packed references because1794 * (a) forcing the filling of the loose reference cache could1795 * be expensive and (b) loose references anyway usually do not1796 * have REF_KNOWS_PEELED.1797 */1798if(flag & REF_ISPACKED) {1799struct ref_entry *r =get_packed_ref(refname);1800if(r) {1801if(peel_entry(r,0))1802return-1;1803hashcpy(sha1, r->u.value.peeled);1804return0;1805}1806}18071808returnpeel_object(base, sha1);1809}18101811struct warn_if_dangling_data {1812FILE*fp;1813const char*refname;1814const struct string_list *refnames;1815const char*msg_fmt;1816};18171818static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1819int flags,void*cb_data)1820{1821struct warn_if_dangling_data *d = cb_data;1822const char*resolves_to;1823unsigned char junk[20];18241825if(!(flags & REF_ISSYMREF))1826return0;18271828 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1829if(!resolves_to1830|| (d->refname1831?strcmp(resolves_to, d->refname)1832: !string_list_has_string(d->refnames, resolves_to))) {1833return0;1834}18351836fprintf(d->fp, d->msg_fmt, refname);1837fputc('\n', d->fp);1838return0;1839}18401841voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1842{1843struct warn_if_dangling_data data;18441845 data.fp = fp;1846 data.refname = refname;1847 data.refnames = NULL;1848 data.msg_fmt = msg_fmt;1849for_each_rawref(warn_if_dangling_symref, &data);1850}18511852voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1853{1854struct warn_if_dangling_data data;18551856 data.fp = fp;1857 data.refname = NULL;1858 data.refnames = refnames;1859 data.msg_fmt = msg_fmt;1860for_each_rawref(warn_if_dangling_symref, &data);1861}18621863/*1864 * Call fn for each reference in the specified ref_cache, omitting1865 * references not in the containing_dir of base. fn is called for all1866 * references, including broken ones. If fn ever returns a non-zero1867 * value, stop the iteration and return that value; otherwise, return1868 * 0.1869 */1870static intdo_for_each_entry(struct ref_cache *refs,const char*base,1871 each_ref_entry_fn fn,void*cb_data)1872{1873struct packed_ref_cache *packed_ref_cache;1874struct ref_dir *loose_dir;1875struct ref_dir *packed_dir;1876int retval =0;18771878/*1879 * We must make sure that all loose refs are read before accessing the1880 * packed-refs file; this avoids a race condition in which loose refs1881 * are migrated to the packed-refs file by a simultaneous process, but1882 * our in-memory view is from before the migration. get_packed_ref_cache()1883 * takes care of making sure our view is up to date with what is on1884 * disk.1885 */1886 loose_dir =get_loose_refs(refs);1887if(base && *base) {1888 loose_dir =find_containing_dir(loose_dir, base,0);1889}1890if(loose_dir)1891prime_ref_dir(loose_dir);18921893 packed_ref_cache =get_packed_ref_cache(refs);1894acquire_packed_ref_cache(packed_ref_cache);1895 packed_dir =get_packed_ref_dir(packed_ref_cache);1896if(base && *base) {1897 packed_dir =find_containing_dir(packed_dir, base,0);1898}18991900if(packed_dir && loose_dir) {1901sort_ref_dir(packed_dir);1902sort_ref_dir(loose_dir);1903 retval =do_for_each_entry_in_dirs(1904 packed_dir, loose_dir, fn, cb_data);1905}else if(packed_dir) {1906sort_ref_dir(packed_dir);1907 retval =do_for_each_entry_in_dir(1908 packed_dir,0, fn, cb_data);1909}else if(loose_dir) {1910sort_ref_dir(loose_dir);1911 retval =do_for_each_entry_in_dir(1912 loose_dir,0, fn, cb_data);1913}19141915release_packed_ref_cache(packed_ref_cache);1916return retval;1917}19181919/*1920 * Call fn for each reference in the specified ref_cache for which the1921 * refname begins with base. If trim is non-zero, then trim that many1922 * characters off the beginning of each refname before passing the1923 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1924 * broken references in the iteration. If fn ever returns a non-zero1925 * value, stop the iteration and return that value; otherwise, return1926 * 0.1927 */1928static intdo_for_each_ref(struct ref_cache *refs,const char*base,1929 each_ref_fn fn,int trim,int flags,void*cb_data)1930{1931struct ref_entry_cb data;1932 data.base = base;1933 data.trim = trim;1934 data.flags = flags;1935 data.fn = fn;1936 data.cb_data = cb_data;19371938returndo_for_each_entry(refs, base, do_one_ref, &data);1939}19401941static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1942{1943unsigned char sha1[20];1944int flag;19451946if(submodule) {1947if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1948returnfn("HEAD", sha1,0, cb_data);19491950return0;1951}19521953if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1954returnfn("HEAD", sha1, flag, cb_data);19551956return0;1957}19581959inthead_ref(each_ref_fn fn,void*cb_data)1960{1961returndo_head_ref(NULL, fn, cb_data);1962}19631964inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1965{1966returndo_head_ref(submodule, fn, cb_data);1967}19681969intfor_each_ref(each_ref_fn fn,void*cb_data)1970{1971returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1972}19731974intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1975{1976returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1977}19781979intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1980{1981returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1982}19831984intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1985 each_ref_fn fn,void*cb_data)1986{1987returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1988}19891990intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1991{1992returnfor_each_ref_in("refs/tags/", fn, cb_data);1993}19941995intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1996{1997returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1998}19992000intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2001{2002returnfor_each_ref_in("refs/heads/", fn, cb_data);2003}20042005intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2006{2007returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2008}20092010intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2011{2012returnfor_each_ref_in("refs/remotes/", fn, cb_data);2013}20142015intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2016{2017returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2018}20192020intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2021{2022returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2023}20242025inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2026{2027struct strbuf buf = STRBUF_INIT;2028int ret =0;2029unsigned char sha1[20];2030int flag;20312032strbuf_addf(&buf,"%sHEAD",get_git_namespace());2033if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2034 ret =fn(buf.buf, sha1, flag, cb_data);2035strbuf_release(&buf);20362037return ret;2038}20392040intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2041{2042struct strbuf buf = STRBUF_INIT;2043int ret;2044strbuf_addf(&buf,"%srefs/",get_git_namespace());2045 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2046strbuf_release(&buf);2047return ret;2048}20492050intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2051const char*prefix,void*cb_data)2052{2053struct strbuf real_pattern = STRBUF_INIT;2054struct ref_filter filter;2055int ret;20562057if(!prefix && !starts_with(pattern,"refs/"))2058strbuf_addstr(&real_pattern,"refs/");2059else if(prefix)2060strbuf_addstr(&real_pattern, prefix);2061strbuf_addstr(&real_pattern, pattern);20622063if(!has_glob_specials(pattern)) {2064/* Append implied '/' '*' if not present. */2065if(real_pattern.buf[real_pattern.len -1] !='/')2066strbuf_addch(&real_pattern,'/');2067/* No need to check for '*', there is none. */2068strbuf_addch(&real_pattern,'*');2069}20702071 filter.pattern = real_pattern.buf;2072 filter.fn = fn;2073 filter.cb_data = cb_data;2074 ret =for_each_ref(filter_refs, &filter);20752076strbuf_release(&real_pattern);2077return ret;2078}20792080intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2081{2082returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2083}20842085intfor_each_rawref(each_ref_fn fn,void*cb_data)2086{2087returndo_for_each_ref(&ref_cache,"", fn,0,2088 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2089}20902091const char*prettify_refname(const char*name)2092{2093return name + (2094starts_with(name,"refs/heads/") ?11:2095starts_with(name,"refs/tags/") ?10:2096starts_with(name,"refs/remotes/") ?13:20970);2098}20992100static const char*ref_rev_parse_rules[] = {2101"%.*s",2102"refs/%.*s",2103"refs/tags/%.*s",2104"refs/heads/%.*s",2105"refs/remotes/%.*s",2106"refs/remotes/%.*s/HEAD",2107 NULL2108};21092110intrefname_match(const char*abbrev_name,const char*full_name)2111{2112const char**p;2113const int abbrev_name_len =strlen(abbrev_name);21142115for(p = ref_rev_parse_rules; *p; p++) {2116if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2117return1;2118}2119}21202121return0;2122}21232124static voidunlock_ref(struct ref_lock *lock)2125{2126/* Do not free lock->lk -- atexit() still looks at them */2127if(lock->lk)2128rollback_lock_file(lock->lk);2129free(lock->ref_name);2130free(lock->orig_ref_name);2131free(lock);2132}21332134/* This function should make sure errno is meaningful on error */2135static struct ref_lock *verify_lock(struct ref_lock *lock,2136const unsigned char*old_sha1,int mustexist)2137{2138if(read_ref_full(lock->ref_name,2139 mustexist ? RESOLVE_REF_READING :0,2140 lock->old_sha1, NULL)) {2141int save_errno = errno;2142error("Can't verify ref%s", lock->ref_name);2143unlock_ref(lock);2144 errno = save_errno;2145return NULL;2146}2147if(hashcmp(lock->old_sha1, old_sha1)) {2148error("Ref%sis at%sbut expected%s", lock->ref_name,2149sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2150unlock_ref(lock);2151 errno = EBUSY;2152return NULL;2153}2154return lock;2155}21562157static intremove_empty_directories(const char*file)2158{2159/* we want to create a file but there is a directory there;2160 * if that is an empty directory (or a directory that contains2161 * only empty directories), remove them.2162 */2163struct strbuf path;2164int result, save_errno;21652166strbuf_init(&path,20);2167strbuf_addstr(&path, file);21682169 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2170 save_errno = errno;21712172strbuf_release(&path);2173 errno = save_errno;21742175return result;2176}21772178/*2179 * *string and *len will only be substituted, and *string returned (for2180 * later free()ing) if the string passed in is a magic short-hand form2181 * to name a branch.2182 */2183static char*substitute_branch_name(const char**string,int*len)2184{2185struct strbuf buf = STRBUF_INIT;2186int ret =interpret_branch_name(*string, *len, &buf);21872188if(ret == *len) {2189size_t size;2190*string =strbuf_detach(&buf, &size);2191*len = size;2192return(char*)*string;2193}21942195return NULL;2196}21972198intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2199{2200char*last_branch =substitute_branch_name(&str, &len);2201const char**p, *r;2202int refs_found =0;22032204*ref = NULL;2205for(p = ref_rev_parse_rules; *p; p++) {2206char fullref[PATH_MAX];2207unsigned char sha1_from_ref[20];2208unsigned char*this_result;2209int flag;22102211 this_result = refs_found ? sha1_from_ref : sha1;2212mksnpath(fullref,sizeof(fullref), *p, len, str);2213 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2214 this_result, &flag);2215if(r) {2216if(!refs_found++)2217*ref =xstrdup(r);2218if(!warn_ambiguous_refs)2219break;2220}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2221warning("ignoring dangling symref%s.", fullref);2222}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2223warning("ignoring broken ref%s.", fullref);2224}2225}2226free(last_branch);2227return refs_found;2228}22292230intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2231{2232char*last_branch =substitute_branch_name(&str, &len);2233const char**p;2234int logs_found =0;22352236*log = NULL;2237for(p = ref_rev_parse_rules; *p; p++) {2238unsigned char hash[20];2239char path[PATH_MAX];2240const char*ref, *it;22412242mksnpath(path,sizeof(path), *p, len, str);2243 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2244 hash, NULL);2245if(!ref)2246continue;2247if(reflog_exists(path))2248 it = path;2249else if(strcmp(ref, path) &&reflog_exists(ref))2250 it = ref;2251else2252continue;2253if(!logs_found++) {2254*log =xstrdup(it);2255hashcpy(sha1, hash);2256}2257if(!warn_ambiguous_refs)2258break;2259}2260free(last_branch);2261return logs_found;2262}22632264/*2265 * Locks a ref returning the lock on success and NULL on failure.2266 * On failure errno is set to something meaningful.2267 */2268static struct ref_lock *lock_ref_sha1_basic(const char*refname,2269const unsigned char*old_sha1,2270const struct string_list *skip,2271unsigned int flags,int*type_p)2272{2273char*ref_file;2274const char*orig_refname = refname;2275struct ref_lock *lock;2276int last_errno =0;2277int type, lflags;2278int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2279int resolve_flags =0;2280int missing =0;2281int attempts_remaining =3;22822283 lock =xcalloc(1,sizeof(struct ref_lock));2284 lock->lock_fd = -1;22852286if(mustexist)2287 resolve_flags |= RESOLVE_REF_READING;2288if(flags & REF_DELETING) {2289 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2290if(flags & REF_NODEREF)2291 resolve_flags |= RESOLVE_REF_NO_RECURSE;2292}22932294 refname =resolve_ref_unsafe(refname, resolve_flags,2295 lock->old_sha1, &type);2296if(!refname && errno == EISDIR) {2297/* we are trying to lock foo but we used to2298 * have foo/bar which now does not exist;2299 * it is normal for the empty directory 'foo'2300 * to remain.2301 */2302 ref_file =git_path("%s", orig_refname);2303if(remove_empty_directories(ref_file)) {2304 last_errno = errno;2305error("there are still refs under '%s'", orig_refname);2306goto error_return;2307}2308 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2309 lock->old_sha1, &type);2310}2311if(type_p)2312*type_p = type;2313if(!refname) {2314 last_errno = errno;2315error("unable to resolve reference%s:%s",2316 orig_refname,strerror(errno));2317goto error_return;2318}2319 missing =is_null_sha1(lock->old_sha1);2320/* When the ref did not exist and we are creating it,2321 * make sure there is no existing ref that is packed2322 * whose name begins with our refname, nor a ref whose2323 * name is a proper prefix of our refname.2324 */2325if(missing &&2326!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2327 last_errno = ENOTDIR;2328goto error_return;2329}23302331 lock->lk =xcalloc(1,sizeof(struct lock_file));23322333 lflags =0;2334if(flags & REF_NODEREF) {2335 refname = orig_refname;2336 lflags |= LOCK_NO_DEREF;2337}2338 lock->ref_name =xstrdup(refname);2339 lock->orig_ref_name =xstrdup(orig_refname);2340 ref_file =git_path("%s", refname);2341if(missing)2342 lock->force_write =1;2343if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2344 lock->force_write =1;23452346 retry:2347switch(safe_create_leading_directories(ref_file)) {2348case SCLD_OK:2349break;/* success */2350case SCLD_VANISHED:2351if(--attempts_remaining >0)2352goto retry;2353/* fall through */2354default:2355 last_errno = errno;2356error("unable to create directory for%s", ref_file);2357goto error_return;2358}23592360 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2361if(lock->lock_fd <0) {2362 last_errno = errno;2363if(errno == ENOENT && --attempts_remaining >0)2364/*2365 * Maybe somebody just deleted one of the2366 * directories leading to ref_file. Try2367 * again:2368 */2369goto retry;2370else{2371struct strbuf err = STRBUF_INIT;2372unable_to_lock_message(ref_file, errno, &err);2373error("%s", err.buf);2374strbuf_release(&err);2375goto error_return;2376}2377}2378return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23792380 error_return:2381unlock_ref(lock);2382 errno = last_errno;2383return NULL;2384}23852386/*2387 * Write an entry to the packed-refs file for the specified refname.2388 * If peeled is non-NULL, write it as the entry's peeled value.2389 */2390static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2391unsigned char*peeled)2392{2393fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2394if(peeled)2395fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2396}23972398/*2399 * An each_ref_entry_fn that writes the entry to a packed-refs file.2400 */2401static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2402{2403enum peel_status peel_status =peel_entry(entry,0);24042405if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2406error("internal error:%sis not a valid packed reference!",2407 entry->name);2408write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2409 peel_status == PEEL_PEELED ?2410 entry->u.value.peeled : NULL);2411return0;2412}24132414/* This should return a meaningful errno on failure */2415intlock_packed_refs(int flags)2416{2417struct packed_ref_cache *packed_ref_cache;24182419if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2420return-1;2421/*2422 * Get the current packed-refs while holding the lock. If the2423 * packed-refs file has been modified since we last read it,2424 * this will automatically invalidate the cache and re-read2425 * the packed-refs file.2426 */2427 packed_ref_cache =get_packed_ref_cache(&ref_cache);2428 packed_ref_cache->lock = &packlock;2429/* Increment the reference count to prevent it from being freed: */2430acquire_packed_ref_cache(packed_ref_cache);2431return0;2432}24332434/*2435 * Commit the packed refs changes.2436 * On error we must make sure that errno contains a meaningful value.2437 */2438intcommit_packed_refs(void)2439{2440struct packed_ref_cache *packed_ref_cache =2441get_packed_ref_cache(&ref_cache);2442int error =0;2443int save_errno =0;2444FILE*out;24452446if(!packed_ref_cache->lock)2447die("internal error: packed-refs not locked");24482449 out =fdopen_lock_file(packed_ref_cache->lock,"w");2450if(!out)2451die_errno("unable to fdopen packed-refs descriptor");24522453fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2454do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24550, write_packed_entry_fn, out);24562457if(commit_lock_file(packed_ref_cache->lock)) {2458 save_errno = errno;2459 error = -1;2460}2461 packed_ref_cache->lock = NULL;2462release_packed_ref_cache(packed_ref_cache);2463 errno = save_errno;2464return error;2465}24662467voidrollback_packed_refs(void)2468{2469struct packed_ref_cache *packed_ref_cache =2470get_packed_ref_cache(&ref_cache);24712472if(!packed_ref_cache->lock)2473die("internal error: packed-refs not locked");2474rollback_lock_file(packed_ref_cache->lock);2475 packed_ref_cache->lock = NULL;2476release_packed_ref_cache(packed_ref_cache);2477clear_packed_ref_cache(&ref_cache);2478}24792480struct ref_to_prune {2481struct ref_to_prune *next;2482unsigned char sha1[20];2483char name[FLEX_ARRAY];2484};24852486struct pack_refs_cb_data {2487unsigned int flags;2488struct ref_dir *packed_refs;2489struct ref_to_prune *ref_to_prune;2490};24912492/*2493 * An each_ref_entry_fn that is run over loose references only. If2494 * the loose reference can be packed, add an entry in the packed ref2495 * cache. If the reference should be pruned, also add it to2496 * ref_to_prune in the pack_refs_cb_data.2497 */2498static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2499{2500struct pack_refs_cb_data *cb = cb_data;2501enum peel_status peel_status;2502struct ref_entry *packed_entry;2503int is_tag_ref =starts_with(entry->name,"refs/tags/");25042505/* ALWAYS pack tags */2506if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2507return0;25082509/* Do not pack symbolic or broken refs: */2510if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2511return0;25122513/* Add a packed ref cache entry equivalent to the loose entry. */2514 peel_status =peel_entry(entry,1);2515if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2516die("internal error peeling reference%s(%s)",2517 entry->name,sha1_to_hex(entry->u.value.sha1));2518 packed_entry =find_ref(cb->packed_refs, entry->name);2519if(packed_entry) {2520/* Overwrite existing packed entry with info from loose entry */2521 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2522hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2523}else{2524 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2525 REF_ISPACKED | REF_KNOWS_PEELED,0);2526add_ref(cb->packed_refs, packed_entry);2527}2528hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25292530/* Schedule the loose reference for pruning if requested. */2531if((cb->flags & PACK_REFS_PRUNE)) {2532int namelen =strlen(entry->name) +1;2533struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2534hashcpy(n->sha1, entry->u.value.sha1);2535strcpy(n->name, entry->name);2536 n->next = cb->ref_to_prune;2537 cb->ref_to_prune = n;2538}2539return0;2540}25412542/*2543 * Remove empty parents, but spare refs/ and immediate subdirs.2544 * Note: munges *name.2545 */2546static voidtry_remove_empty_parents(char*name)2547{2548char*p, *q;2549int i;2550 p = name;2551for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2552while(*p && *p !='/')2553 p++;2554/* tolerate duplicate slashes; see check_refname_format() */2555while(*p =='/')2556 p++;2557}2558for(q = p; *q; q++)2559;2560while(1) {2561while(q > p && *q !='/')2562 q--;2563while(q > p && *(q-1) =='/')2564 q--;2565if(q == p)2566break;2567*q ='\0';2568if(rmdir(git_path("%s", name)))2569break;2570}2571}25722573/* make sure nobody touched the ref, and unlink */2574static voidprune_ref(struct ref_to_prune *r)2575{2576struct ref_transaction *transaction;2577struct strbuf err = STRBUF_INIT;25782579if(check_refname_format(r->name,0))2580return;25812582 transaction =ref_transaction_begin(&err);2583if(!transaction ||2584ref_transaction_delete(transaction, r->name, r->sha1,2585 REF_ISPRUNING, NULL, &err) ||2586ref_transaction_commit(transaction, &err)) {2587ref_transaction_free(transaction);2588error("%s", err.buf);2589strbuf_release(&err);2590return;2591}2592ref_transaction_free(transaction);2593strbuf_release(&err);2594try_remove_empty_parents(r->name);2595}25962597static voidprune_refs(struct ref_to_prune *r)2598{2599while(r) {2600prune_ref(r);2601 r = r->next;2602}2603}26042605intpack_refs(unsigned int flags)2606{2607struct pack_refs_cb_data cbdata;26082609memset(&cbdata,0,sizeof(cbdata));2610 cbdata.flags = flags;26112612lock_packed_refs(LOCK_DIE_ON_ERROR);2613 cbdata.packed_refs =get_packed_refs(&ref_cache);26142615do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2616 pack_if_possible_fn, &cbdata);26172618if(commit_packed_refs())2619die_errno("unable to overwrite old ref-pack file");26202621prune_refs(cbdata.ref_to_prune);2622return0;2623}26242625/*2626 * If entry is no longer needed in packed-refs, add it to the string2627 * list pointed to by cb_data. Reasons for deleting entries:2628 *2629 * - Entry is broken.2630 * - Entry is overridden by a loose ref.2631 * - Entry does not point at a valid object.2632 *2633 * In the first and third cases, also emit an error message because these2634 * are indications of repository corruption.2635 */2636static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2637{2638struct string_list *refs_to_delete = cb_data;26392640if(entry->flag & REF_ISBROKEN) {2641/* This shouldn't happen to packed refs. */2642error("%sis broken!", entry->name);2643string_list_append(refs_to_delete, entry->name);2644return0;2645}2646if(!has_sha1_file(entry->u.value.sha1)) {2647unsigned char sha1[20];2648int flags;26492650if(read_ref_full(entry->name,0, sha1, &flags))2651/* We should at least have found the packed ref. */2652die("Internal error");2653if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2654/*2655 * This packed reference is overridden by a2656 * loose reference, so it is OK that its value2657 * is no longer valid; for example, it might2658 * refer to an object that has been garbage2659 * collected. For this purpose we don't even2660 * care whether the loose reference itself is2661 * invalid, broken, symbolic, etc. Silently2662 * remove the packed reference.2663 */2664string_list_append(refs_to_delete, entry->name);2665return0;2666}2667/*2668 * There is no overriding loose reference, so the fact2669 * that this reference doesn't refer to a valid object2670 * indicates some kind of repository corruption.2671 * Report the problem, then omit the reference from2672 * the output.2673 */2674error("%sdoes not point to a valid object!", entry->name);2675string_list_append(refs_to_delete, entry->name);2676return0;2677}26782679return0;2680}26812682intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2683{2684struct ref_dir *packed;2685struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2686struct string_list_item *refname, *ref_to_delete;2687int ret, needs_repacking =0, removed =0;26882689assert(err);26902691/* Look for a packed ref */2692for_each_string_list_item(refname, refnames) {2693if(get_packed_ref(refname->string)) {2694 needs_repacking =1;2695break;2696}2697}26982699/* Avoid locking if we have nothing to do */2700if(!needs_repacking)2701return0;/* no refname exists in packed refs */27022703if(lock_packed_refs(0)) {2704unable_to_lock_message(git_path("packed-refs"), errno, err);2705return-1;2706}2707 packed =get_packed_refs(&ref_cache);27082709/* Remove refnames from the cache */2710for_each_string_list_item(refname, refnames)2711if(remove_entry(packed, refname->string) != -1)2712 removed =1;2713if(!removed) {2714/*2715 * All packed entries disappeared while we were2716 * acquiring the lock.2717 */2718rollback_packed_refs();2719return0;2720}27212722/* Remove any other accumulated cruft */2723do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2724for_each_string_list_item(ref_to_delete, &refs_to_delete) {2725if(remove_entry(packed, ref_to_delete->string) == -1)2726die("internal error");2727}27282729/* Write what remains */2730 ret =commit_packed_refs();2731if(ret)2732strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2733strerror(errno));2734return ret;2735}27362737static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2738{2739assert(err);27402741if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2742/*2743 * loose. The loose file name is the same as the2744 * lockfile name, minus ".lock":2745 */2746char*loose_filename =get_locked_file_path(lock->lk);2747int res =unlink_or_msg(loose_filename, err);2748free(loose_filename);2749if(res)2750return1;2751}2752return0;2753}27542755intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2756{2757struct ref_transaction *transaction;2758struct strbuf err = STRBUF_INIT;27592760 transaction =ref_transaction_begin(&err);2761if(!transaction ||2762ref_transaction_delete(transaction, refname,2763(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2764 flags, NULL, &err) ||2765ref_transaction_commit(transaction, &err)) {2766error("%s", err.buf);2767ref_transaction_free(transaction);2768strbuf_release(&err);2769return1;2770}2771ref_transaction_free(transaction);2772strbuf_release(&err);2773return0;2774}27752776/*2777 * People using contrib's git-new-workdir have .git/logs/refs ->2778 * /some/other/path/.git/logs/refs, and that may live on another device.2779 *2780 * IOW, to avoid cross device rename errors, the temporary renamed log must2781 * live into logs/refs.2782 */2783#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27842785static intrename_tmp_log(const char*newrefname)2786{2787int attempts_remaining =4;27882789 retry:2790switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2791case SCLD_OK:2792break;/* success */2793case SCLD_VANISHED:2794if(--attempts_remaining >0)2795goto retry;2796/* fall through */2797default:2798error("unable to create directory for%s", newrefname);2799return-1;2800}28012802if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2803if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2804/*2805 * rename(a, b) when b is an existing2806 * directory ought to result in ISDIR, but2807 * Solaris 5.8 gives ENOTDIR. Sheesh.2808 */2809if(remove_empty_directories(git_path("logs/%s", newrefname))) {2810error("Directory not empty: logs/%s", newrefname);2811return-1;2812}2813goto retry;2814}else if(errno == ENOENT && --attempts_remaining >0) {2815/*2816 * Maybe another process just deleted one of2817 * the directories in the path to newrefname.2818 * Try again from the beginning.2819 */2820goto retry;2821}else{2822error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2823 newrefname,strerror(errno));2824return-1;2825}2826}2827return0;2828}28292830static intrename_ref_available(const char*oldname,const char*newname)2831{2832struct string_list skip = STRING_LIST_INIT_NODUP;2833int ret;28342835string_list_insert(&skip, oldname);2836 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2837&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2838string_list_clear(&skip,0);2839return ret;2840}28412842static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2843const char*logmsg);28442845intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2846{2847unsigned char sha1[20], orig_sha1[20];2848int flag =0, logmoved =0;2849struct ref_lock *lock;2850struct stat loginfo;2851int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2852const char*symref = NULL;28532854if(log &&S_ISLNK(loginfo.st_mode))2855returnerror("reflog for%sis a symlink", oldrefname);28562857 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2858 orig_sha1, &flag);2859if(flag & REF_ISSYMREF)2860returnerror("refname%sis a symbolic ref, renaming it is not supported",2861 oldrefname);2862if(!symref)2863returnerror("refname%snot found", oldrefname);28642865if(!rename_ref_available(oldrefname, newrefname))2866return1;28672868if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2869returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2870 oldrefname,strerror(errno));28712872if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2873error("unable to delete old%s", oldrefname);2874goto rollback;2875}28762877if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2878delete_ref(newrefname, sha1, REF_NODEREF)) {2879if(errno==EISDIR) {2880if(remove_empty_directories(git_path("%s", newrefname))) {2881error("Directory not empty:%s", newrefname);2882goto rollback;2883}2884}else{2885error("unable to delete existing%s", newrefname);2886goto rollback;2887}2888}28892890if(log &&rename_tmp_log(newrefname))2891goto rollback;28922893 logmoved = log;28942895 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2896if(!lock) {2897error("unable to lock%sfor update", newrefname);2898goto rollback;2899}2900 lock->force_write =1;2901hashcpy(lock->old_sha1, orig_sha1);2902if(write_ref_sha1(lock, orig_sha1, logmsg)) {2903error("unable to write current sha1 into%s", newrefname);2904goto rollback;2905}29062907return0;29082909 rollback:2910 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2911if(!lock) {2912error("unable to lock%sfor rollback", oldrefname);2913goto rollbacklog;2914}29152916 lock->force_write =1;2917 flag = log_all_ref_updates;2918 log_all_ref_updates =0;2919if(write_ref_sha1(lock, orig_sha1, NULL))2920error("unable to write current sha1 into%s", oldrefname);2921 log_all_ref_updates = flag;29222923 rollbacklog:2924if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2925error("unable to restore logfile%sfrom%s:%s",2926 oldrefname, newrefname,strerror(errno));2927if(!logmoved && log &&2928rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2929error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2930 oldrefname,strerror(errno));29312932return1;2933}29342935static intclose_ref(struct ref_lock *lock)2936{2937if(close_lock_file(lock->lk))2938return-1;2939 lock->lock_fd = -1;2940return0;2941}29422943static intcommit_ref(struct ref_lock *lock)2944{2945if(commit_lock_file(lock->lk))2946return-1;2947 lock->lock_fd = -1;2948return0;2949}29502951/*2952 * copy the reflog message msg to buf, which has been allocated sufficiently2953 * large, while cleaning up the whitespaces. Especially, convert LF to space,2954 * because reflog file is one line per entry.2955 */2956static intcopy_msg(char*buf,const char*msg)2957{2958char*cp = buf;2959char c;2960int wasspace =1;29612962*cp++ ='\t';2963while((c = *msg++)) {2964if(wasspace &&isspace(c))2965continue;2966 wasspace =isspace(c);2967if(wasspace)2968 c =' ';2969*cp++ = c;2970}2971while(buf < cp &&isspace(cp[-1]))2972 cp--;2973*cp++ ='\n';2974return cp - buf;2975}29762977/* This function must set a meaningful errno on failure */2978intlog_ref_setup(const char*refname,char*logfile,int bufsize)2979{2980int logfd, oflags = O_APPEND | O_WRONLY;29812982git_snpath(logfile, bufsize,"logs/%s", refname);2983if(log_all_ref_updates &&2984(starts_with(refname,"refs/heads/") ||2985starts_with(refname,"refs/remotes/") ||2986starts_with(refname,"refs/notes/") ||2987!strcmp(refname,"HEAD"))) {2988if(safe_create_leading_directories(logfile) <0) {2989int save_errno = errno;2990error("unable to create directory for%s", logfile);2991 errno = save_errno;2992return-1;2993}2994 oflags |= O_CREAT;2995}29962997 logfd =open(logfile, oflags,0666);2998if(logfd <0) {2999if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3000return0;30013002if(errno == EISDIR) {3003if(remove_empty_directories(logfile)) {3004int save_errno = errno;3005error("There are still logs under '%s'",3006 logfile);3007 errno = save_errno;3008return-1;3009}3010 logfd =open(logfile, oflags,0666);3011}30123013if(logfd <0) {3014int save_errno = errno;3015error("Unable to append to%s:%s", logfile,3016strerror(errno));3017 errno = save_errno;3018return-1;3019}3020}30213022adjust_shared_perm(logfile);3023close(logfd);3024return0;3025}30263027static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3028const unsigned char*new_sha1,3029const char*committer,const char*msg)3030{3031int msglen, written;3032unsigned maxlen, len;3033char*logrec;30343035 msglen = msg ?strlen(msg) :0;3036 maxlen =strlen(committer) + msglen +100;3037 logrec =xmalloc(maxlen);3038 len =sprintf(logrec,"%s %s %s\n",3039sha1_to_hex(old_sha1),3040sha1_to_hex(new_sha1),3041 committer);3042if(msglen)3043 len +=copy_msg(logrec + len -1, msg) -1;30443045 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3046free(logrec);3047if(written != len)3048return-1;30493050return0;3051}30523053static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3054const unsigned char*new_sha1,const char*msg)3055{3056int logfd, result, oflags = O_APPEND | O_WRONLY;3057char log_file[PATH_MAX];30583059if(log_all_ref_updates <0)3060 log_all_ref_updates = !is_bare_repository();30613062 result =log_ref_setup(refname, log_file,sizeof(log_file));3063if(result)3064return result;30653066 logfd =open(log_file, oflags);3067if(logfd <0)3068return0;3069 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3070git_committer_info(0), msg);3071if(result) {3072int save_errno = errno;3073close(logfd);3074error("Unable to append to%s", log_file);3075 errno = save_errno;3076return-1;3077}3078if(close(logfd)) {3079int save_errno = errno;3080error("Unable to append to%s", log_file);3081 errno = save_errno;3082return-1;3083}3084return0;3085}30863087intis_branch(const char*refname)3088{3089return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3090}30913092/*3093 * Write sha1 into the ref specified by the lock. Make sure that errno3094 * is sane on error.3095 */3096static intwrite_ref_sha1(struct ref_lock *lock,3097const unsigned char*sha1,const char*logmsg)3098{3099static char term ='\n';3100struct object *o;31013102if(!lock) {3103 errno = EINVAL;3104return-1;3105}3106if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3107unlock_ref(lock);3108return0;3109}3110 o =parse_object(sha1);3111if(!o) {3112error("Trying to write ref%swith nonexistent object%s",3113 lock->ref_name,sha1_to_hex(sha1));3114unlock_ref(lock);3115 errno = EINVAL;3116return-1;3117}3118if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3119error("Trying to write non-commit object%sto branch%s",3120sha1_to_hex(sha1), lock->ref_name);3121unlock_ref(lock);3122 errno = EINVAL;3123return-1;3124}3125if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3126write_in_full(lock->lock_fd, &term,1) !=1||3127close_ref(lock) <0) {3128int save_errno = errno;3129error("Couldn't write%s", lock->lk->filename.buf);3130unlock_ref(lock);3131 errno = save_errno;3132return-1;3133}3134clear_loose_ref_cache(&ref_cache);3135if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3136(strcmp(lock->ref_name, lock->orig_ref_name) &&3137log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3138unlock_ref(lock);3139return-1;3140}3141if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3142/*3143 * Special hack: If a branch is updated directly and HEAD3144 * points to it (may happen on the remote side of a push3145 * for example) then logically the HEAD reflog should be3146 * updated too.3147 * A generic solution implies reverse symref information,3148 * but finding all symrefs pointing to the given branch3149 * would be rather costly for this rare event (the direct3150 * update of a branch) to be worth it. So let's cheat and3151 * check with HEAD only which should cover 99% of all usage3152 * scenarios (even 100% of the default ones).3153 */3154unsigned char head_sha1[20];3155int head_flag;3156const char*head_ref;3157 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3158 head_sha1, &head_flag);3159if(head_ref && (head_flag & REF_ISSYMREF) &&3160!strcmp(head_ref, lock->ref_name))3161log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3162}3163if(commit_ref(lock)) {3164error("Couldn't set%s", lock->ref_name);3165unlock_ref(lock);3166return-1;3167}3168unlock_ref(lock);3169return0;3170}31713172intcreate_symref(const char*ref_target,const char*refs_heads_master,3173const char*logmsg)3174{3175const char*lockpath;3176char ref[1000];3177int fd, len, written;3178char*git_HEAD =git_pathdup("%s", ref_target);3179unsigned char old_sha1[20], new_sha1[20];31803181if(logmsg &&read_ref(ref_target, old_sha1))3182hashclr(old_sha1);31833184if(safe_create_leading_directories(git_HEAD) <0)3185returnerror("unable to create directory for%s", git_HEAD);31863187#ifndef NO_SYMLINK_HEAD3188if(prefer_symlink_refs) {3189unlink(git_HEAD);3190if(!symlink(refs_heads_master, git_HEAD))3191goto done;3192fprintf(stderr,"no symlink - falling back to symbolic ref\n");3193}3194#endif31953196 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3197if(sizeof(ref) <= len) {3198error("refname too long:%s", refs_heads_master);3199goto error_free_return;3200}3201 lockpath =mkpath("%s.lock", git_HEAD);3202 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3203if(fd <0) {3204error("Unable to open%sfor writing", lockpath);3205goto error_free_return;3206}3207 written =write_in_full(fd, ref, len);3208if(close(fd) !=0|| written != len) {3209error("Unable to write to%s", lockpath);3210goto error_unlink_return;3211}3212if(rename(lockpath, git_HEAD) <0) {3213error("Unable to create%s", git_HEAD);3214goto error_unlink_return;3215}3216if(adjust_shared_perm(git_HEAD)) {3217error("Unable to fix permissions on%s", lockpath);3218 error_unlink_return:3219unlink_or_warn(lockpath);3220 error_free_return:3221free(git_HEAD);3222return-1;3223}32243225#ifndef NO_SYMLINK_HEAD3226 done:3227#endif3228if(logmsg && !read_ref(refs_heads_master, new_sha1))3229log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32303231free(git_HEAD);3232return0;3233}32343235struct read_ref_at_cb {3236const char*refname;3237unsigned long at_time;3238int cnt;3239int reccnt;3240unsigned char*sha1;3241int found_it;32423243unsigned char osha1[20];3244unsigned char nsha1[20];3245int tz;3246unsigned long date;3247char**msg;3248unsigned long*cutoff_time;3249int*cutoff_tz;3250int*cutoff_cnt;3251};32523253static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3254const char*email,unsigned long timestamp,int tz,3255const char*message,void*cb_data)3256{3257struct read_ref_at_cb *cb = cb_data;32583259 cb->reccnt++;3260 cb->tz = tz;3261 cb->date = timestamp;32623263if(timestamp <= cb->at_time || cb->cnt ==0) {3264if(cb->msg)3265*cb->msg =xstrdup(message);3266if(cb->cutoff_time)3267*cb->cutoff_time = timestamp;3268if(cb->cutoff_tz)3269*cb->cutoff_tz = tz;3270if(cb->cutoff_cnt)3271*cb->cutoff_cnt = cb->reccnt -1;3272/*3273 * we have not yet updated cb->[n|o]sha1 so they still3274 * hold the values for the previous record.3275 */3276if(!is_null_sha1(cb->osha1)) {3277hashcpy(cb->sha1, nsha1);3278if(hashcmp(cb->osha1, nsha1))3279warning("Log for ref%shas gap after%s.",3280 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3281}3282else if(cb->date == cb->at_time)3283hashcpy(cb->sha1, nsha1);3284else if(hashcmp(nsha1, cb->sha1))3285warning("Log for ref%sunexpectedly ended on%s.",3286 cb->refname,show_date(cb->date, cb->tz,3287 DATE_RFC2822));3288hashcpy(cb->osha1, osha1);3289hashcpy(cb->nsha1, nsha1);3290 cb->found_it =1;3291return1;3292}3293hashcpy(cb->osha1, osha1);3294hashcpy(cb->nsha1, nsha1);3295if(cb->cnt >0)3296 cb->cnt--;3297return0;3298}32993300static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3301const char*email,unsigned long timestamp,3302int tz,const char*message,void*cb_data)3303{3304struct read_ref_at_cb *cb = cb_data;33053306if(cb->msg)3307*cb->msg =xstrdup(message);3308if(cb->cutoff_time)3309*cb->cutoff_time = timestamp;3310if(cb->cutoff_tz)3311*cb->cutoff_tz = tz;3312if(cb->cutoff_cnt)3313*cb->cutoff_cnt = cb->reccnt;3314hashcpy(cb->sha1, osha1);3315if(is_null_sha1(cb->sha1))3316hashcpy(cb->sha1, nsha1);3317/* We just want the first entry */3318return1;3319}33203321intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3322unsigned char*sha1,char**msg,3323unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3324{3325struct read_ref_at_cb cb;33263327memset(&cb,0,sizeof(cb));3328 cb.refname = refname;3329 cb.at_time = at_time;3330 cb.cnt = cnt;3331 cb.msg = msg;3332 cb.cutoff_time = cutoff_time;3333 cb.cutoff_tz = cutoff_tz;3334 cb.cutoff_cnt = cutoff_cnt;3335 cb.sha1 = sha1;33363337for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33383339if(!cb.reccnt) {3340if(flags & GET_SHA1_QUIETLY)3341exit(128);3342else3343die("Log for%sis empty.", refname);3344}3345if(cb.found_it)3346return0;33473348for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33493350return1;3351}33523353intreflog_exists(const char*refname)3354{3355struct stat st;33563357return!lstat(git_path("logs/%s", refname), &st) &&3358S_ISREG(st.st_mode);3359}33603361intdelete_reflog(const char*refname)3362{3363returnremove_path(git_path("logs/%s", refname));3364}33653366static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3367{3368unsigned char osha1[20], nsha1[20];3369char*email_end, *message;3370unsigned long timestamp;3371int tz;33723373/* old SP new SP name <email> SP time TAB msg LF */3374if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3375get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3376get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3377!(email_end =strchr(sb->buf +82,'>')) ||3378 email_end[1] !=' '||3379!(timestamp =strtoul(email_end +2, &message,10)) ||3380!message || message[0] !=' '||3381(message[1] !='+'&& message[1] !='-') ||3382!isdigit(message[2]) || !isdigit(message[3]) ||3383!isdigit(message[4]) || !isdigit(message[5]))3384return0;/* corrupt? */3385 email_end[1] ='\0';3386 tz =strtol(message +1, NULL,10);3387if(message[6] !='\t')3388 message +=6;3389else3390 message +=7;3391returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3392}33933394static char*find_beginning_of_line(char*bob,char*scan)3395{3396while(bob < scan && *(--scan) !='\n')3397;/* keep scanning backwards */3398/*3399 * Return either beginning of the buffer, or LF at the end of3400 * the previous line.3401 */3402return scan;3403}34043405intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3406{3407struct strbuf sb = STRBUF_INIT;3408FILE*logfp;3409long pos;3410int ret =0, at_tail =1;34113412 logfp =fopen(git_path("logs/%s", refname),"r");3413if(!logfp)3414return-1;34153416/* Jump to the end */3417if(fseek(logfp,0, SEEK_END) <0)3418returnerror("cannot seek back reflog for%s:%s",3419 refname,strerror(errno));3420 pos =ftell(logfp);3421while(!ret &&0< pos) {3422int cnt;3423size_t nread;3424char buf[BUFSIZ];3425char*endp, *scanp;34263427/* Fill next block from the end */3428 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3429if(fseek(logfp, pos - cnt, SEEK_SET))3430returnerror("cannot seek back reflog for%s:%s",3431 refname,strerror(errno));3432 nread =fread(buf, cnt,1, logfp);3433if(nread !=1)3434returnerror("cannot read%dbytes from reflog for%s:%s",3435 cnt, refname,strerror(errno));3436 pos -= cnt;34373438 scanp = endp = buf + cnt;3439if(at_tail && scanp[-1] =='\n')3440/* Looking at the final LF at the end of the file */3441 scanp--;3442 at_tail =0;34433444while(buf < scanp) {3445/*3446 * terminating LF of the previous line, or the beginning3447 * of the buffer.3448 */3449char*bp;34503451 bp =find_beginning_of_line(buf, scanp);34523453if(*bp =='\n') {3454/*3455 * The newline is the end of the previous line,3456 * so we know we have complete line starting3457 * at (bp + 1). Prefix it onto any prior data3458 * we collected for the line and process it.3459 */3460strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3461 scanp = bp;3462 endp = bp +1;3463 ret =show_one_reflog_ent(&sb, fn, cb_data);3464strbuf_reset(&sb);3465if(ret)3466break;3467}else if(!pos) {3468/*3469 * We are at the start of the buffer, and the3470 * start of the file; there is no previous3471 * line, and we have everything for this one.3472 * Process it, and we can end the loop.3473 */3474strbuf_splice(&sb,0,0, buf, endp - buf);3475 ret =show_one_reflog_ent(&sb, fn, cb_data);3476strbuf_reset(&sb);3477break;3478}34793480if(bp == buf) {3481/*3482 * We are at the start of the buffer, and there3483 * is more file to read backwards. Which means3484 * we are in the middle of a line. Note that we3485 * may get here even if *bp was a newline; that3486 * just means we are at the exact end of the3487 * previous line, rather than some spot in the3488 * middle.3489 *3490 * Save away what we have to be combined with3491 * the data from the next read.3492 */3493strbuf_splice(&sb,0,0, buf, endp - buf);3494break;3495}3496}34973498}3499if(!ret && sb.len)3500die("BUG: reverse reflog parser had leftover data");35013502fclose(logfp);3503strbuf_release(&sb);3504return ret;3505}35063507intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3508{3509FILE*logfp;3510struct strbuf sb = STRBUF_INIT;3511int ret =0;35123513 logfp =fopen(git_path("logs/%s", refname),"r");3514if(!logfp)3515return-1;35163517while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3518 ret =show_one_reflog_ent(&sb, fn, cb_data);3519fclose(logfp);3520strbuf_release(&sb);3521return ret;3522}3523/*3524 * Call fn for each reflog in the namespace indicated by name. name3525 * must be empty or end with '/'. Name will be used as a scratch3526 * space, but its contents will be restored before return.3527 */3528static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3529{3530DIR*d =opendir(git_path("logs/%s", name->buf));3531int retval =0;3532struct dirent *de;3533int oldlen = name->len;35343535if(!d)3536return name->len ? errno :0;35373538while((de =readdir(d)) != NULL) {3539struct stat st;35403541if(de->d_name[0] =='.')3542continue;3543if(ends_with(de->d_name,".lock"))3544continue;3545strbuf_addstr(name, de->d_name);3546if(stat(git_path("logs/%s", name->buf), &st) <0) {3547;/* silently ignore */3548}else{3549if(S_ISDIR(st.st_mode)) {3550strbuf_addch(name,'/');3551 retval =do_for_each_reflog(name, fn, cb_data);3552}else{3553unsigned char sha1[20];3554if(read_ref_full(name->buf,0, sha1, NULL))3555 retval =error("bad ref for%s", name->buf);3556else3557 retval =fn(name->buf, sha1,0, cb_data);3558}3559if(retval)3560break;3561}3562strbuf_setlen(name, oldlen);3563}3564closedir(d);3565return retval;3566}35673568intfor_each_reflog(each_ref_fn fn,void*cb_data)3569{3570int retval;3571struct strbuf name;3572strbuf_init(&name, PATH_MAX);3573 retval =do_for_each_reflog(&name, fn, cb_data);3574strbuf_release(&name);3575return retval;3576}35773578/**3579 * Information needed for a single ref update. Set new_sha1 to the new3580 * value or to null_sha1 to delete the ref. To check the old value3581 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3582 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3583 * not exist before update.3584 */3585struct ref_update {3586/*3587 * If (flags & REF_HAVE_NEW), set the reference to this value:3588 */3589unsigned char new_sha1[20];3590/*3591 * If (flags & REF_HAVE_OLD), check that the reference3592 * previously had this value:3593 */3594unsigned char old_sha1[20];3595/*3596 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3597 * REF_DELETING, and REF_ISPRUNING:3598 */3599unsigned int flags;3600struct ref_lock *lock;3601int type;3602char*msg;3603const char refname[FLEX_ARRAY];3604};36053606/*3607 * Transaction states.3608 * OPEN: The transaction is in a valid state and can accept new updates.3609 * An OPEN transaction can be committed.3610 * CLOSED: A closed transaction is no longer active and no other operations3611 * than free can be used on it in this state.3612 * A transaction can either become closed by successfully committing3613 * an active transaction or if there is a failure while building3614 * the transaction thus rendering it failed/inactive.3615 */3616enum ref_transaction_state {3617 REF_TRANSACTION_OPEN =0,3618 REF_TRANSACTION_CLOSED =13619};36203621/*3622 * Data structure for holding a reference transaction, which can3623 * consist of checks and updates to multiple references, carried out3624 * as atomically as possible. This structure is opaque to callers.3625 */3626struct ref_transaction {3627struct ref_update **updates;3628size_t alloc;3629size_t nr;3630enum ref_transaction_state state;3631};36323633struct ref_transaction *ref_transaction_begin(struct strbuf *err)3634{3635assert(err);36363637returnxcalloc(1,sizeof(struct ref_transaction));3638}36393640voidref_transaction_free(struct ref_transaction *transaction)3641{3642int i;36433644if(!transaction)3645return;36463647for(i =0; i < transaction->nr; i++) {3648free(transaction->updates[i]->msg);3649free(transaction->updates[i]);3650}3651free(transaction->updates);3652free(transaction);3653}36543655static struct ref_update *add_update(struct ref_transaction *transaction,3656const char*refname)3657{3658size_t len =strlen(refname);3659struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36603661strcpy((char*)update->refname, refname);3662ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3663 transaction->updates[transaction->nr++] = update;3664return update;3665}36663667intref_transaction_update(struct ref_transaction *transaction,3668const char*refname,3669const unsigned char*new_sha1,3670const unsigned char*old_sha1,3671unsigned int flags,const char*msg,3672struct strbuf *err)3673{3674struct ref_update *update;36753676assert(err);36773678if(transaction->state != REF_TRANSACTION_OPEN)3679die("BUG: update called for transaction that is not open");36803681if(new_sha1 && !is_null_sha1(new_sha1) &&3682check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3683strbuf_addf(err,"refusing to update ref with bad name%s",3684 refname);3685return-1;3686}36873688 update =add_update(transaction, refname);3689if(new_sha1) {3690hashcpy(update->new_sha1, new_sha1);3691 flags |= REF_HAVE_NEW;3692}3693if(old_sha1) {3694hashcpy(update->old_sha1, old_sha1);3695 flags |= REF_HAVE_OLD;3696}3697 update->flags = flags;3698if(msg)3699 update->msg =xstrdup(msg);3700return0;3701}37023703intref_transaction_create(struct ref_transaction *transaction,3704const char*refname,3705const unsigned char*new_sha1,3706unsigned int flags,const char*msg,3707struct strbuf *err)3708{3709if(!new_sha1 ||is_null_sha1(new_sha1))3710die("BUG: create called without valid new_sha1");3711returnref_transaction_update(transaction, refname, new_sha1,3712 null_sha1, flags, msg, err);3713}37143715intref_transaction_delete(struct ref_transaction *transaction,3716const char*refname,3717const unsigned char*old_sha1,3718unsigned int flags,const char*msg,3719struct strbuf *err)3720{3721if(old_sha1 &&is_null_sha1(old_sha1))3722die("BUG: delete called with old_sha1 set to zeros");3723returnref_transaction_update(transaction, refname,3724 null_sha1, old_sha1,3725 flags, msg, err);3726}37273728intref_transaction_verify(struct ref_transaction *transaction,3729const char*refname,3730const unsigned char*old_sha1,3731unsigned int flags,3732struct strbuf *err)3733{3734if(!old_sha1)3735die("BUG: verify called with old_sha1 set to NULL");3736returnref_transaction_update(transaction, refname,3737 NULL, old_sha1,3738 flags, NULL, err);3739}37403741intupdate_ref(const char*msg,const char*refname,3742const unsigned char*new_sha1,const unsigned char*old_sha1,3743unsigned int flags,enum action_on_err onerr)3744{3745struct ref_transaction *t;3746struct strbuf err = STRBUF_INIT;37473748 t =ref_transaction_begin(&err);3749if(!t ||3750ref_transaction_update(t, refname, new_sha1, old_sha1,3751 flags, msg, &err) ||3752ref_transaction_commit(t, &err)) {3753const char*str ="update_ref failed for ref '%s':%s";37543755ref_transaction_free(t);3756switch(onerr) {3757case UPDATE_REFS_MSG_ON_ERR:3758error(str, refname, err.buf);3759break;3760case UPDATE_REFS_DIE_ON_ERR:3761die(str, refname, err.buf);3762break;3763case UPDATE_REFS_QUIET_ON_ERR:3764break;3765}3766strbuf_release(&err);3767return1;3768}3769strbuf_release(&err);3770ref_transaction_free(t);3771return0;3772}37733774static intref_update_compare(const void*r1,const void*r2)3775{3776const struct ref_update *const*u1 = r1;3777const struct ref_update *const*u2 = r2;3778returnstrcmp((*u1)->refname, (*u2)->refname);3779}37803781static intref_update_reject_duplicates(struct ref_update **updates,int n,3782struct strbuf *err)3783{3784int i;37853786assert(err);37873788for(i =1; i < n; i++)3789if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3790strbuf_addf(err,3791"Multiple updates for ref '%s' not allowed.",3792 updates[i]->refname);3793return1;3794}3795return0;3796}37973798intref_transaction_commit(struct ref_transaction *transaction,3799struct strbuf *err)3800{3801int ret =0, i;3802int n = transaction->nr;3803struct ref_update **updates = transaction->updates;3804struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3805struct string_list_item *ref_to_delete;38063807assert(err);38083809if(transaction->state != REF_TRANSACTION_OPEN)3810die("BUG: commit called for transaction that is not open");38113812if(!n) {3813 transaction->state = REF_TRANSACTION_CLOSED;3814return0;3815}38163817/* Copy, sort, and reject duplicate refs */3818qsort(updates, n,sizeof(*updates), ref_update_compare);3819if(ref_update_reject_duplicates(updates, n, err)) {3820 ret = TRANSACTION_GENERIC_ERROR;3821goto cleanup;3822}38233824/* Acquire all locks while verifying old values */3825for(i =0; i < n; i++) {3826struct ref_update *update = updates[i];3827unsigned int flags = update->flags;38283829if((flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3830 flags |= REF_DELETING;3831 update->lock =lock_ref_sha1_basic(3832 update->refname,3833((update->flags & REF_HAVE_OLD) ?3834 update->old_sha1 : NULL),3835 NULL,3836 flags,3837&update->type);3838if(!update->lock) {3839 ret = (errno == ENOTDIR)3840? TRANSACTION_NAME_CONFLICT3841: TRANSACTION_GENERIC_ERROR;3842strbuf_addf(err,"Cannot lock the ref '%s'.",3843 update->refname);3844goto cleanup;3845}3846}38473848/* Perform updates first so live commits remain referenced */3849for(i =0; i < n; i++) {3850struct ref_update *update = updates[i];3851int flags = update->flags;38523853if((flags & REF_HAVE_NEW) && !is_null_sha1(update->new_sha1)) {3854if(write_ref_sha1(update->lock, update->new_sha1,3855 update->msg)) {3856 update->lock = NULL;/* freed by write_ref_sha1 */3857strbuf_addf(err,"Cannot update the ref '%s'.",3858 update->refname);3859 ret = TRANSACTION_GENERIC_ERROR;3860goto cleanup;3861}3862 update->lock = NULL;/* freed by write_ref_sha1 */3863}3864}38653866/* Perform deletes now that updates are safely completed */3867for(i =0; i < n; i++) {3868struct ref_update *update = updates[i];3869int flags = update->flags;38703871if((flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1)) {3872if(delete_ref_loose(update->lock, update->type, err)) {3873 ret = TRANSACTION_GENERIC_ERROR;3874goto cleanup;3875}38763877if(!(flags & REF_ISPRUNING))3878string_list_append(&refs_to_delete,3879 update->lock->ref_name);3880}3881}38823883if(repack_without_refs(&refs_to_delete, err)) {3884 ret = TRANSACTION_GENERIC_ERROR;3885goto cleanup;3886}3887for_each_string_list_item(ref_to_delete, &refs_to_delete)3888unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3889clear_loose_ref_cache(&ref_cache);38903891cleanup:3892 transaction->state = REF_TRANSACTION_CLOSED;38933894for(i =0; i < n; i++)3895if(updates[i]->lock)3896unlock_ref(updates[i]->lock);3897string_list_clear(&refs_to_delete,0);3898return ret;3899}39003901char*shorten_unambiguous_ref(const char*refname,int strict)3902{3903int i;3904static char**scanf_fmts;3905static int nr_rules;3906char*short_name;39073908if(!nr_rules) {3909/*3910 * Pre-generate scanf formats from ref_rev_parse_rules[].3911 * Generate a format suitable for scanf from a3912 * ref_rev_parse_rules rule by interpolating "%s" at the3913 * location of the "%.*s".3914 */3915size_t total_len =0;3916size_t offset =0;39173918/* the rule list is NULL terminated, count them first */3919for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3920/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3921 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;39223923 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);39243925 offset =0;3926for(i =0; i < nr_rules; i++) {3927assert(offset < total_len);3928 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3929 offset +=snprintf(scanf_fmts[i], total_len - offset,3930 ref_rev_parse_rules[i],2,"%s") +1;3931}3932}39333934/* bail out if there are no rules */3935if(!nr_rules)3936returnxstrdup(refname);39373938/* buffer for scanf result, at most refname must fit */3939 short_name =xstrdup(refname);39403941/* skip first rule, it will always match */3942for(i = nr_rules -1; i >0; --i) {3943int j;3944int rules_to_fail = i;3945int short_name_len;39463947if(1!=sscanf(refname, scanf_fmts[i], short_name))3948continue;39493950 short_name_len =strlen(short_name);39513952/*3953 * in strict mode, all (except the matched one) rules3954 * must fail to resolve to a valid non-ambiguous ref3955 */3956if(strict)3957 rules_to_fail = nr_rules;39583959/*3960 * check if the short name resolves to a valid ref,3961 * but use only rules prior to the matched one3962 */3963for(j =0; j < rules_to_fail; j++) {3964const char*rule = ref_rev_parse_rules[j];3965char refname[PATH_MAX];39663967/* skip matched rule */3968if(i == j)3969continue;39703971/*3972 * the short name is ambiguous, if it resolves3973 * (with this previous rule) to a valid ref3974 * read_ref() returns 0 on success3975 */3976mksnpath(refname,sizeof(refname),3977 rule, short_name_len, short_name);3978if(ref_exists(refname))3979break;3980}39813982/*3983 * short name is non-ambiguous if all previous rules3984 * haven't resolved to a valid ref3985 */3986if(j == rules_to_fail)3987return short_name;3988}39893990free(short_name);3991returnxstrdup(refname);3992}39933994static struct string_list *hide_refs;39953996intparse_hide_refs_config(const char*var,const char*value,const char*section)3997{3998if(!strcmp("transfer.hiderefs", var) ||3999/* NEEDSWORK: use parse_config_key() once both are merged */4000(starts_with(var, section) && var[strlen(section)] =='.'&&4001!strcmp(var +strlen(section),".hiderefs"))) {4002char*ref;4003int len;40044005if(!value)4006returnconfig_error_nonbool(var);4007 ref =xstrdup(value);4008 len =strlen(ref);4009while(len && ref[len -1] =='/')4010 ref[--len] ='\0';4011if(!hide_refs) {4012 hide_refs =xcalloc(1,sizeof(*hide_refs));4013 hide_refs->strdup_strings =1;4014}4015string_list_append(hide_refs, ref);4016}4017return0;4018}40194020intref_is_hidden(const char*refname)4021{4022struct string_list_item *item;40234024if(!hide_refs)4025return0;4026for_each_string_list_item(item, hide_refs) {4027int len;4028if(!starts_with(refname, item->string))4029continue;4030 len =strlen(item->string);4031if(!refname[len] || refname[len] =='/')4032return1;4033}4034return0;4035}40364037struct expire_reflog_cb {4038unsigned int flags;4039 reflog_expiry_should_prune_fn *should_prune_fn;4040void*policy_cb;4041FILE*newlog;4042unsigned char last_kept_sha1[20];4043};40444045static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4046const char*email,unsigned long timestamp,int tz,4047const char*message,void*cb_data)4048{4049struct expire_reflog_cb *cb = cb_data;4050struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;40514052if(cb->flags & EXPIRE_REFLOGS_REWRITE)4053 osha1 = cb->last_kept_sha1;40544055if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4056 message, policy_cb)) {4057if(!cb->newlog)4058printf("would prune%s", message);4059else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4060printf("prune%s", message);4061}else{4062if(cb->newlog) {4063fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4064sha1_to_hex(osha1),sha1_to_hex(nsha1),4065 email, timestamp, tz, message);4066hashcpy(cb->last_kept_sha1, nsha1);4067}4068if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4069printf("keep%s", message);4070}4071return0;4072}40734074intreflog_expire(const char*refname,const unsigned char*sha1,4075unsigned int flags,4076 reflog_expiry_prepare_fn prepare_fn,4077 reflog_expiry_should_prune_fn should_prune_fn,4078 reflog_expiry_cleanup_fn cleanup_fn,4079void*policy_cb_data)4080{4081static struct lock_file reflog_lock;4082struct expire_reflog_cb cb;4083struct ref_lock *lock;4084char*log_file;4085int status =0;40864087memset(&cb,0,sizeof(cb));4088 cb.flags = flags;4089 cb.policy_cb = policy_cb_data;4090 cb.should_prune_fn = should_prune_fn;40914092/*4093 * The reflog file is locked by holding the lock on the4094 * reference itself, plus we might need to update the4095 * reference if --updateref was specified:4096 */4097 lock =lock_ref_sha1_basic(refname, sha1, NULL,0, NULL);4098if(!lock)4099returnerror("cannot lock ref '%s'", refname);4100if(!reflog_exists(refname)) {4101unlock_ref(lock);4102return0;4103}41044105 log_file =git_pathdup("logs/%s", refname);4106if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4107/*4108 * Even though holding $GIT_DIR/logs/$reflog.lock has4109 * no locking implications, we use the lock_file4110 * machinery here anyway because it does a lot of the4111 * work we need, including cleaning up if the program4112 * exits unexpectedly.4113 */4114if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4115struct strbuf err = STRBUF_INIT;4116unable_to_lock_message(log_file, errno, &err);4117error("%s", err.buf);4118strbuf_release(&err);4119goto failure;4120}4121 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4122if(!cb.newlog) {4123error("cannot fdopen%s(%s)",4124 reflog_lock.filename.buf,strerror(errno));4125goto failure;4126}4127}41284129(*prepare_fn)(refname, sha1, cb.policy_cb);4130for_each_reflog_ent(refname, expire_reflog_ent, &cb);4131(*cleanup_fn)(cb.policy_cb);41324133if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4134if(close_lock_file(&reflog_lock)) {4135 status |=error("couldn't write%s:%s", log_file,4136strerror(errno));4137}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&4138(write_in_full(lock->lock_fd,4139sha1_to_hex(cb.last_kept_sha1),40) !=40||4140write_str_in_full(lock->lock_fd,"\n") !=1||4141close_ref(lock) <0)) {4142 status |=error("couldn't write%s",4143 lock->lk->filename.buf);4144rollback_lock_file(&reflog_lock);4145}else if(commit_lock_file(&reflog_lock)) {4146 status |=error("unable to commit reflog '%s' (%s)",4147 log_file,strerror(errno));4148}else if((flags & EXPIRE_REFLOGS_UPDATE_REF) &&commit_ref(lock)) {4149 status |=error("couldn't set%s", lock->ref_name);4150}4151}4152free(log_file);4153unlock_ref(lock);4154return status;41554156 failure:4157rollback_lock_file(&reflog_lock);4158free(log_file);4159unlock_ref(lock);4160return-1;4161}