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; 15}; 16 17/* 18 * How to handle various characters in refnames: 19 * 0: An acceptable character for refs 20 * 1: End-of-component 21 * 2: ., look for a preceding . to reject .. in refs 22 * 3: {, look for a preceding @ to reject @{ in refs 23 * 4: A bad character: ASCII control characters, and 24 * ":", "?", "[", "\", "^", "~", SP, or TAB 25 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 26 */ 27static unsigned char refname_disposition[256] = { 281,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 304,0,0,0,0,0,0,0,0,0,5,0,0,0,2,1, 310,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 320,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 330,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 340,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 350,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 36}; 37 38/* 39 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 40 * refs (i.e., because the reference is about to be deleted anyway). 41 */ 42#define REF_DELETING 0x02 43 44/* 45 * Used as a flag in ref_update::flags when a loose ref is being 46 * pruned. 47 */ 48#define REF_ISPRUNING 0x04 49 50/* 51 * Used as a flag in ref_update::flags when the reference should be 52 * updated to new_sha1. 53 */ 54#define REF_HAVE_NEW 0x08 55 56/* 57 * Used as a flag in ref_update::flags when old_sha1 should be 58 * checked. 59 */ 60#define REF_HAVE_OLD 0x10 61 62/* 63 * Used as a flag in ref_update::flags when the lockfile needs to be 64 * committed. 65 */ 66#define REF_NEEDS_COMMIT 0x20 67 68/* 69 * Try to read one refname component from the front of refname. 70 * Return the length of the component found, or -1 if the component is 71 * not legal. It is legal if it is something reasonable to have under 72 * ".git/refs/"; We do not like it if: 73 * 74 * - any path component of it begins with ".", or 75 * - it has double dots "..", or 76 * - it has ASCII control characters, or 77 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 78 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 79 * - it ends with a "/", or 80 * - it ends with ".lock", or 81 * - it contains a "@{" portion 82 */ 83static intcheck_refname_component(const char*refname,int*flags) 84{ 85const char*cp; 86char last ='\0'; 87 88for(cp = refname; ; cp++) { 89int ch = *cp &255; 90unsigned char disp = refname_disposition[ch]; 91switch(disp) { 92case1: 93goto out; 94case2: 95if(last =='.') 96return-1;/* Refname contains "..". */ 97break; 98case3: 99if(last =='@') 100return-1;/* Refname contains "@{". */ 101break; 102case4: 103return-1; 104case5: 105if(!(*flags & REFNAME_REFSPEC_PATTERN)) 106return-1;/* refspec can't be a pattern */ 107 108/* 109 * Unset the pattern flag so that we only accept 110 * a single asterisk for one side of refspec. 111 */ 112*flags &= ~ REFNAME_REFSPEC_PATTERN; 113break; 114} 115 last = ch; 116} 117out: 118if(cp == refname) 119return0;/* Component has zero length. */ 120if(refname[0] =='.') 121return-1;/* Component starts with '.'. */ 122if(cp - refname >= LOCK_SUFFIX_LEN && 123!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 124return-1;/* Refname ends with ".lock". */ 125return cp - refname; 126} 127 128intcheck_refname_format(const char*refname,int flags) 129{ 130int component_len, component_count =0; 131 132if(!strcmp(refname,"@")) 133/* Refname is a single character '@'. */ 134return-1; 135 136while(1) { 137/* We are at the start of a path component. */ 138 component_len =check_refname_component(refname, &flags); 139if(component_len <=0) 140return-1; 141 142 component_count++; 143if(refname[component_len] =='\0') 144break; 145/* Skip to next component. */ 146 refname += component_len +1; 147} 148 149if(refname[component_len -1] =='.') 150return-1;/* Refname ends with '.'. */ 151if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 152return-1;/* Refname has only one component. */ 153return0; 154} 155 156struct ref_entry; 157 158/* 159 * Information used (along with the information in ref_entry) to 160 * describe a single cached reference. This data structure only 161 * occurs embedded in a union in struct ref_entry, and only when 162 * (ref_entry->flag & REF_DIR) is zero. 163 */ 164struct ref_value { 165/* 166 * The name of the object to which this reference resolves 167 * (which may be a tag object). If REF_ISBROKEN, this is 168 * null. If REF_ISSYMREF, then this is the name of the object 169 * referred to by the last reference in the symlink chain. 170 */ 171unsigned char sha1[20]; 172 173/* 174 * If REF_KNOWS_PEELED, then this field holds the peeled value 175 * of this reference, or null if the reference is known not to 176 * be peelable. See the documentation for peel_ref() for an 177 * exact definition of "peelable". 178 */ 179unsigned char peeled[20]; 180}; 181 182struct ref_cache; 183 184/* 185 * Information used (along with the information in ref_entry) to 186 * describe a level in the hierarchy of references. This data 187 * structure only occurs embedded in a union in struct ref_entry, and 188 * only when (ref_entry.flag & REF_DIR) is set. In that case, 189 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 190 * in the directory have already been read: 191 * 192 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 193 * or packed references, already read. 194 * 195 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 196 * references that hasn't been read yet (nor has any of its 197 * subdirectories). 198 * 199 * Entries within a directory are stored within a growable array of 200 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 201 * sorted are sorted by their component name in strcmp() order and the 202 * remaining entries are unsorted. 203 * 204 * Loose references are read lazily, one directory at a time. When a 205 * directory of loose references is read, then all of the references 206 * in that directory are stored, and REF_INCOMPLETE stubs are created 207 * for any subdirectories, but the subdirectories themselves are not 208 * read. The reading is triggered by get_ref_dir(). 209 */ 210struct ref_dir { 211int nr, alloc; 212 213/* 214 * Entries with index 0 <= i < sorted are sorted by name. New 215 * entries are appended to the list unsorted, and are sorted 216 * only when required; thus we avoid the need to sort the list 217 * after the addition of every reference. 218 */ 219int sorted; 220 221/* A pointer to the ref_cache that contains this ref_dir. */ 222struct ref_cache *ref_cache; 223 224struct ref_entry **entries; 225}; 226 227/* 228 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 229 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 230 * public values; see refs.h. 231 */ 232 233/* 234 * The field ref_entry->u.value.peeled of this value entry contains 235 * the correct peeled value for the reference, which might be 236 * null_sha1 if the reference is not a tag or if it is broken. 237 */ 238#define REF_KNOWS_PEELED 0x10 239 240/* ref_entry represents a directory of references */ 241#define REF_DIR 0x20 242 243/* 244 * Entry has not yet been read from disk (used only for REF_DIR 245 * entries representing loose references) 246 */ 247#define REF_INCOMPLETE 0x40 248 249/* 250 * A ref_entry represents either a reference or a "subdirectory" of 251 * references. 252 * 253 * Each directory in the reference namespace is represented by a 254 * ref_entry with (flags & REF_DIR) set and containing a subdir member 255 * that holds the entries in that directory that have been read so 256 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 257 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 258 * used for loose reference directories. 259 * 260 * References are represented by a ref_entry with (flags & REF_DIR) 261 * unset and a value member that describes the reference's value. The 262 * flag member is at the ref_entry level, but it is also needed to 263 * interpret the contents of the value field (in other words, a 264 * ref_value object is not very much use without the enclosing 265 * ref_entry). 266 * 267 * Reference names cannot end with slash and directories' names are 268 * always stored with a trailing slash (except for the top-level 269 * directory, which is always denoted by ""). This has two nice 270 * consequences: (1) when the entries in each subdir are sorted 271 * lexicographically by name (as they usually are), the references in 272 * a whole tree can be generated in lexicographic order by traversing 273 * the tree in left-to-right, depth-first order; (2) the names of 274 * references and subdirectories cannot conflict, and therefore the 275 * presence of an empty subdirectory does not block the creation of a 276 * similarly-named reference. (The fact that reference names with the 277 * same leading components can conflict *with each other* is a 278 * separate issue that is regulated by verify_refname_available().) 279 * 280 * Please note that the name field contains the fully-qualified 281 * reference (or subdirectory) name. Space could be saved by only 282 * storing the relative names. But that would require the full names 283 * to be generated on the fly when iterating in do_for_each_ref(), and 284 * would break callback functions, who have always been able to assume 285 * that the name strings that they are passed will not be freed during 286 * the iteration. 287 */ 288struct ref_entry { 289unsigned char flag;/* ISSYMREF? ISPACKED? */ 290union{ 291struct ref_value value;/* if not (flags&REF_DIR) */ 292struct ref_dir subdir;/* if (flags&REF_DIR) */ 293} u; 294/* 295 * The full name of the reference (e.g., "refs/heads/master") 296 * or the full name of the directory with a trailing slash 297 * (e.g., "refs/heads/"): 298 */ 299char name[FLEX_ARRAY]; 300}; 301 302static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 303 304static struct ref_dir *get_ref_dir(struct ref_entry *entry) 305{ 306struct ref_dir *dir; 307assert(entry->flag & REF_DIR); 308 dir = &entry->u.subdir; 309if(entry->flag & REF_INCOMPLETE) { 310read_loose_refs(entry->name, dir); 311 entry->flag &= ~REF_INCOMPLETE; 312} 313return dir; 314} 315 316/* 317 * Check if a refname is safe. 318 * For refs that start with "refs/" we consider it safe as long they do 319 * not try to resolve to outside of refs/. 320 * 321 * For all other refs we only consider them safe iff they only contain 322 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 323 * "config"). 324 */ 325static intrefname_is_safe(const char*refname) 326{ 327if(starts_with(refname,"refs/")) { 328char*buf; 329int result; 330 331 buf =xmalloc(strlen(refname) +1); 332/* 333 * Does the refname try to escape refs/? 334 * For example: refs/foo/../bar is safe but refs/foo/../../bar 335 * is not. 336 */ 337 result = !normalize_path_copy(buf, refname +strlen("refs/")); 338free(buf); 339return result; 340} 341while(*refname) { 342if(!isupper(*refname) && *refname !='_') 343return0; 344 refname++; 345} 346return1; 347} 348 349static struct ref_entry *create_ref_entry(const char*refname, 350const unsigned char*sha1,int flag, 351int check_name) 352{ 353int len; 354struct ref_entry *ref; 355 356if(check_name && 357check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 358die("Reference has invalid format: '%s'", refname); 359if(!check_name && !refname_is_safe(refname)) 360die("Reference has invalid name: '%s'", refname); 361 len =strlen(refname) +1; 362 ref =xmalloc(sizeof(struct ref_entry) + len); 363hashcpy(ref->u.value.sha1, sha1); 364hashclr(ref->u.value.peeled); 365memcpy(ref->name, refname, len); 366 ref->flag = flag; 367return ref; 368} 369 370static voidclear_ref_dir(struct ref_dir *dir); 371 372static voidfree_ref_entry(struct ref_entry *entry) 373{ 374if(entry->flag & REF_DIR) { 375/* 376 * Do not use get_ref_dir() here, as that might 377 * trigger the reading of loose refs. 378 */ 379clear_ref_dir(&entry->u.subdir); 380} 381free(entry); 382} 383 384/* 385 * Add a ref_entry to the end of dir (unsorted). Entry is always 386 * stored directly in dir; no recursion into subdirectories is 387 * done. 388 */ 389static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 390{ 391ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 392 dir->entries[dir->nr++] = entry; 393/* optimize for the case that entries are added in order */ 394if(dir->nr ==1|| 395(dir->nr == dir->sorted +1&& 396strcmp(dir->entries[dir->nr -2]->name, 397 dir->entries[dir->nr -1]->name) <0)) 398 dir->sorted = dir->nr; 399} 400 401/* 402 * Clear and free all entries in dir, recursively. 403 */ 404static voidclear_ref_dir(struct ref_dir *dir) 405{ 406int i; 407for(i =0; i < dir->nr; i++) 408free_ref_entry(dir->entries[i]); 409free(dir->entries); 410 dir->sorted = dir->nr = dir->alloc =0; 411 dir->entries = NULL; 412} 413 414/* 415 * Create a struct ref_entry object for the specified dirname. 416 * dirname is the name of the directory with a trailing slash (e.g., 417 * "refs/heads/") or "" for the top-level directory. 418 */ 419static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 420const char*dirname,size_t len, 421int incomplete) 422{ 423struct ref_entry *direntry; 424 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 425memcpy(direntry->name, dirname, len); 426 direntry->name[len] ='\0'; 427 direntry->u.subdir.ref_cache = ref_cache; 428 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 429return direntry; 430} 431 432static intref_entry_cmp(const void*a,const void*b) 433{ 434struct ref_entry *one = *(struct ref_entry **)a; 435struct ref_entry *two = *(struct ref_entry **)b; 436returnstrcmp(one->name, two->name); 437} 438 439static voidsort_ref_dir(struct ref_dir *dir); 440 441struct string_slice { 442size_t len; 443const char*str; 444}; 445 446static intref_entry_cmp_sslice(const void*key_,const void*ent_) 447{ 448const struct string_slice *key = key_; 449const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 450int cmp =strncmp(key->str, ent->name, key->len); 451if(cmp) 452return cmp; 453return'\0'- (unsigned char)ent->name[key->len]; 454} 455 456/* 457 * Return the index of the entry with the given refname from the 458 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 459 * no such entry is found. dir must already be complete. 460 */ 461static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 462{ 463struct ref_entry **r; 464struct string_slice key; 465 466if(refname == NULL || !dir->nr) 467return-1; 468 469sort_ref_dir(dir); 470 key.len = len; 471 key.str = refname; 472 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 473 ref_entry_cmp_sslice); 474 475if(r == NULL) 476return-1; 477 478return r - dir->entries; 479} 480 481/* 482 * Search for a directory entry directly within dir (without 483 * recursing). Sort dir if necessary. subdirname must be a directory 484 * name (i.e., end in '/'). If mkdir is set, then create the 485 * directory if it is missing; otherwise, return NULL if the desired 486 * directory cannot be found. dir must already be complete. 487 */ 488static struct ref_dir *search_for_subdir(struct ref_dir *dir, 489const char*subdirname,size_t len, 490int mkdir) 491{ 492int entry_index =search_ref_dir(dir, subdirname, len); 493struct ref_entry *entry; 494if(entry_index == -1) { 495if(!mkdir) 496return NULL; 497/* 498 * Since dir is complete, the absence of a subdir 499 * means that the subdir really doesn't exist; 500 * therefore, create an empty record for it but mark 501 * the record complete. 502 */ 503 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 504add_entry_to_dir(dir, entry); 505}else{ 506 entry = dir->entries[entry_index]; 507} 508returnget_ref_dir(entry); 509} 510 511/* 512 * If refname is a reference name, find the ref_dir within the dir 513 * tree that should hold refname. If refname is a directory name 514 * (i.e., ends in '/'), then return that ref_dir itself. dir must 515 * represent the top-level directory and must already be complete. 516 * Sort ref_dirs and recurse into subdirectories as necessary. If 517 * mkdir is set, then create any missing directories; otherwise, 518 * return NULL if the desired directory cannot be found. 519 */ 520static struct ref_dir *find_containing_dir(struct ref_dir *dir, 521const char*refname,int mkdir) 522{ 523const char*slash; 524for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 525size_t dirnamelen = slash - refname +1; 526struct ref_dir *subdir; 527 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 528if(!subdir) { 529 dir = NULL; 530break; 531} 532 dir = subdir; 533} 534 535return dir; 536} 537 538/* 539 * Find the value entry with the given name in dir, sorting ref_dirs 540 * and recursing into subdirectories as necessary. If the name is not 541 * found or it corresponds to a directory entry, return NULL. 542 */ 543static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 544{ 545int entry_index; 546struct ref_entry *entry; 547 dir =find_containing_dir(dir, refname,0); 548if(!dir) 549return NULL; 550 entry_index =search_ref_dir(dir, refname,strlen(refname)); 551if(entry_index == -1) 552return NULL; 553 entry = dir->entries[entry_index]; 554return(entry->flag & REF_DIR) ? NULL : entry; 555} 556 557/* 558 * Remove the entry with the given name from dir, recursing into 559 * subdirectories as necessary. If refname is the name of a directory 560 * (i.e., ends with '/'), then remove the directory and its contents. 561 * If the removal was successful, return the number of entries 562 * remaining in the directory entry that contained the deleted entry. 563 * If the name was not found, return -1. Please note that this 564 * function only deletes the entry from the cache; it does not delete 565 * it from the filesystem or ensure that other cache entries (which 566 * might be symbolic references to the removed entry) are updated. 567 * Nor does it remove any containing dir entries that might be made 568 * empty by the removal. dir must represent the top-level directory 569 * and must already be complete. 570 */ 571static intremove_entry(struct ref_dir *dir,const char*refname) 572{ 573int refname_len =strlen(refname); 574int entry_index; 575struct ref_entry *entry; 576int is_dir = refname[refname_len -1] =='/'; 577if(is_dir) { 578/* 579 * refname represents a reference directory. Remove 580 * the trailing slash; otherwise we will get the 581 * directory *representing* refname rather than the 582 * one *containing* it. 583 */ 584char*dirname =xmemdupz(refname, refname_len -1); 585 dir =find_containing_dir(dir, dirname,0); 586free(dirname); 587}else{ 588 dir =find_containing_dir(dir, refname,0); 589} 590if(!dir) 591return-1; 592 entry_index =search_ref_dir(dir, refname, refname_len); 593if(entry_index == -1) 594return-1; 595 entry = dir->entries[entry_index]; 596 597memmove(&dir->entries[entry_index], 598&dir->entries[entry_index +1], 599(dir->nr - entry_index -1) *sizeof(*dir->entries) 600); 601 dir->nr--; 602if(dir->sorted > entry_index) 603 dir->sorted--; 604free_ref_entry(entry); 605return dir->nr; 606} 607 608/* 609 * Add a ref_entry to the ref_dir (unsorted), recursing into 610 * subdirectories as necessary. dir must represent the top-level 611 * directory. Return 0 on success. 612 */ 613static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 614{ 615 dir =find_containing_dir(dir, ref->name,1); 616if(!dir) 617return-1; 618add_entry_to_dir(dir, ref); 619return0; 620} 621 622/* 623 * Emit a warning and return true iff ref1 and ref2 have the same name 624 * and the same sha1. Die if they have the same name but different 625 * sha1s. 626 */ 627static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 628{ 629if(strcmp(ref1->name, ref2->name)) 630return0; 631 632/* Duplicate name; make sure that they don't conflict: */ 633 634if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 635/* This is impossible by construction */ 636die("Reference directory conflict:%s", ref1->name); 637 638if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 639die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 640 641warning("Duplicated ref:%s", ref1->name); 642return1; 643} 644 645/* 646 * Sort the entries in dir non-recursively (if they are not already 647 * sorted) and remove any duplicate entries. 648 */ 649static voidsort_ref_dir(struct ref_dir *dir) 650{ 651int i, j; 652struct ref_entry *last = NULL; 653 654/* 655 * This check also prevents passing a zero-length array to qsort(), 656 * which is a problem on some platforms. 657 */ 658if(dir->sorted == dir->nr) 659return; 660 661qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 662 663/* Remove any duplicates: */ 664for(i =0, j =0; j < dir->nr; j++) { 665struct ref_entry *entry = dir->entries[j]; 666if(last &&is_dup_ref(last, entry)) 667free_ref_entry(entry); 668else 669 last = dir->entries[i++] = entry; 670} 671 dir->sorted = dir->nr = i; 672} 673 674/* Include broken references in a do_for_each_ref*() iteration: */ 675#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 676 677/* 678 * Return true iff the reference described by entry can be resolved to 679 * an object in the database. Emit a warning if the referred-to 680 * object does not exist. 681 */ 682static intref_resolves_to_object(struct ref_entry *entry) 683{ 684if(entry->flag & REF_ISBROKEN) 685return0; 686if(!has_sha1_file(entry->u.value.sha1)) { 687error("%sdoes not point to a valid object!", entry->name); 688return0; 689} 690return1; 691} 692 693/* 694 * current_ref is a performance hack: when iterating over references 695 * using the for_each_ref*() functions, current_ref is set to the 696 * current reference's entry before calling the callback function. If 697 * the callback function calls peel_ref(), then peel_ref() first 698 * checks whether the reference to be peeled is the current reference 699 * (it usually is) and if so, returns that reference's peeled version 700 * if it is available. This avoids a refname lookup in a common case. 701 */ 702static struct ref_entry *current_ref; 703 704typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 705 706struct ref_entry_cb { 707const char*base; 708int trim; 709int flags; 710 each_ref_fn *fn; 711void*cb_data; 712}; 713 714/* 715 * Handle one reference in a do_for_each_ref*()-style iteration, 716 * calling an each_ref_fn for each entry. 717 */ 718static intdo_one_ref(struct ref_entry *entry,void*cb_data) 719{ 720struct ref_entry_cb *data = cb_data; 721struct ref_entry *old_current_ref; 722int retval; 723 724if(!starts_with(entry->name, data->base)) 725return0; 726 727if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 728!ref_resolves_to_object(entry)) 729return0; 730 731/* Store the old value, in case this is a recursive call: */ 732 old_current_ref = current_ref; 733 current_ref = entry; 734 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 735 entry->flag, data->cb_data); 736 current_ref = old_current_ref; 737return retval; 738} 739 740/* 741 * Call fn for each reference in dir that has index in the range 742 * offset <= index < dir->nr. Recurse into subdirectories that are in 743 * that index range, sorting them before iterating. This function 744 * does not sort dir itself; it should be sorted beforehand. fn is 745 * called for all references, including broken ones. 746 */ 747static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 748 each_ref_entry_fn fn,void*cb_data) 749{ 750int i; 751assert(dir->sorted == dir->nr); 752for(i = offset; i < dir->nr; i++) { 753struct ref_entry *entry = dir->entries[i]; 754int retval; 755if(entry->flag & REF_DIR) { 756struct ref_dir *subdir =get_ref_dir(entry); 757sort_ref_dir(subdir); 758 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 759}else{ 760 retval =fn(entry, cb_data); 761} 762if(retval) 763return retval; 764} 765return0; 766} 767 768/* 769 * Call fn for each reference in the union of dir1 and dir2, in order 770 * by refname. Recurse into subdirectories. If a value entry appears 771 * in both dir1 and dir2, then only process the version that is in 772 * dir2. The input dirs must already be sorted, but subdirs will be 773 * sorted as needed. fn is called for all references, including 774 * broken ones. 775 */ 776static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 777struct ref_dir *dir2, 778 each_ref_entry_fn fn,void*cb_data) 779{ 780int retval; 781int i1 =0, i2 =0; 782 783assert(dir1->sorted == dir1->nr); 784assert(dir2->sorted == dir2->nr); 785while(1) { 786struct ref_entry *e1, *e2; 787int cmp; 788if(i1 == dir1->nr) { 789returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 790} 791if(i2 == dir2->nr) { 792returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 793} 794 e1 = dir1->entries[i1]; 795 e2 = dir2->entries[i2]; 796 cmp =strcmp(e1->name, e2->name); 797if(cmp ==0) { 798if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 799/* Both are directories; descend them in parallel. */ 800struct ref_dir *subdir1 =get_ref_dir(e1); 801struct ref_dir *subdir2 =get_ref_dir(e2); 802sort_ref_dir(subdir1); 803sort_ref_dir(subdir2); 804 retval =do_for_each_entry_in_dirs( 805 subdir1, subdir2, fn, cb_data); 806 i1++; 807 i2++; 808}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 809/* Both are references; ignore the one from dir1. */ 810 retval =fn(e2, cb_data); 811 i1++; 812 i2++; 813}else{ 814die("conflict between reference and directory:%s", 815 e1->name); 816} 817}else{ 818struct ref_entry *e; 819if(cmp <0) { 820 e = e1; 821 i1++; 822}else{ 823 e = e2; 824 i2++; 825} 826if(e->flag & REF_DIR) { 827struct ref_dir *subdir =get_ref_dir(e); 828sort_ref_dir(subdir); 829 retval =do_for_each_entry_in_dir( 830 subdir,0, fn, cb_data); 831}else{ 832 retval =fn(e, cb_data); 833} 834} 835if(retval) 836return retval; 837} 838} 839 840/* 841 * Load all of the refs from the dir into our in-memory cache. The hard work 842 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 843 * through all of the sub-directories. We do not even need to care about 844 * sorting, as traversal order does not matter to us. 845 */ 846static voidprime_ref_dir(struct ref_dir *dir) 847{ 848int i; 849for(i =0; i < dir->nr; i++) { 850struct ref_entry *entry = dir->entries[i]; 851if(entry->flag & REF_DIR) 852prime_ref_dir(get_ref_dir(entry)); 853} 854} 855 856struct nonmatching_ref_data { 857const struct string_list *skip; 858const char*conflicting_refname; 859}; 860 861static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 862{ 863struct nonmatching_ref_data *data = vdata; 864 865if(data->skip &&string_list_has_string(data->skip, entry->name)) 866return0; 867 868 data->conflicting_refname = entry->name; 869return1; 870} 871 872/* 873 * Return 0 if a reference named refname could be created without 874 * conflicting with the name of an existing reference in dir. 875 * Otherwise, return a negative value and write an explanation to err. 876 * If extras is non-NULL, it is a list of additional refnames with 877 * which refname is not allowed to conflict. If skip is non-NULL, 878 * ignore potential conflicts with refs in skip (e.g., because they 879 * are scheduled for deletion in the same operation). Behavior is 880 * undefined if the same name is listed in both extras and skip. 881 * 882 * Two reference names conflict if one of them exactly matches the 883 * leading components of the other; e.g., "refs/foo/bar" conflicts 884 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 885 * "refs/foo/bar" or "refs/foo/barbados". 886 * 887 * extras and skip must be sorted. 888 */ 889static intverify_refname_available(const char*refname, 890const struct string_list *extras, 891const struct string_list *skip, 892struct ref_dir *dir, 893struct strbuf *err) 894{ 895const char*slash; 896int pos; 897struct strbuf dirname = STRBUF_INIT; 898int ret = -1; 899 900/* 901 * For the sake of comments in this function, suppose that 902 * refname is "refs/foo/bar". 903 */ 904 905assert(err); 906 907strbuf_grow(&dirname,strlen(refname) +1); 908for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 909/* Expand dirname to the new prefix, not including the trailing slash: */ 910strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 911 912/* 913 * We are still at a leading dir of the refname (e.g., 914 * "refs/foo"; if there is a reference with that name, 915 * it is a conflict, *unless* it is in skip. 916 */ 917if(dir) { 918 pos =search_ref_dir(dir, dirname.buf, dirname.len); 919if(pos >=0&& 920(!skip || !string_list_has_string(skip, dirname.buf))) { 921/* 922 * We found a reference whose name is 923 * a proper prefix of refname; e.g., 924 * "refs/foo", and is not in skip. 925 */ 926strbuf_addf(err,"'%s' exists; cannot create '%s'", 927 dirname.buf, refname); 928goto cleanup; 929} 930} 931 932if(extras &&string_list_has_string(extras, dirname.buf) && 933(!skip || !string_list_has_string(skip, dirname.buf))) { 934strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 935 refname, dirname.buf); 936goto cleanup; 937} 938 939/* 940 * Otherwise, we can try to continue our search with 941 * the next component. So try to look up the 942 * directory, e.g., "refs/foo/". If we come up empty, 943 * we know there is nothing under this whole prefix, 944 * but even in that case we still have to continue the 945 * search for conflicts with extras. 946 */ 947strbuf_addch(&dirname,'/'); 948if(dir) { 949 pos =search_ref_dir(dir, dirname.buf, dirname.len); 950if(pos <0) { 951/* 952 * There was no directory "refs/foo/", 953 * so there is nothing under this 954 * whole prefix. So there is no need 955 * to continue looking for conflicting 956 * references. But we need to continue 957 * looking for conflicting extras. 958 */ 959 dir = NULL; 960}else{ 961 dir =get_ref_dir(dir->entries[pos]); 962} 963} 964} 965 966/* 967 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 968 * There is no point in searching for a reference with that 969 * name, because a refname isn't considered to conflict with 970 * itself. But we still need to check for references whose 971 * names are in the "refs/foo/bar/" namespace, because they 972 * *do* conflict. 973 */ 974strbuf_addstr(&dirname, refname + dirname.len); 975strbuf_addch(&dirname,'/'); 976 977if(dir) { 978 pos =search_ref_dir(dir, dirname.buf, dirname.len); 979 980if(pos >=0) { 981/* 982 * We found a directory named "$refname/" 983 * (e.g., "refs/foo/bar/"). It is a problem 984 * iff it contains any ref that is not in 985 * "skip". 986 */ 987struct nonmatching_ref_data data; 988 989 data.skip = skip; 990 data.conflicting_refname = NULL; 991 dir =get_ref_dir(dir->entries[pos]); 992sort_ref_dir(dir); 993if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 994strbuf_addf(err,"'%s' exists; cannot create '%s'", 995 data.conflicting_refname, refname); 996goto cleanup; 997} 998} 999}10001001if(extras) {1002/*1003 * Check for entries in extras that start with1004 * "$refname/". We do that by looking for the place1005 * where "$refname/" would be inserted in extras. If1006 * there is an entry at that position that starts with1007 * "$refname/" and is not in skip, then we have a1008 * conflict.1009 */1010for(pos =string_list_find_insert_index(extras, dirname.buf,0);1011 pos < extras->nr; pos++) {1012const char*extra_refname = extras->items[pos].string;10131014if(!starts_with(extra_refname, dirname.buf))1015break;10161017if(!skip || !string_list_has_string(skip, extra_refname)) {1018strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1019 refname, extra_refname);1020goto cleanup;1021}1022}1023}10241025/* No conflicts were found */1026 ret =0;10271028cleanup:1029strbuf_release(&dirname);1030return ret;1031}10321033struct packed_ref_cache {1034struct ref_entry *root;10351036/*1037 * Count of references to the data structure in this instance,1038 * including the pointer from ref_cache::packed if any. The1039 * data will not be freed as long as the reference count is1040 * nonzero.1041 */1042unsigned int referrers;10431044/*1045 * Iff the packed-refs file associated with this instance is1046 * currently locked for writing, this points at the associated1047 * lock (which is owned by somebody else). The referrer count1048 * is also incremented when the file is locked and decremented1049 * when it is unlocked.1050 */1051struct lock_file *lock;10521053/* The metadata from when this packed-refs cache was read */1054struct stat_validity validity;1055};10561057/*1058 * Future: need to be in "struct repository"1059 * when doing a full libification.1060 */1061static struct ref_cache {1062struct ref_cache *next;1063struct ref_entry *loose;1064struct packed_ref_cache *packed;1065/*1066 * The submodule name, or "" for the main repo. We allocate1067 * length 1 rather than FLEX_ARRAY so that the main ref_cache1068 * is initialized correctly.1069 */1070char name[1];1071} ref_cache, *submodule_ref_caches;10721073/* Lock used for the main packed-refs file: */1074static struct lock_file packlock;10751076/*1077 * Increment the reference count of *packed_refs.1078 */1079static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1080{1081 packed_refs->referrers++;1082}10831084/*1085 * Decrease the reference count of *packed_refs. If it goes to zero,1086 * free *packed_refs and return true; otherwise return false.1087 */1088static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1089{1090if(!--packed_refs->referrers) {1091free_ref_entry(packed_refs->root);1092stat_validity_clear(&packed_refs->validity);1093free(packed_refs);1094return1;1095}else{1096return0;1097}1098}10991100static voidclear_packed_ref_cache(struct ref_cache *refs)1101{1102if(refs->packed) {1103struct packed_ref_cache *packed_refs = refs->packed;11041105if(packed_refs->lock)1106die("internal error: packed-ref cache cleared while locked");1107 refs->packed = NULL;1108release_packed_ref_cache(packed_refs);1109}1110}11111112static voidclear_loose_ref_cache(struct ref_cache *refs)1113{1114if(refs->loose) {1115free_ref_entry(refs->loose);1116 refs->loose = NULL;1117}1118}11191120static struct ref_cache *create_ref_cache(const char*submodule)1121{1122int len;1123struct ref_cache *refs;1124if(!submodule)1125 submodule ="";1126 len =strlen(submodule) +1;1127 refs =xcalloc(1,sizeof(struct ref_cache) + len);1128memcpy(refs->name, submodule, len);1129return refs;1130}11311132/*1133 * Return a pointer to a ref_cache for the specified submodule. For1134 * the main repository, use submodule==NULL. The returned structure1135 * will be allocated and initialized but not necessarily populated; it1136 * should not be freed.1137 */1138static struct ref_cache *get_ref_cache(const char*submodule)1139{1140struct ref_cache *refs;11411142if(!submodule || !*submodule)1143return&ref_cache;11441145for(refs = submodule_ref_caches; refs; refs = refs->next)1146if(!strcmp(submodule, refs->name))1147return refs;11481149 refs =create_ref_cache(submodule);1150 refs->next = submodule_ref_caches;1151 submodule_ref_caches = refs;1152return refs;1153}11541155/* The length of a peeled reference line in packed-refs, including EOL: */1156#define PEELED_LINE_LENGTH 4211571158/*1159 * The packed-refs header line that we write out. Perhaps other1160 * traits will be added later. The trailing space is required.1161 */1162static const char PACKED_REFS_HEADER[] =1163"# pack-refs with: peeled fully-peeled\n";11641165/*1166 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1167 * Return a pointer to the refname within the line (null-terminated),1168 * or NULL if there was a problem.1169 */1170static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1171{1172const char*ref;11731174/*1175 * 42: the answer to everything.1176 *1177 * In this case, it happens to be the answer to1178 * 40 (length of sha1 hex representation)1179 * +1 (space in between hex and name)1180 * +1 (newline at the end of the line)1181 */1182if(line->len <=42)1183return NULL;11841185if(get_sha1_hex(line->buf, sha1) <0)1186return NULL;1187if(!isspace(line->buf[40]))1188return NULL;11891190 ref = line->buf +41;1191if(isspace(*ref))1192return NULL;11931194if(line->buf[line->len -1] !='\n')1195return NULL;1196 line->buf[--line->len] =0;11971198return ref;1199}12001201/*1202 * Read f, which is a packed-refs file, into dir.1203 *1204 * A comment line of the form "# pack-refs with: " may contain zero or1205 * more traits. We interpret the traits as follows:1206 *1207 * No traits:1208 *1209 * Probably no references are peeled. But if the file contains a1210 * peeled value for a reference, we will use it.1211 *1212 * peeled:1213 *1214 * References under "refs/tags/", if they *can* be peeled, *are*1215 * peeled in this file. References outside of "refs/tags/" are1216 * probably not peeled even if they could have been, but if we find1217 * a peeled value for such a reference we will use it.1218 *1219 * fully-peeled:1220 *1221 * All references in the file that can be peeled are peeled.1222 * Inversely (and this is more important), any references in the1223 * file for which no peeled value is recorded is not peelable. This1224 * trait should typically be written alongside "peeled" for1225 * compatibility with older clients, but we do not require it1226 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1227 */1228static voidread_packed_refs(FILE*f,struct ref_dir *dir)1229{1230struct ref_entry *last = NULL;1231struct strbuf line = STRBUF_INIT;1232enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12331234while(strbuf_getwholeline(&line, f,'\n') != EOF) {1235unsigned char sha1[20];1236const char*refname;1237const char*traits;12381239if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1240if(strstr(traits," fully-peeled "))1241 peeled = PEELED_FULLY;1242else if(strstr(traits," peeled "))1243 peeled = PEELED_TAGS;1244/* perhaps other traits later as well */1245continue;1246}12471248 refname =parse_ref_line(&line, sha1);1249if(refname) {1250int flag = REF_ISPACKED;12511252if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1253hashclr(sha1);1254 flag |= REF_BAD_NAME | REF_ISBROKEN;1255}1256 last =create_ref_entry(refname, sha1, flag,0);1257if(peeled == PEELED_FULLY ||1258(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1259 last->flag |= REF_KNOWS_PEELED;1260add_ref(dir, last);1261continue;1262}1263if(last &&1264 line.buf[0] =='^'&&1265 line.len == PEELED_LINE_LENGTH &&1266 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1267!get_sha1_hex(line.buf +1, sha1)) {1268hashcpy(last->u.value.peeled, sha1);1269/*1270 * Regardless of what the file header said,1271 * we definitely know the value of *this*1272 * reference:1273 */1274 last->flag |= REF_KNOWS_PEELED;1275}1276}12771278strbuf_release(&line);1279}12801281/*1282 * Get the packed_ref_cache for the specified ref_cache, creating it1283 * if necessary.1284 */1285static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1286{1287const char*packed_refs_file;12881289if(*refs->name)1290 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1291else1292 packed_refs_file =git_path("packed-refs");12931294if(refs->packed &&1295!stat_validity_check(&refs->packed->validity, packed_refs_file))1296clear_packed_ref_cache(refs);12971298if(!refs->packed) {1299FILE*f;13001301 refs->packed =xcalloc(1,sizeof(*refs->packed));1302acquire_packed_ref_cache(refs->packed);1303 refs->packed->root =create_dir_entry(refs,"",0,0);1304 f =fopen(packed_refs_file,"r");1305if(f) {1306stat_validity_update(&refs->packed->validity,fileno(f));1307read_packed_refs(f,get_ref_dir(refs->packed->root));1308fclose(f);1309}1310}1311return refs->packed;1312}13131314static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1315{1316returnget_ref_dir(packed_ref_cache->root);1317}13181319static struct ref_dir *get_packed_refs(struct ref_cache *refs)1320{1321returnget_packed_ref_dir(get_packed_ref_cache(refs));1322}13231324voidadd_packed_ref(const char*refname,const unsigned char*sha1)1325{1326struct packed_ref_cache *packed_ref_cache =1327get_packed_ref_cache(&ref_cache);13281329if(!packed_ref_cache->lock)1330die("internal error: packed refs not locked");1331add_ref(get_packed_ref_dir(packed_ref_cache),1332create_ref_entry(refname, sha1, REF_ISPACKED,1));1333}13341335/*1336 * Read the loose references from the namespace dirname into dir1337 * (without recursing). dirname must end with '/'. dir must be the1338 * directory entry corresponding to dirname.1339 */1340static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1341{1342struct ref_cache *refs = dir->ref_cache;1343DIR*d;1344const char*path;1345struct dirent *de;1346int dirnamelen =strlen(dirname);1347struct strbuf refname;13481349if(*refs->name)1350 path =git_path_submodule(refs->name,"%s", dirname);1351else1352 path =git_path("%s", dirname);13531354 d =opendir(path);1355if(!d)1356return;13571358strbuf_init(&refname, dirnamelen +257);1359strbuf_add(&refname, dirname, dirnamelen);13601361while((de =readdir(d)) != NULL) {1362unsigned char sha1[20];1363struct stat st;1364int flag;1365const char*refdir;13661367if(de->d_name[0] =='.')1368continue;1369if(ends_with(de->d_name,".lock"))1370continue;1371strbuf_addstr(&refname, de->d_name);1372 refdir = *refs->name1373?git_path_submodule(refs->name,"%s", refname.buf)1374:git_path("%s", refname.buf);1375if(stat(refdir, &st) <0) {1376;/* silently ignore */1377}else if(S_ISDIR(st.st_mode)) {1378strbuf_addch(&refname,'/');1379add_entry_to_dir(dir,1380create_dir_entry(refs, refname.buf,1381 refname.len,1));1382}else{1383if(*refs->name) {1384hashclr(sha1);1385 flag =0;1386if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1387hashclr(sha1);1388 flag |= REF_ISBROKEN;1389}1390}else if(read_ref_full(refname.buf,1391 RESOLVE_REF_READING,1392 sha1, &flag)) {1393hashclr(sha1);1394 flag |= REF_ISBROKEN;1395}1396if(check_refname_format(refname.buf,1397 REFNAME_ALLOW_ONELEVEL)) {1398hashclr(sha1);1399 flag |= REF_BAD_NAME | REF_ISBROKEN;1400}1401add_entry_to_dir(dir,1402create_ref_entry(refname.buf, sha1, flag,0));1403}1404strbuf_setlen(&refname, dirnamelen);1405}1406strbuf_release(&refname);1407closedir(d);1408}14091410static struct ref_dir *get_loose_refs(struct ref_cache *refs)1411{1412if(!refs->loose) {1413/*1414 * Mark the top-level directory complete because we1415 * are about to read the only subdirectory that can1416 * hold references:1417 */1418 refs->loose =create_dir_entry(refs,"",0,0);1419/*1420 * Create an incomplete entry for "refs/":1421 */1422add_entry_to_dir(get_ref_dir(refs->loose),1423create_dir_entry(refs,"refs/",5,1));1424}1425returnget_ref_dir(refs->loose);1426}14271428/* We allow "recursive" symbolic refs. Only within reason, though */1429#define MAXDEPTH 51430#define MAXREFLEN (1024)14311432/*1433 * Called by resolve_gitlink_ref_recursive() after it failed to read1434 * from the loose refs in ref_cache refs. Find <refname> in the1435 * packed-refs file for the submodule.1436 */1437static intresolve_gitlink_packed_ref(struct ref_cache *refs,1438const char*refname,unsigned char*sha1)1439{1440struct ref_entry *ref;1441struct ref_dir *dir =get_packed_refs(refs);14421443 ref =find_ref(dir, refname);1444if(ref == NULL)1445return-1;14461447hashcpy(sha1, ref->u.value.sha1);1448return0;1449}14501451static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1452const char*refname,unsigned char*sha1,1453int recursion)1454{1455int fd, len;1456char buffer[128], *p;1457char*path;14581459if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1460return-1;1461 path = *refs->name1462?git_path_submodule(refs->name,"%s", refname)1463:git_path("%s", refname);1464 fd =open(path, O_RDONLY);1465if(fd <0)1466returnresolve_gitlink_packed_ref(refs, refname, sha1);14671468 len =read(fd, buffer,sizeof(buffer)-1);1469close(fd);1470if(len <0)1471return-1;1472while(len &&isspace(buffer[len-1]))1473 len--;1474 buffer[len] =0;14751476/* Was it a detached head or an old-fashioned symlink? */1477if(!get_sha1_hex(buffer, sha1))1478return0;14791480/* Symref? */1481if(strncmp(buffer,"ref:",4))1482return-1;1483 p = buffer +4;1484while(isspace(*p))1485 p++;14861487returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1488}14891490intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1491{1492int len =strlen(path), retval;1493char*submodule;1494struct ref_cache *refs;14951496while(len && path[len-1] =='/')1497 len--;1498if(!len)1499return-1;1500 submodule =xstrndup(path, len);1501 refs =get_ref_cache(submodule);1502free(submodule);15031504 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1505return retval;1506}15071508/*1509 * Return the ref_entry for the given refname from the packed1510 * references. If it does not exist, return NULL.1511 */1512static struct ref_entry *get_packed_ref(const char*refname)1513{1514returnfind_ref(get_packed_refs(&ref_cache), refname);1515}15161517/*1518 * A loose ref file doesn't exist; check for a packed ref. The1519 * options are forwarded from resolve_safe_unsafe().1520 */1521static intresolve_missing_loose_ref(const char*refname,1522int resolve_flags,1523unsigned char*sha1,1524int*flags)1525{1526struct ref_entry *entry;15271528/*1529 * The loose reference file does not exist; check for a packed1530 * reference.1531 */1532 entry =get_packed_ref(refname);1533if(entry) {1534hashcpy(sha1, entry->u.value.sha1);1535if(flags)1536*flags |= REF_ISPACKED;1537return0;1538}1539/* The reference is not a packed reference, either. */1540if(resolve_flags & RESOLVE_REF_READING) {1541 errno = ENOENT;1542return-1;1543}else{1544hashclr(sha1);1545return0;1546}1547}15481549/* This function needs to return a meaningful errno on failure */1550const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1551{1552int depth = MAXDEPTH;1553 ssize_t len;1554char buffer[256];1555static char refname_buffer[256];1556int bad_name =0;15571558if(flags)1559*flags =0;15601561if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1562if(flags)1563*flags |= REF_BAD_NAME;15641565if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1566!refname_is_safe(refname)) {1567 errno = EINVAL;1568return NULL;1569}1570/*1571 * dwim_ref() uses REF_ISBROKEN to distinguish between1572 * missing refs and refs that were present but invalid,1573 * to complain about the latter to stderr.1574 *1575 * We don't know whether the ref exists, so don't set1576 * REF_ISBROKEN yet.1577 */1578 bad_name =1;1579}1580for(;;) {1581char path[PATH_MAX];1582struct stat st;1583char*buf;1584int fd;15851586if(--depth <0) {1587 errno = ELOOP;1588return NULL;1589}15901591git_snpath(path,sizeof(path),"%s", refname);15921593/*1594 * We might have to loop back here to avoid a race1595 * condition: first we lstat() the file, then we try1596 * to read it as a link or as a file. But if somebody1597 * changes the type of the file (file <-> directory1598 * <-> symlink) between the lstat() and reading, then1599 * we don't want to report that as an error but rather1600 * try again starting with the lstat().1601 */1602 stat_ref:1603if(lstat(path, &st) <0) {1604if(errno != ENOENT)1605return NULL;1606if(resolve_missing_loose_ref(refname, resolve_flags,1607 sha1, flags))1608return NULL;1609if(bad_name) {1610hashclr(sha1);1611if(flags)1612*flags |= REF_ISBROKEN;1613}1614return refname;1615}16161617/* Follow "normalized" - ie "refs/.." symlinks by hand */1618if(S_ISLNK(st.st_mode)) {1619 len =readlink(path, buffer,sizeof(buffer)-1);1620if(len <0) {1621if(errno == ENOENT || errno == EINVAL)1622/* inconsistent with lstat; retry */1623goto stat_ref;1624else1625return NULL;1626}1627 buffer[len] =0;1628if(starts_with(buffer,"refs/") &&1629!check_refname_format(buffer,0)) {1630strcpy(refname_buffer, buffer);1631 refname = refname_buffer;1632if(flags)1633*flags |= REF_ISSYMREF;1634if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1635hashclr(sha1);1636return refname;1637}1638continue;1639}1640}16411642/* Is it a directory? */1643if(S_ISDIR(st.st_mode)) {1644 errno = EISDIR;1645return NULL;1646}16471648/*1649 * Anything else, just open it and try to use it as1650 * a ref1651 */1652 fd =open(path, O_RDONLY);1653if(fd <0) {1654if(errno == ENOENT)1655/* inconsistent with lstat; retry */1656goto stat_ref;1657else1658return NULL;1659}1660 len =read_in_full(fd, buffer,sizeof(buffer)-1);1661if(len <0) {1662int save_errno = errno;1663close(fd);1664 errno = save_errno;1665return NULL;1666}1667close(fd);1668while(len &&isspace(buffer[len-1]))1669 len--;1670 buffer[len] ='\0';16711672/*1673 * Is it a symbolic ref?1674 */1675if(!starts_with(buffer,"ref:")) {1676/*1677 * Please note that FETCH_HEAD has a second1678 * line containing other data.1679 */1680if(get_sha1_hex(buffer, sha1) ||1681(buffer[40] !='\0'&& !isspace(buffer[40]))) {1682if(flags)1683*flags |= REF_ISBROKEN;1684 errno = EINVAL;1685return NULL;1686}1687if(bad_name) {1688hashclr(sha1);1689if(flags)1690*flags |= REF_ISBROKEN;1691}1692return refname;1693}1694if(flags)1695*flags |= REF_ISSYMREF;1696 buf = buffer +4;1697while(isspace(*buf))1698 buf++;1699 refname =strcpy(refname_buffer, buf);1700if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1701hashclr(sha1);1702return refname;1703}1704if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1705if(flags)1706*flags |= REF_ISBROKEN;17071708if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1709!refname_is_safe(buf)) {1710 errno = EINVAL;1711return NULL;1712}1713 bad_name =1;1714}1715}1716}17171718char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1719{1720returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1721}17221723/* The argument to filter_refs */1724struct ref_filter {1725const char*pattern;1726 each_ref_fn *fn;1727void*cb_data;1728};17291730intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1731{1732if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1733return0;1734return-1;1735}17361737intread_ref(const char*refname,unsigned char*sha1)1738{1739returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1740}17411742intref_exists(const char*refname)1743{1744unsigned char sha1[20];1745return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1746}17471748static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1749void*data)1750{1751struct ref_filter *filter = (struct ref_filter *)data;1752if(wildmatch(filter->pattern, refname,0, NULL))1753return0;1754return filter->fn(refname, sha1, flags, filter->cb_data);1755}17561757enum peel_status {1758/* object was peeled successfully: */1759 PEEL_PEELED =0,17601761/*1762 * object cannot be peeled because the named object (or an1763 * object referred to by a tag in the peel chain), does not1764 * exist.1765 */1766 PEEL_INVALID = -1,17671768/* object cannot be peeled because it is not a tag: */1769 PEEL_NON_TAG = -2,17701771/* ref_entry contains no peeled value because it is a symref: */1772 PEEL_IS_SYMREF = -3,17731774/*1775 * ref_entry cannot be peeled because it is broken (i.e., the1776 * symbolic reference cannot even be resolved to an object1777 * name):1778 */1779 PEEL_BROKEN = -41780};17811782/*1783 * Peel the named object; i.e., if the object is a tag, resolve the1784 * tag recursively until a non-tag is found. If successful, store the1785 * result to sha1 and return PEEL_PEELED. If the object is not a tag1786 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1787 * and leave sha1 unchanged.1788 */1789static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1790{1791struct object *o =lookup_unknown_object(name);17921793if(o->type == OBJ_NONE) {1794int type =sha1_object_info(name, NULL);1795if(type <0|| !object_as_type(o, type,0))1796return PEEL_INVALID;1797}17981799if(o->type != OBJ_TAG)1800return PEEL_NON_TAG;18011802 o =deref_tag_noverify(o);1803if(!o)1804return PEEL_INVALID;18051806hashcpy(sha1, o->sha1);1807return PEEL_PEELED;1808}18091810/*1811 * Peel the entry (if possible) and return its new peel_status. If1812 * repeel is true, re-peel the entry even if there is an old peeled1813 * value that is already stored in it.1814 *1815 * It is OK to call this function with a packed reference entry that1816 * might be stale and might even refer to an object that has since1817 * been garbage-collected. In such a case, if the entry has1818 * REF_KNOWS_PEELED then leave the status unchanged and return1819 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1820 */1821static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1822{1823enum peel_status status;18241825if(entry->flag & REF_KNOWS_PEELED) {1826if(repeel) {1827 entry->flag &= ~REF_KNOWS_PEELED;1828hashclr(entry->u.value.peeled);1829}else{1830returnis_null_sha1(entry->u.value.peeled) ?1831 PEEL_NON_TAG : PEEL_PEELED;1832}1833}1834if(entry->flag & REF_ISBROKEN)1835return PEEL_BROKEN;1836if(entry->flag & REF_ISSYMREF)1837return PEEL_IS_SYMREF;18381839 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1840if(status == PEEL_PEELED || status == PEEL_NON_TAG)1841 entry->flag |= REF_KNOWS_PEELED;1842return status;1843}18441845intpeel_ref(const char*refname,unsigned char*sha1)1846{1847int flag;1848unsigned char base[20];18491850if(current_ref && (current_ref->name == refname1851|| !strcmp(current_ref->name, refname))) {1852if(peel_entry(current_ref,0))1853return-1;1854hashcpy(sha1, current_ref->u.value.peeled);1855return0;1856}18571858if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1859return-1;18601861/*1862 * If the reference is packed, read its ref_entry from the1863 * cache in the hope that we already know its peeled value.1864 * We only try this optimization on packed references because1865 * (a) forcing the filling of the loose reference cache could1866 * be expensive and (b) loose references anyway usually do not1867 * have REF_KNOWS_PEELED.1868 */1869if(flag & REF_ISPACKED) {1870struct ref_entry *r =get_packed_ref(refname);1871if(r) {1872if(peel_entry(r,0))1873return-1;1874hashcpy(sha1, r->u.value.peeled);1875return0;1876}1877}18781879returnpeel_object(base, sha1);1880}18811882struct warn_if_dangling_data {1883FILE*fp;1884const char*refname;1885const struct string_list *refnames;1886const char*msg_fmt;1887};18881889static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1890int flags,void*cb_data)1891{1892struct warn_if_dangling_data *d = cb_data;1893const char*resolves_to;1894unsigned char junk[20];18951896if(!(flags & REF_ISSYMREF))1897return0;18981899 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1900if(!resolves_to1901|| (d->refname1902?strcmp(resolves_to, d->refname)1903: !string_list_has_string(d->refnames, resolves_to))) {1904return0;1905}19061907fprintf(d->fp, d->msg_fmt, refname);1908fputc('\n', d->fp);1909return0;1910}19111912voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1913{1914struct warn_if_dangling_data data;19151916 data.fp = fp;1917 data.refname = refname;1918 data.refnames = NULL;1919 data.msg_fmt = msg_fmt;1920for_each_rawref(warn_if_dangling_symref, &data);1921}19221923voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1924{1925struct warn_if_dangling_data data;19261927 data.fp = fp;1928 data.refname = NULL;1929 data.refnames = refnames;1930 data.msg_fmt = msg_fmt;1931for_each_rawref(warn_if_dangling_symref, &data);1932}19331934/*1935 * Call fn for each reference in the specified ref_cache, omitting1936 * references not in the containing_dir of base. fn is called for all1937 * references, including broken ones. If fn ever returns a non-zero1938 * value, stop the iteration and return that value; otherwise, return1939 * 0.1940 */1941static intdo_for_each_entry(struct ref_cache *refs,const char*base,1942 each_ref_entry_fn fn,void*cb_data)1943{1944struct packed_ref_cache *packed_ref_cache;1945struct ref_dir *loose_dir;1946struct ref_dir *packed_dir;1947int retval =0;19481949/*1950 * We must make sure that all loose refs are read before accessing the1951 * packed-refs file; this avoids a race condition in which loose refs1952 * are migrated to the packed-refs file by a simultaneous process, but1953 * our in-memory view is from before the migration. get_packed_ref_cache()1954 * takes care of making sure our view is up to date with what is on1955 * disk.1956 */1957 loose_dir =get_loose_refs(refs);1958if(base && *base) {1959 loose_dir =find_containing_dir(loose_dir, base,0);1960}1961if(loose_dir)1962prime_ref_dir(loose_dir);19631964 packed_ref_cache =get_packed_ref_cache(refs);1965acquire_packed_ref_cache(packed_ref_cache);1966 packed_dir =get_packed_ref_dir(packed_ref_cache);1967if(base && *base) {1968 packed_dir =find_containing_dir(packed_dir, base,0);1969}19701971if(packed_dir && loose_dir) {1972sort_ref_dir(packed_dir);1973sort_ref_dir(loose_dir);1974 retval =do_for_each_entry_in_dirs(1975 packed_dir, loose_dir, fn, cb_data);1976}else if(packed_dir) {1977sort_ref_dir(packed_dir);1978 retval =do_for_each_entry_in_dir(1979 packed_dir,0, fn, cb_data);1980}else if(loose_dir) {1981sort_ref_dir(loose_dir);1982 retval =do_for_each_entry_in_dir(1983 loose_dir,0, fn, cb_data);1984}19851986release_packed_ref_cache(packed_ref_cache);1987return retval;1988}19891990/*1991 * Call fn for each reference in the specified ref_cache for which the1992 * refname begins with base. If trim is non-zero, then trim that many1993 * characters off the beginning of each refname before passing the1994 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1995 * broken references in the iteration. If fn ever returns a non-zero1996 * value, stop the iteration and return that value; otherwise, return1997 * 0.1998 */1999static intdo_for_each_ref(struct ref_cache *refs,const char*base,2000 each_ref_fn fn,int trim,int flags,void*cb_data)2001{2002struct ref_entry_cb data;2003 data.base = base;2004 data.trim = trim;2005 data.flags = flags;2006 data.fn = fn;2007 data.cb_data = cb_data;20082009if(ref_paranoia <0)2010 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2011if(ref_paranoia)2012 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20132014returndo_for_each_entry(refs, base, do_one_ref, &data);2015}20162017static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2018{2019unsigned char sha1[20];2020int flag;20212022if(submodule) {2023if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)2024returnfn("HEAD", sha1,0, cb_data);20252026return0;2027}20282029if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))2030returnfn("HEAD", sha1, flag, cb_data);20312032return0;2033}20342035inthead_ref(each_ref_fn fn,void*cb_data)2036{2037returndo_head_ref(NULL, fn, cb_data);2038}20392040inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2041{2042returndo_head_ref(submodule, fn, cb_data);2043}20442045intfor_each_ref(each_ref_fn fn,void*cb_data)2046{2047returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2048}20492050intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2051{2052returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2053}20542055intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2056{2057returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2058}20592060intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2061 each_ref_fn fn,void*cb_data)2062{2063returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2064}20652066intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2067{2068returnfor_each_ref_in("refs/tags/", fn, cb_data);2069}20702071intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2072{2073returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2074}20752076intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2077{2078returnfor_each_ref_in("refs/heads/", fn, cb_data);2079}20802081intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2082{2083returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2084}20852086intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2087{2088returnfor_each_ref_in("refs/remotes/", fn, cb_data);2089}20902091intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2092{2093returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2094}20952096intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2097{2098returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2099}21002101inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2102{2103struct strbuf buf = STRBUF_INIT;2104int ret =0;2105unsigned char sha1[20];2106int flag;21072108strbuf_addf(&buf,"%sHEAD",get_git_namespace());2109if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2110 ret =fn(buf.buf, sha1, flag, cb_data);2111strbuf_release(&buf);21122113return ret;2114}21152116intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2117{2118struct strbuf buf = STRBUF_INIT;2119int ret;2120strbuf_addf(&buf,"%srefs/",get_git_namespace());2121 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2122strbuf_release(&buf);2123return ret;2124}21252126intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2127const char*prefix,void*cb_data)2128{2129struct strbuf real_pattern = STRBUF_INIT;2130struct ref_filter filter;2131int ret;21322133if(!prefix && !starts_with(pattern,"refs/"))2134strbuf_addstr(&real_pattern,"refs/");2135else if(prefix)2136strbuf_addstr(&real_pattern, prefix);2137strbuf_addstr(&real_pattern, pattern);21382139if(!has_glob_specials(pattern)) {2140/* Append implied '/' '*' if not present. */2141if(real_pattern.buf[real_pattern.len -1] !='/')2142strbuf_addch(&real_pattern,'/');2143/* No need to check for '*', there is none. */2144strbuf_addch(&real_pattern,'*');2145}21462147 filter.pattern = real_pattern.buf;2148 filter.fn = fn;2149 filter.cb_data = cb_data;2150 ret =for_each_ref(filter_refs, &filter);21512152strbuf_release(&real_pattern);2153return ret;2154}21552156intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2157{2158returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2159}21602161intfor_each_rawref(each_ref_fn fn,void*cb_data)2162{2163returndo_for_each_ref(&ref_cache,"", fn,0,2164 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2165}21662167const char*prettify_refname(const char*name)2168{2169return name + (2170starts_with(name,"refs/heads/") ?11:2171starts_with(name,"refs/tags/") ?10:2172starts_with(name,"refs/remotes/") ?13:21730);2174}21752176static const char*ref_rev_parse_rules[] = {2177"%.*s",2178"refs/%.*s",2179"refs/tags/%.*s",2180"refs/heads/%.*s",2181"refs/remotes/%.*s",2182"refs/remotes/%.*s/HEAD",2183 NULL2184};21852186intrefname_match(const char*abbrev_name,const char*full_name)2187{2188const char**p;2189const int abbrev_name_len =strlen(abbrev_name);21902191for(p = ref_rev_parse_rules; *p; p++) {2192if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2193return1;2194}2195}21962197return0;2198}21992200static voidunlock_ref(struct ref_lock *lock)2201{2202/* Do not free lock->lk -- atexit() still looks at them */2203if(lock->lk)2204rollback_lock_file(lock->lk);2205free(lock->ref_name);2206free(lock->orig_ref_name);2207free(lock);2208}22092210/* This function should make sure errno is meaningful on error */2211static struct ref_lock *verify_lock(struct ref_lock *lock,2212const unsigned char*old_sha1,int mustexist)2213{2214if(read_ref_full(lock->ref_name,2215 mustexist ? RESOLVE_REF_READING :0,2216 lock->old_sha1, NULL)) {2217int save_errno = errno;2218error("Can't verify ref%s", lock->ref_name);2219unlock_ref(lock);2220 errno = save_errno;2221return NULL;2222}2223if(hashcmp(lock->old_sha1, old_sha1)) {2224error("Ref%sis at%sbut expected%s", lock->ref_name,2225sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2226unlock_ref(lock);2227 errno = EBUSY;2228return NULL;2229}2230return lock;2231}22322233static intremove_empty_directories(const char*file)2234{2235/* we want to create a file but there is a directory there;2236 * if that is an empty directory (or a directory that contains2237 * only empty directories), remove them.2238 */2239struct strbuf path;2240int result, save_errno;22412242strbuf_init(&path,20);2243strbuf_addstr(&path, file);22442245 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2246 save_errno = errno;22472248strbuf_release(&path);2249 errno = save_errno;22502251return result;2252}22532254/*2255 * *string and *len will only be substituted, and *string returned (for2256 * later free()ing) if the string passed in is a magic short-hand form2257 * to name a branch.2258 */2259static char*substitute_branch_name(const char**string,int*len)2260{2261struct strbuf buf = STRBUF_INIT;2262int ret =interpret_branch_name(*string, *len, &buf);22632264if(ret == *len) {2265size_t size;2266*string =strbuf_detach(&buf, &size);2267*len = size;2268return(char*)*string;2269}22702271return NULL;2272}22732274intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2275{2276char*last_branch =substitute_branch_name(&str, &len);2277const char**p, *r;2278int refs_found =0;22792280*ref = NULL;2281for(p = ref_rev_parse_rules; *p; p++) {2282char fullref[PATH_MAX];2283unsigned char sha1_from_ref[20];2284unsigned char*this_result;2285int flag;22862287 this_result = refs_found ? sha1_from_ref : sha1;2288mksnpath(fullref,sizeof(fullref), *p, len, str);2289 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2290 this_result, &flag);2291if(r) {2292if(!refs_found++)2293*ref =xstrdup(r);2294if(!warn_ambiguous_refs)2295break;2296}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2297warning("ignoring dangling symref%s.", fullref);2298}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2299warning("ignoring broken ref%s.", fullref);2300}2301}2302free(last_branch);2303return refs_found;2304}23052306intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2307{2308char*last_branch =substitute_branch_name(&str, &len);2309const char**p;2310int logs_found =0;23112312*log = NULL;2313for(p = ref_rev_parse_rules; *p; p++) {2314unsigned char hash[20];2315char path[PATH_MAX];2316const char*ref, *it;23172318mksnpath(path,sizeof(path), *p, len, str);2319 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2320 hash, NULL);2321if(!ref)2322continue;2323if(reflog_exists(path))2324 it = path;2325else if(strcmp(ref, path) &&reflog_exists(ref))2326 it = ref;2327else2328continue;2329if(!logs_found++) {2330*log =xstrdup(it);2331hashcpy(sha1, hash);2332}2333if(!warn_ambiguous_refs)2334break;2335}2336free(last_branch);2337return logs_found;2338}23392340/*2341 * Locks a ref returning the lock on success and NULL on failure.2342 * On failure errno is set to something meaningful.2343 */2344static struct ref_lock *lock_ref_sha1_basic(const char*refname,2345const unsigned char*old_sha1,2346const struct string_list *extras,2347const struct string_list *skip,2348unsigned int flags,int*type_p,2349struct strbuf *err)2350{2351char*ref_file;2352const char*orig_refname = refname;2353struct ref_lock *lock;2354int last_errno =0;2355int type, lflags;2356int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2357int resolve_flags =0;2358int attempts_remaining =3;23592360assert(err);23612362 lock =xcalloc(1,sizeof(struct ref_lock));2363 lock->lock_fd = -1;23642365if(mustexist)2366 resolve_flags |= RESOLVE_REF_READING;2367if(flags & REF_DELETING) {2368 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2369if(flags & REF_NODEREF)2370 resolve_flags |= RESOLVE_REF_NO_RECURSE;2371}23722373 refname =resolve_ref_unsafe(refname, resolve_flags,2374 lock->old_sha1, &type);2375if(!refname && errno == EISDIR) {2376/* we are trying to lock foo but we used to2377 * have foo/bar which now does not exist;2378 * it is normal for the empty directory 'foo'2379 * to remain.2380 */2381 ref_file =git_path("%s", orig_refname);2382if(remove_empty_directories(ref_file)) {2383 last_errno = errno;23842385if(!verify_refname_available(orig_refname, extras, skip,2386get_loose_refs(&ref_cache), err))2387strbuf_addf(err,"there are still refs under '%s'",2388 orig_refname);23892390goto error_return;2391}2392 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2393 lock->old_sha1, &type);2394}2395if(type_p)2396*type_p = type;2397if(!refname) {2398 last_errno = errno;2399if(last_errno != ENOTDIR ||2400!verify_refname_available(orig_refname, extras, skip,2401get_loose_refs(&ref_cache), err))2402strbuf_addf(err,"unable to resolve reference%s:%s",2403 orig_refname,strerror(last_errno));24042405goto error_return;2406}2407/*2408 * If the ref did not exist and we are creating it, make sure2409 * there is no existing packed ref whose name begins with our2410 * refname, nor a packed ref whose name is a proper prefix of2411 * our refname.2412 */2413if(is_null_sha1(lock->old_sha1) &&2414verify_refname_available(refname, extras, skip,2415get_packed_refs(&ref_cache), err)) {2416 last_errno = ENOTDIR;2417goto error_return;2418}24192420 lock->lk =xcalloc(1,sizeof(struct lock_file));24212422 lflags =0;2423if(flags & REF_NODEREF) {2424 refname = orig_refname;2425 lflags |= LOCK_NO_DEREF;2426}2427 lock->ref_name =xstrdup(refname);2428 lock->orig_ref_name =xstrdup(orig_refname);2429 ref_file =git_path("%s", refname);24302431 retry:2432switch(safe_create_leading_directories(ref_file)) {2433case SCLD_OK:2434break;/* success */2435case SCLD_VANISHED:2436if(--attempts_remaining >0)2437goto retry;2438/* fall through */2439default:2440 last_errno = errno;2441strbuf_addf(err,"unable to create directory for%s", ref_file);2442goto error_return;2443}24442445 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2446if(lock->lock_fd <0) {2447 last_errno = errno;2448if(errno == ENOENT && --attempts_remaining >0)2449/*2450 * Maybe somebody just deleted one of the2451 * directories leading to ref_file. Try2452 * again:2453 */2454goto retry;2455else{2456unable_to_lock_message(ref_file, errno, err);2457goto error_return;2458}2459}2460return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;24612462 error_return:2463unlock_ref(lock);2464 errno = last_errno;2465return NULL;2466}24672468/*2469 * Write an entry to the packed-refs file for the specified refname.2470 * If peeled is non-NULL, write it as the entry's peeled value.2471 */2472static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2473unsigned char*peeled)2474{2475fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2476if(peeled)2477fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2478}24792480/*2481 * An each_ref_entry_fn that writes the entry to a packed-refs file.2482 */2483static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2484{2485enum peel_status peel_status =peel_entry(entry,0);24862487if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2488error("internal error:%sis not a valid packed reference!",2489 entry->name);2490write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2491 peel_status == PEEL_PEELED ?2492 entry->u.value.peeled : NULL);2493return0;2494}24952496/* This should return a meaningful errno on failure */2497intlock_packed_refs(int flags)2498{2499struct packed_ref_cache *packed_ref_cache;25002501if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2502return-1;2503/*2504 * Get the current packed-refs while holding the lock. If the2505 * packed-refs file has been modified since we last read it,2506 * this will automatically invalidate the cache and re-read2507 * the packed-refs file.2508 */2509 packed_ref_cache =get_packed_ref_cache(&ref_cache);2510 packed_ref_cache->lock = &packlock;2511/* Increment the reference count to prevent it from being freed: */2512acquire_packed_ref_cache(packed_ref_cache);2513return0;2514}25152516/*2517 * Commit the packed refs changes.2518 * On error we must make sure that errno contains a meaningful value.2519 */2520intcommit_packed_refs(void)2521{2522struct packed_ref_cache *packed_ref_cache =2523get_packed_ref_cache(&ref_cache);2524int error =0;2525int save_errno =0;2526FILE*out;25272528if(!packed_ref_cache->lock)2529die("internal error: packed-refs not locked");25302531 out =fdopen_lock_file(packed_ref_cache->lock,"w");2532if(!out)2533die_errno("unable to fdopen packed-refs descriptor");25342535fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2536do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25370, write_packed_entry_fn, out);25382539if(commit_lock_file(packed_ref_cache->lock)) {2540 save_errno = errno;2541 error = -1;2542}2543 packed_ref_cache->lock = NULL;2544release_packed_ref_cache(packed_ref_cache);2545 errno = save_errno;2546return error;2547}25482549voidrollback_packed_refs(void)2550{2551struct packed_ref_cache *packed_ref_cache =2552get_packed_ref_cache(&ref_cache);25532554if(!packed_ref_cache->lock)2555die("internal error: packed-refs not locked");2556rollback_lock_file(packed_ref_cache->lock);2557 packed_ref_cache->lock = NULL;2558release_packed_ref_cache(packed_ref_cache);2559clear_packed_ref_cache(&ref_cache);2560}25612562struct ref_to_prune {2563struct ref_to_prune *next;2564unsigned char sha1[20];2565char name[FLEX_ARRAY];2566};25672568struct pack_refs_cb_data {2569unsigned int flags;2570struct ref_dir *packed_refs;2571struct ref_to_prune *ref_to_prune;2572};25732574/*2575 * An each_ref_entry_fn that is run over loose references only. If2576 * the loose reference can be packed, add an entry in the packed ref2577 * cache. If the reference should be pruned, also add it to2578 * ref_to_prune in the pack_refs_cb_data.2579 */2580static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2581{2582struct pack_refs_cb_data *cb = cb_data;2583enum peel_status peel_status;2584struct ref_entry *packed_entry;2585int is_tag_ref =starts_with(entry->name,"refs/tags/");25862587/* ALWAYS pack tags */2588if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2589return0;25902591/* Do not pack symbolic or broken refs: */2592if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2593return0;25942595/* Add a packed ref cache entry equivalent to the loose entry. */2596 peel_status =peel_entry(entry,1);2597if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2598die("internal error peeling reference%s(%s)",2599 entry->name,sha1_to_hex(entry->u.value.sha1));2600 packed_entry =find_ref(cb->packed_refs, entry->name);2601if(packed_entry) {2602/* Overwrite existing packed entry with info from loose entry */2603 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2604hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2605}else{2606 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2607 REF_ISPACKED | REF_KNOWS_PEELED,0);2608add_ref(cb->packed_refs, packed_entry);2609}2610hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);26112612/* Schedule the loose reference for pruning if requested. */2613if((cb->flags & PACK_REFS_PRUNE)) {2614int namelen =strlen(entry->name) +1;2615struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2616hashcpy(n->sha1, entry->u.value.sha1);2617strcpy(n->name, entry->name);2618 n->next = cb->ref_to_prune;2619 cb->ref_to_prune = n;2620}2621return0;2622}26232624/*2625 * Remove empty parents, but spare refs/ and immediate subdirs.2626 * Note: munges *name.2627 */2628static voidtry_remove_empty_parents(char*name)2629{2630char*p, *q;2631int i;2632 p = name;2633for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2634while(*p && *p !='/')2635 p++;2636/* tolerate duplicate slashes; see check_refname_format() */2637while(*p =='/')2638 p++;2639}2640for(q = p; *q; q++)2641;2642while(1) {2643while(q > p && *q !='/')2644 q--;2645while(q > p && *(q-1) =='/')2646 q--;2647if(q == p)2648break;2649*q ='\0';2650if(rmdir(git_path("%s", name)))2651break;2652}2653}26542655/* make sure nobody touched the ref, and unlink */2656static voidprune_ref(struct ref_to_prune *r)2657{2658struct ref_transaction *transaction;2659struct strbuf err = STRBUF_INIT;26602661if(check_refname_format(r->name,0))2662return;26632664 transaction =ref_transaction_begin(&err);2665if(!transaction ||2666ref_transaction_delete(transaction, r->name, r->sha1,2667 REF_ISPRUNING, NULL, &err) ||2668ref_transaction_commit(transaction, &err)) {2669ref_transaction_free(transaction);2670error("%s", err.buf);2671strbuf_release(&err);2672return;2673}2674ref_transaction_free(transaction);2675strbuf_release(&err);2676try_remove_empty_parents(r->name);2677}26782679static voidprune_refs(struct ref_to_prune *r)2680{2681while(r) {2682prune_ref(r);2683 r = r->next;2684}2685}26862687intpack_refs(unsigned int flags)2688{2689struct pack_refs_cb_data cbdata;26902691memset(&cbdata,0,sizeof(cbdata));2692 cbdata.flags = flags;26932694lock_packed_refs(LOCK_DIE_ON_ERROR);2695 cbdata.packed_refs =get_packed_refs(&ref_cache);26962697do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2698 pack_if_possible_fn, &cbdata);26992700if(commit_packed_refs())2701die_errno("unable to overwrite old ref-pack file");27022703prune_refs(cbdata.ref_to_prune);2704return0;2705}27062707intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2708{2709struct ref_dir *packed;2710struct string_list_item *refname;2711int ret, needs_repacking =0, removed =0;27122713assert(err);27142715/* Look for a packed ref */2716for_each_string_list_item(refname, refnames) {2717if(get_packed_ref(refname->string)) {2718 needs_repacking =1;2719break;2720}2721}27222723/* Avoid locking if we have nothing to do */2724if(!needs_repacking)2725return0;/* no refname exists in packed refs */27262727if(lock_packed_refs(0)) {2728unable_to_lock_message(git_path("packed-refs"), errno, err);2729return-1;2730}2731 packed =get_packed_refs(&ref_cache);27322733/* Remove refnames from the cache */2734for_each_string_list_item(refname, refnames)2735if(remove_entry(packed, refname->string) != -1)2736 removed =1;2737if(!removed) {2738/*2739 * All packed entries disappeared while we were2740 * acquiring the lock.2741 */2742rollback_packed_refs();2743return0;2744}27452746/* Write what remains */2747 ret =commit_packed_refs();2748if(ret)2749strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2750strerror(errno));2751return ret;2752}27532754static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2755{2756assert(err);27572758if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2759/*2760 * loose. The loose file name is the same as the2761 * lockfile name, minus ".lock":2762 */2763char*loose_filename =get_locked_file_path(lock->lk);2764int res =unlink_or_msg(loose_filename, err);2765free(loose_filename);2766if(res)2767return1;2768}2769return0;2770}27712772intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2773{2774struct ref_transaction *transaction;2775struct strbuf err = STRBUF_INIT;27762777 transaction =ref_transaction_begin(&err);2778if(!transaction ||2779ref_transaction_delete(transaction, refname,2780(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2781 flags, NULL, &err) ||2782ref_transaction_commit(transaction, &err)) {2783error("%s", err.buf);2784ref_transaction_free(transaction);2785strbuf_release(&err);2786return1;2787}2788ref_transaction_free(transaction);2789strbuf_release(&err);2790return0;2791}27922793/*2794 * People using contrib's git-new-workdir have .git/logs/refs ->2795 * /some/other/path/.git/logs/refs, and that may live on another device.2796 *2797 * IOW, to avoid cross device rename errors, the temporary renamed log must2798 * live into logs/refs.2799 */2800#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"28012802static intrename_tmp_log(const char*newrefname)2803{2804int attempts_remaining =4;28052806 retry:2807switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2808case SCLD_OK:2809break;/* success */2810case SCLD_VANISHED:2811if(--attempts_remaining >0)2812goto retry;2813/* fall through */2814default:2815error("unable to create directory for%s", newrefname);2816return-1;2817}28182819if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2820if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2821/*2822 * rename(a, b) when b is an existing2823 * directory ought to result in ISDIR, but2824 * Solaris 5.8 gives ENOTDIR. Sheesh.2825 */2826if(remove_empty_directories(git_path("logs/%s", newrefname))) {2827error("Directory not empty: logs/%s", newrefname);2828return-1;2829}2830goto retry;2831}else if(errno == ENOENT && --attempts_remaining >0) {2832/*2833 * Maybe another process just deleted one of2834 * the directories in the path to newrefname.2835 * Try again from the beginning.2836 */2837goto retry;2838}else{2839error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2840 newrefname,strerror(errno));2841return-1;2842}2843}2844return0;2845}28462847static intrename_ref_available(const char*oldname,const char*newname)2848{2849struct string_list skip = STRING_LIST_INIT_NODUP;2850struct strbuf err = STRBUF_INIT;2851int ret;28522853string_list_insert(&skip, oldname);2854 ret = !verify_refname_available(newname, NULL, &skip,2855get_packed_refs(&ref_cache), &err)2856&& !verify_refname_available(newname, NULL, &skip,2857get_loose_refs(&ref_cache), &err);2858if(!ret)2859error("%s", err.buf);28602861string_list_clear(&skip,0);2862strbuf_release(&err);2863return ret;2864}28652866static intwrite_ref_to_lockfile(struct ref_lock *lock,const unsigned char*sha1);2867static intcommit_ref_update(struct ref_lock *lock,2868const unsigned char*sha1,const char*logmsg);28692870intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2871{2872unsigned char sha1[20], orig_sha1[20];2873int flag =0, logmoved =0;2874struct ref_lock *lock;2875struct stat loginfo;2876int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2877const char*symref = NULL;2878struct strbuf err = STRBUF_INIT;28792880if(log &&S_ISLNK(loginfo.st_mode))2881returnerror("reflog for%sis a symlink", oldrefname);28822883 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2884 orig_sha1, &flag);2885if(flag & REF_ISSYMREF)2886returnerror("refname%sis a symbolic ref, renaming it is not supported",2887 oldrefname);2888if(!symref)2889returnerror("refname%snot found", oldrefname);28902891if(!rename_ref_available(oldrefname, newrefname))2892return1;28932894if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2895returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2896 oldrefname,strerror(errno));28972898if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2899error("unable to delete old%s", oldrefname);2900goto rollback;2901}29022903if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2904delete_ref(newrefname, sha1, REF_NODEREF)) {2905if(errno==EISDIR) {2906if(remove_empty_directories(git_path("%s", newrefname))) {2907error("Directory not empty:%s", newrefname);2908goto rollback;2909}2910}else{2911error("unable to delete existing%s", newrefname);2912goto rollback;2913}2914}29152916if(log &&rename_tmp_log(newrefname))2917goto rollback;29182919 logmoved = log;29202921 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2922if(!lock) {2923error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2924strbuf_release(&err);2925goto rollback;2926}2927hashcpy(lock->old_sha1, orig_sha1);29282929if(write_ref_to_lockfile(lock, orig_sha1) ||2930commit_ref_update(lock, orig_sha1, logmsg)) {2931error("unable to write current sha1 into%s", newrefname);2932goto rollback;2933}29342935return0;29362937 rollback:2938 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2939if(!lock) {2940error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2941strbuf_release(&err);2942goto rollbacklog;2943}29442945 flag = log_all_ref_updates;2946 log_all_ref_updates =0;2947if(write_ref_to_lockfile(lock, orig_sha1) ||2948commit_ref_update(lock, orig_sha1, NULL))2949error("unable to write current sha1 into%s", oldrefname);2950 log_all_ref_updates = flag;29512952 rollbacklog:2953if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2954error("unable to restore logfile%sfrom%s:%s",2955 oldrefname, newrefname,strerror(errno));2956if(!logmoved && log &&2957rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2958error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2959 oldrefname,strerror(errno));29602961return1;2962}29632964static intclose_ref(struct ref_lock *lock)2965{2966if(close_lock_file(lock->lk))2967return-1;2968 lock->lock_fd = -1;2969return0;2970}29712972static intcommit_ref(struct ref_lock *lock)2973{2974if(commit_lock_file(lock->lk))2975return-1;2976 lock->lock_fd = -1;2977return0;2978}29792980/*2981 * copy the reflog message msg to buf, which has been allocated sufficiently2982 * large, while cleaning up the whitespaces. Especially, convert LF to space,2983 * because reflog file is one line per entry.2984 */2985static intcopy_msg(char*buf,const char*msg)2986{2987char*cp = buf;2988char c;2989int wasspace =1;29902991*cp++ ='\t';2992while((c = *msg++)) {2993if(wasspace &&isspace(c))2994continue;2995 wasspace =isspace(c);2996if(wasspace)2997 c =' ';2998*cp++ = c;2999}3000while(buf < cp &&isspace(cp[-1]))3001 cp--;3002*cp++ ='\n';3003return cp - buf;3004}30053006/* This function must set a meaningful errno on failure */3007intlog_ref_setup(const char*refname,char*logfile,int bufsize)3008{3009int logfd, oflags = O_APPEND | O_WRONLY;30103011git_snpath(logfile, bufsize,"logs/%s", refname);3012if(log_all_ref_updates &&3013(starts_with(refname,"refs/heads/") ||3014starts_with(refname,"refs/remotes/") ||3015starts_with(refname,"refs/notes/") ||3016!strcmp(refname,"HEAD"))) {3017if(safe_create_leading_directories(logfile) <0) {3018int save_errno = errno;3019error("unable to create directory for%s", logfile);3020 errno = save_errno;3021return-1;3022}3023 oflags |= O_CREAT;3024}30253026 logfd =open(logfile, oflags,0666);3027if(logfd <0) {3028if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3029return0;30303031if(errno == EISDIR) {3032if(remove_empty_directories(logfile)) {3033int save_errno = errno;3034error("There are still logs under '%s'",3035 logfile);3036 errno = save_errno;3037return-1;3038}3039 logfd =open(logfile, oflags,0666);3040}30413042if(logfd <0) {3043int save_errno = errno;3044error("Unable to append to%s:%s", logfile,3045strerror(errno));3046 errno = save_errno;3047return-1;3048}3049}30503051adjust_shared_perm(logfile);3052close(logfd);3053return0;3054}30553056static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3057const unsigned char*new_sha1,3058const char*committer,const char*msg)3059{3060int msglen, written;3061unsigned maxlen, len;3062char*logrec;30633064 msglen = msg ?strlen(msg) :0;3065 maxlen =strlen(committer) + msglen +100;3066 logrec =xmalloc(maxlen);3067 len =sprintf(logrec,"%s %s %s\n",3068sha1_to_hex(old_sha1),3069sha1_to_hex(new_sha1),3070 committer);3071if(msglen)3072 len +=copy_msg(logrec + len -1, msg) -1;30733074 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3075free(logrec);3076if(written != len)3077return-1;30783079return0;3080}30813082static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3083const unsigned char*new_sha1,const char*msg)3084{3085int logfd, result, oflags = O_APPEND | O_WRONLY;3086char log_file[PATH_MAX];30873088if(log_all_ref_updates <0)3089 log_all_ref_updates = !is_bare_repository();30903091 result =log_ref_setup(refname, log_file,sizeof(log_file));3092if(result)3093return result;30943095 logfd =open(log_file, oflags);3096if(logfd <0)3097return0;3098 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3099git_committer_info(0), msg);3100if(result) {3101int save_errno = errno;3102close(logfd);3103error("Unable to append to%s", log_file);3104 errno = save_errno;3105return-1;3106}3107if(close(logfd)) {3108int save_errno = errno;3109error("Unable to append to%s", log_file);3110 errno = save_errno;3111return-1;3112}3113return0;3114}31153116intis_branch(const char*refname)3117{3118return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3119}31203121/*3122 * Write sha1 into the open lockfile, then close the lockfile. On3123 * errors, rollback the lockfile and set errno to reflect the problem.3124 */3125static intwrite_ref_to_lockfile(struct ref_lock *lock,3126const unsigned char*sha1)3127{3128static char term ='\n';3129struct object *o;31303131 o =parse_object(sha1);3132if(!o) {3133error("Trying to write ref%swith nonexistent object%s",3134 lock->ref_name,sha1_to_hex(sha1));3135unlock_ref(lock);3136 errno = EINVAL;3137return-1;3138}3139if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3140error("Trying to write non-commit object%sto branch%s",3141sha1_to_hex(sha1), lock->ref_name);3142unlock_ref(lock);3143 errno = EINVAL;3144return-1;3145}3146if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3147write_in_full(lock->lock_fd, &term,1) !=1||3148close_ref(lock) <0) {3149int save_errno = errno;3150error("Couldn't write%s", lock->lk->filename.buf);3151unlock_ref(lock);3152 errno = save_errno;3153return-1;3154}3155return0;3156}31573158/*3159 * Commit a change to a loose reference that has already been written3160 * to the loose reference lockfile. Also update the reflogs if3161 * necessary, using the specified lockmsg (which can be NULL).3162 */3163static intcommit_ref_update(struct ref_lock *lock,3164const unsigned char*sha1,const char*logmsg)3165{3166clear_loose_ref_cache(&ref_cache);3167if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3168(strcmp(lock->ref_name, lock->orig_ref_name) &&3169log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3170unlock_ref(lock);3171return-1;3172}3173if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3174/*3175 * Special hack: If a branch is updated directly and HEAD3176 * points to it (may happen on the remote side of a push3177 * for example) then logically the HEAD reflog should be3178 * updated too.3179 * A generic solution implies reverse symref information,3180 * but finding all symrefs pointing to the given branch3181 * would be rather costly for this rare event (the direct3182 * update of a branch) to be worth it. So let's cheat and3183 * check with HEAD only which should cover 99% of all usage3184 * scenarios (even 100% of the default ones).3185 */3186unsigned char head_sha1[20];3187int head_flag;3188const char*head_ref;3189 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3190 head_sha1, &head_flag);3191if(head_ref && (head_flag & REF_ISSYMREF) &&3192!strcmp(head_ref, lock->ref_name))3193log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3194}3195if(commit_ref(lock)) {3196error("Couldn't set%s", lock->ref_name);3197unlock_ref(lock);3198return-1;3199}3200unlock_ref(lock);3201return0;3202}32033204intcreate_symref(const char*ref_target,const char*refs_heads_master,3205const char*logmsg)3206{3207const char*lockpath;3208char ref[1000];3209int fd, len, written;3210char*git_HEAD =git_pathdup("%s", ref_target);3211unsigned char old_sha1[20], new_sha1[20];32123213if(logmsg &&read_ref(ref_target, old_sha1))3214hashclr(old_sha1);32153216if(safe_create_leading_directories(git_HEAD) <0)3217returnerror("unable to create directory for%s", git_HEAD);32183219#ifndef NO_SYMLINK_HEAD3220if(prefer_symlink_refs) {3221unlink(git_HEAD);3222if(!symlink(refs_heads_master, git_HEAD))3223goto done;3224fprintf(stderr,"no symlink - falling back to symbolic ref\n");3225}3226#endif32273228 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3229if(sizeof(ref) <= len) {3230error("refname too long:%s", refs_heads_master);3231goto error_free_return;3232}3233 lockpath =mkpath("%s.lock", git_HEAD);3234 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3235if(fd <0) {3236error("Unable to open%sfor writing", lockpath);3237goto error_free_return;3238}3239 written =write_in_full(fd, ref, len);3240if(close(fd) !=0|| written != len) {3241error("Unable to write to%s", lockpath);3242goto error_unlink_return;3243}3244if(rename(lockpath, git_HEAD) <0) {3245error("Unable to create%s", git_HEAD);3246goto error_unlink_return;3247}3248if(adjust_shared_perm(git_HEAD)) {3249error("Unable to fix permissions on%s", lockpath);3250 error_unlink_return:3251unlink_or_warn(lockpath);3252 error_free_return:3253free(git_HEAD);3254return-1;3255}32563257#ifndef NO_SYMLINK_HEAD3258 done:3259#endif3260if(logmsg && !read_ref(refs_heads_master, new_sha1))3261log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32623263free(git_HEAD);3264return0;3265}32663267struct read_ref_at_cb {3268const char*refname;3269unsigned long at_time;3270int cnt;3271int reccnt;3272unsigned char*sha1;3273int found_it;32743275unsigned char osha1[20];3276unsigned char nsha1[20];3277int tz;3278unsigned long date;3279char**msg;3280unsigned long*cutoff_time;3281int*cutoff_tz;3282int*cutoff_cnt;3283};32843285static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3286const char*email,unsigned long timestamp,int tz,3287const char*message,void*cb_data)3288{3289struct read_ref_at_cb *cb = cb_data;32903291 cb->reccnt++;3292 cb->tz = tz;3293 cb->date = timestamp;32943295if(timestamp <= cb->at_time || cb->cnt ==0) {3296if(cb->msg)3297*cb->msg =xstrdup(message);3298if(cb->cutoff_time)3299*cb->cutoff_time = timestamp;3300if(cb->cutoff_tz)3301*cb->cutoff_tz = tz;3302if(cb->cutoff_cnt)3303*cb->cutoff_cnt = cb->reccnt -1;3304/*3305 * we have not yet updated cb->[n|o]sha1 so they still3306 * hold the values for the previous record.3307 */3308if(!is_null_sha1(cb->osha1)) {3309hashcpy(cb->sha1, nsha1);3310if(hashcmp(cb->osha1, nsha1))3311warning("Log for ref%shas gap after%s.",3312 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3313}3314else if(cb->date == cb->at_time)3315hashcpy(cb->sha1, nsha1);3316else if(hashcmp(nsha1, cb->sha1))3317warning("Log for ref%sunexpectedly ended on%s.",3318 cb->refname,show_date(cb->date, cb->tz,3319 DATE_RFC2822));3320hashcpy(cb->osha1, osha1);3321hashcpy(cb->nsha1, nsha1);3322 cb->found_it =1;3323return1;3324}3325hashcpy(cb->osha1, osha1);3326hashcpy(cb->nsha1, nsha1);3327if(cb->cnt >0)3328 cb->cnt--;3329return0;3330}33313332static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3333const char*email,unsigned long timestamp,3334int tz,const char*message,void*cb_data)3335{3336struct read_ref_at_cb *cb = cb_data;33373338if(cb->msg)3339*cb->msg =xstrdup(message);3340if(cb->cutoff_time)3341*cb->cutoff_time = timestamp;3342if(cb->cutoff_tz)3343*cb->cutoff_tz = tz;3344if(cb->cutoff_cnt)3345*cb->cutoff_cnt = cb->reccnt;3346hashcpy(cb->sha1, osha1);3347if(is_null_sha1(cb->sha1))3348hashcpy(cb->sha1, nsha1);3349/* We just want the first entry */3350return1;3351}33523353intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3354unsigned char*sha1,char**msg,3355unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3356{3357struct read_ref_at_cb cb;33583359memset(&cb,0,sizeof(cb));3360 cb.refname = refname;3361 cb.at_time = at_time;3362 cb.cnt = cnt;3363 cb.msg = msg;3364 cb.cutoff_time = cutoff_time;3365 cb.cutoff_tz = cutoff_tz;3366 cb.cutoff_cnt = cutoff_cnt;3367 cb.sha1 = sha1;33683369for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33703371if(!cb.reccnt) {3372if(flags & GET_SHA1_QUIETLY)3373exit(128);3374else3375die("Log for%sis empty.", refname);3376}3377if(cb.found_it)3378return0;33793380for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33813382return1;3383}33843385intreflog_exists(const char*refname)3386{3387struct stat st;33883389return!lstat(git_path("logs/%s", refname), &st) &&3390S_ISREG(st.st_mode);3391}33923393intdelete_reflog(const char*refname)3394{3395returnremove_path(git_path("logs/%s", refname));3396}33973398static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3399{3400unsigned char osha1[20], nsha1[20];3401char*email_end, *message;3402unsigned long timestamp;3403int tz;34043405/* old SP new SP name <email> SP time TAB msg LF */3406if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3407get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3408get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3409!(email_end =strchr(sb->buf +82,'>')) ||3410 email_end[1] !=' '||3411!(timestamp =strtoul(email_end +2, &message,10)) ||3412!message || message[0] !=' '||3413(message[1] !='+'&& message[1] !='-') ||3414!isdigit(message[2]) || !isdigit(message[3]) ||3415!isdigit(message[4]) || !isdigit(message[5]))3416return0;/* corrupt? */3417 email_end[1] ='\0';3418 tz =strtol(message +1, NULL,10);3419if(message[6] !='\t')3420 message +=6;3421else3422 message +=7;3423returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3424}34253426static char*find_beginning_of_line(char*bob,char*scan)3427{3428while(bob < scan && *(--scan) !='\n')3429;/* keep scanning backwards */3430/*3431 * Return either beginning of the buffer, or LF at the end of3432 * the previous line.3433 */3434return scan;3435}34363437intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3438{3439struct strbuf sb = STRBUF_INIT;3440FILE*logfp;3441long pos;3442int ret =0, at_tail =1;34433444 logfp =fopen(git_path("logs/%s", refname),"r");3445if(!logfp)3446return-1;34473448/* Jump to the end */3449if(fseek(logfp,0, SEEK_END) <0)3450returnerror("cannot seek back reflog for%s:%s",3451 refname,strerror(errno));3452 pos =ftell(logfp);3453while(!ret &&0< pos) {3454int cnt;3455size_t nread;3456char buf[BUFSIZ];3457char*endp, *scanp;34583459/* Fill next block from the end */3460 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3461if(fseek(logfp, pos - cnt, SEEK_SET))3462returnerror("cannot seek back reflog for%s:%s",3463 refname,strerror(errno));3464 nread =fread(buf, cnt,1, logfp);3465if(nread !=1)3466returnerror("cannot read%dbytes from reflog for%s:%s",3467 cnt, refname,strerror(errno));3468 pos -= cnt;34693470 scanp = endp = buf + cnt;3471if(at_tail && scanp[-1] =='\n')3472/* Looking at the final LF at the end of the file */3473 scanp--;3474 at_tail =0;34753476while(buf < scanp) {3477/*3478 * terminating LF of the previous line, or the beginning3479 * of the buffer.3480 */3481char*bp;34823483 bp =find_beginning_of_line(buf, scanp);34843485if(*bp =='\n') {3486/*3487 * The newline is the end of the previous line,3488 * so we know we have complete line starting3489 * at (bp + 1). Prefix it onto any prior data3490 * we collected for the line and process it.3491 */3492strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3493 scanp = bp;3494 endp = bp +1;3495 ret =show_one_reflog_ent(&sb, fn, cb_data);3496strbuf_reset(&sb);3497if(ret)3498break;3499}else if(!pos) {3500/*3501 * We are at the start of the buffer, and the3502 * start of the file; there is no previous3503 * line, and we have everything for this one.3504 * Process it, and we can end the loop.3505 */3506strbuf_splice(&sb,0,0, buf, endp - buf);3507 ret =show_one_reflog_ent(&sb, fn, cb_data);3508strbuf_reset(&sb);3509break;3510}35113512if(bp == buf) {3513/*3514 * We are at the start of the buffer, and there3515 * is more file to read backwards. Which means3516 * we are in the middle of a line. Note that we3517 * may get here even if *bp was a newline; that3518 * just means we are at the exact end of the3519 * previous line, rather than some spot in the3520 * middle.3521 *3522 * Save away what we have to be combined with3523 * the data from the next read.3524 */3525strbuf_splice(&sb,0,0, buf, endp - buf);3526break;3527}3528}35293530}3531if(!ret && sb.len)3532die("BUG: reverse reflog parser had leftover data");35333534fclose(logfp);3535strbuf_release(&sb);3536return ret;3537}35383539intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3540{3541FILE*logfp;3542struct strbuf sb = STRBUF_INIT;3543int ret =0;35443545 logfp =fopen(git_path("logs/%s", refname),"r");3546if(!logfp)3547return-1;35483549while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3550 ret =show_one_reflog_ent(&sb, fn, cb_data);3551fclose(logfp);3552strbuf_release(&sb);3553return ret;3554}3555/*3556 * Call fn for each reflog in the namespace indicated by name. name3557 * must be empty or end with '/'. Name will be used as a scratch3558 * space, but its contents will be restored before return.3559 */3560static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3561{3562DIR*d =opendir(git_path("logs/%s", name->buf));3563int retval =0;3564struct dirent *de;3565int oldlen = name->len;35663567if(!d)3568return name->len ? errno :0;35693570while((de =readdir(d)) != NULL) {3571struct stat st;35723573if(de->d_name[0] =='.')3574continue;3575if(ends_with(de->d_name,".lock"))3576continue;3577strbuf_addstr(name, de->d_name);3578if(stat(git_path("logs/%s", name->buf), &st) <0) {3579;/* silently ignore */3580}else{3581if(S_ISDIR(st.st_mode)) {3582strbuf_addch(name,'/');3583 retval =do_for_each_reflog(name, fn, cb_data);3584}else{3585unsigned char sha1[20];3586if(read_ref_full(name->buf,0, sha1, NULL))3587 retval =error("bad ref for%s", name->buf);3588else3589 retval =fn(name->buf, sha1,0, cb_data);3590}3591if(retval)3592break;3593}3594strbuf_setlen(name, oldlen);3595}3596closedir(d);3597return retval;3598}35993600intfor_each_reflog(each_ref_fn fn,void*cb_data)3601{3602int retval;3603struct strbuf name;3604strbuf_init(&name, PATH_MAX);3605 retval =do_for_each_reflog(&name, fn, cb_data);3606strbuf_release(&name);3607return retval;3608}36093610/**3611 * Information needed for a single ref update. Set new_sha1 to the new3612 * value or to null_sha1 to delete the ref. To check the old value3613 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3614 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3615 * not exist before update.3616 */3617struct ref_update {3618/*3619 * If (flags & REF_HAVE_NEW), set the reference to this value:3620 */3621unsigned char new_sha1[20];3622/*3623 * If (flags & REF_HAVE_OLD), check that the reference3624 * previously had this value:3625 */3626unsigned char old_sha1[20];3627/*3628 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3629 * REF_DELETING, and REF_ISPRUNING:3630 */3631unsigned int flags;3632struct ref_lock *lock;3633int type;3634char*msg;3635const char refname[FLEX_ARRAY];3636};36373638/*3639 * Transaction states.3640 * OPEN: The transaction is in a valid state and can accept new updates.3641 * An OPEN transaction can be committed.3642 * CLOSED: A closed transaction is no longer active and no other operations3643 * than free can be used on it in this state.3644 * A transaction can either become closed by successfully committing3645 * an active transaction or if there is a failure while building3646 * the transaction thus rendering it failed/inactive.3647 */3648enum ref_transaction_state {3649 REF_TRANSACTION_OPEN =0,3650 REF_TRANSACTION_CLOSED =13651};36523653/*3654 * Data structure for holding a reference transaction, which can3655 * consist of checks and updates to multiple references, carried out3656 * as atomically as possible. This structure is opaque to callers.3657 */3658struct ref_transaction {3659struct ref_update **updates;3660size_t alloc;3661size_t nr;3662enum ref_transaction_state state;3663};36643665struct ref_transaction *ref_transaction_begin(struct strbuf *err)3666{3667assert(err);36683669returnxcalloc(1,sizeof(struct ref_transaction));3670}36713672voidref_transaction_free(struct ref_transaction *transaction)3673{3674int i;36753676if(!transaction)3677return;36783679for(i =0; i < transaction->nr; i++) {3680free(transaction->updates[i]->msg);3681free(transaction->updates[i]);3682}3683free(transaction->updates);3684free(transaction);3685}36863687static struct ref_update *add_update(struct ref_transaction *transaction,3688const char*refname)3689{3690size_t len =strlen(refname);3691struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36923693strcpy((char*)update->refname, refname);3694ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3695 transaction->updates[transaction->nr++] = update;3696return update;3697}36983699intref_transaction_update(struct ref_transaction *transaction,3700const char*refname,3701const unsigned char*new_sha1,3702const unsigned char*old_sha1,3703unsigned int flags,const char*msg,3704struct strbuf *err)3705{3706struct ref_update *update;37073708assert(err);37093710if(transaction->state != REF_TRANSACTION_OPEN)3711die("BUG: update called for transaction that is not open");37123713if(new_sha1 && !is_null_sha1(new_sha1) &&3714check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3715strbuf_addf(err,"refusing to update ref with bad name%s",3716 refname);3717return-1;3718}37193720 update =add_update(transaction, refname);3721if(new_sha1) {3722hashcpy(update->new_sha1, new_sha1);3723 flags |= REF_HAVE_NEW;3724}3725if(old_sha1) {3726hashcpy(update->old_sha1, old_sha1);3727 flags |= REF_HAVE_OLD;3728}3729 update->flags = flags;3730if(msg)3731 update->msg =xstrdup(msg);3732return0;3733}37343735intref_transaction_create(struct ref_transaction *transaction,3736const char*refname,3737const unsigned char*new_sha1,3738unsigned int flags,const char*msg,3739struct strbuf *err)3740{3741if(!new_sha1 ||is_null_sha1(new_sha1))3742die("BUG: create called without valid new_sha1");3743returnref_transaction_update(transaction, refname, new_sha1,3744 null_sha1, flags, msg, err);3745}37463747intref_transaction_delete(struct ref_transaction *transaction,3748const char*refname,3749const unsigned char*old_sha1,3750unsigned int flags,const char*msg,3751struct strbuf *err)3752{3753if(old_sha1 &&is_null_sha1(old_sha1))3754die("BUG: delete called with old_sha1 set to zeros");3755returnref_transaction_update(transaction, refname,3756 null_sha1, old_sha1,3757 flags, msg, err);3758}37593760intref_transaction_verify(struct ref_transaction *transaction,3761const char*refname,3762const unsigned char*old_sha1,3763unsigned int flags,3764struct strbuf *err)3765{3766if(!old_sha1)3767die("BUG: verify called with old_sha1 set to NULL");3768returnref_transaction_update(transaction, refname,3769 NULL, old_sha1,3770 flags, NULL, err);3771}37723773intupdate_ref(const char*msg,const char*refname,3774const unsigned char*new_sha1,const unsigned char*old_sha1,3775unsigned int flags,enum action_on_err onerr)3776{3777struct ref_transaction *t;3778struct strbuf err = STRBUF_INIT;37793780 t =ref_transaction_begin(&err);3781if(!t ||3782ref_transaction_update(t, refname, new_sha1, old_sha1,3783 flags, msg, &err) ||3784ref_transaction_commit(t, &err)) {3785const char*str ="update_ref failed for ref '%s':%s";37863787ref_transaction_free(t);3788switch(onerr) {3789case UPDATE_REFS_MSG_ON_ERR:3790error(str, refname, err.buf);3791break;3792case UPDATE_REFS_DIE_ON_ERR:3793die(str, refname, err.buf);3794break;3795case UPDATE_REFS_QUIET_ON_ERR:3796break;3797}3798strbuf_release(&err);3799return1;3800}3801strbuf_release(&err);3802ref_transaction_free(t);3803return0;3804}38053806static intref_update_reject_duplicates(struct string_list *refnames,3807struct strbuf *err)3808{3809int i, n = refnames->nr;38103811assert(err);38123813for(i =1; i < n; i++)3814if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3815strbuf_addf(err,3816"Multiple updates for ref '%s' not allowed.",3817 refnames->items[i].string);3818return1;3819}3820return0;3821}38223823intref_transaction_commit(struct ref_transaction *transaction,3824struct strbuf *err)3825{3826int ret =0, i;3827int n = transaction->nr;3828struct ref_update **updates = transaction->updates;3829struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3830struct string_list_item *ref_to_delete;3831struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38323833assert(err);38343835if(transaction->state != REF_TRANSACTION_OPEN)3836die("BUG: commit called for transaction that is not open");38373838if(!n) {3839 transaction->state = REF_TRANSACTION_CLOSED;3840return0;3841}38423843/* Fail if a refname appears more than once in the transaction: */3844for(i =0; i < n; i++)3845string_list_append(&affected_refnames, updates[i]->refname);3846string_list_sort(&affected_refnames);3847if(ref_update_reject_duplicates(&affected_refnames, err)) {3848 ret = TRANSACTION_GENERIC_ERROR;3849goto cleanup;3850}38513852/*3853 * Acquire all locks, verify old values if provided, check3854 * that new values are valid, and write new values to the3855 * lockfiles, ready to be activated. Only keep one lockfile3856 * open at a time to avoid running out of file descriptors.3857 */3858for(i =0; i < n; i++) {3859struct ref_update *update = updates[i];38603861if((update->flags & REF_HAVE_NEW) &&3862is_null_sha1(update->new_sha1))3863 update->flags |= REF_DELETING;3864 update->lock =lock_ref_sha1_basic(3865 update->refname,3866((update->flags & REF_HAVE_OLD) ?3867 update->old_sha1 : NULL),3868&affected_refnames, NULL,3869 update->flags,3870&update->type,3871 err);3872if(!update->lock) {3873char*reason;38743875 ret = (errno == ENOTDIR)3876? TRANSACTION_NAME_CONFLICT3877: TRANSACTION_GENERIC_ERROR;3878 reason =strbuf_detach(err, NULL);3879strbuf_addf(err,"Cannot lock ref '%s':%s",3880 update->refname, reason);3881free(reason);3882goto cleanup;3883}3884if((update->flags & REF_HAVE_NEW) &&3885!(update->flags & REF_DELETING)) {3886int overwriting_symref = ((update->type & REF_ISSYMREF) &&3887(update->flags & REF_NODEREF));38883889if(!overwriting_symref &&3890!hashcmp(update->lock->old_sha1, update->new_sha1)) {3891/*3892 * The reference already has the desired3893 * value, so we don't need to write it.3894 */3895}else if(write_ref_to_lockfile(update->lock,3896 update->new_sha1)) {3897/*3898 * The lock was freed upon failure of3899 * write_ref_to_lockfile():3900 */3901 update->lock = NULL;3902strbuf_addf(err,"Cannot update the ref '%s'.",3903 update->refname);3904 ret = TRANSACTION_GENERIC_ERROR;3905goto cleanup;3906}else{3907 update->flags |= REF_NEEDS_COMMIT;3908}3909}3910if(!(update->flags & REF_NEEDS_COMMIT)) {3911/*3912 * We didn't have to write anything to the lockfile.3913 * Close it to free up the file descriptor:3914 */3915if(close_ref(update->lock)) {3916strbuf_addf(err,"Couldn't close%s.lock",3917 update->refname);3918goto cleanup;3919}3920}3921}39223923/* Perform updates first so live commits remain referenced */3924for(i =0; i < n; i++) {3925struct ref_update *update = updates[i];39263927if(update->flags & REF_NEEDS_COMMIT) {3928if(commit_ref_update(update->lock,3929 update->new_sha1, update->msg)) {3930/* freed by commit_ref_update(): */3931 update->lock = NULL;3932strbuf_addf(err,"Cannot update the ref '%s'.",3933 update->refname);3934 ret = TRANSACTION_GENERIC_ERROR;3935goto cleanup;3936}else{3937/* freed by commit_ref_update(): */3938 update->lock = NULL;3939}3940}3941}39423943/* Perform deletes now that updates are safely completed */3944for(i =0; i < n; i++) {3945struct ref_update *update = updates[i];39463947if(update->flags & REF_DELETING) {3948if(delete_ref_loose(update->lock, update->type, err)) {3949 ret = TRANSACTION_GENERIC_ERROR;3950goto cleanup;3951}39523953if(!(update->flags & REF_ISPRUNING))3954string_list_append(&refs_to_delete,3955 update->lock->ref_name);3956}3957}39583959if(repack_without_refs(&refs_to_delete, err)) {3960 ret = TRANSACTION_GENERIC_ERROR;3961goto cleanup;3962}3963for_each_string_list_item(ref_to_delete, &refs_to_delete)3964unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3965clear_loose_ref_cache(&ref_cache);39663967cleanup:3968 transaction->state = REF_TRANSACTION_CLOSED;39693970for(i =0; i < n; i++)3971if(updates[i]->lock)3972unlock_ref(updates[i]->lock);3973string_list_clear(&refs_to_delete,0);3974string_list_clear(&affected_refnames,0);3975return ret;3976}39773978char*shorten_unambiguous_ref(const char*refname,int strict)3979{3980int i;3981static char**scanf_fmts;3982static int nr_rules;3983char*short_name;39843985if(!nr_rules) {3986/*3987 * Pre-generate scanf formats from ref_rev_parse_rules[].3988 * Generate a format suitable for scanf from a3989 * ref_rev_parse_rules rule by interpolating "%s" at the3990 * location of the "%.*s".3991 */3992size_t total_len =0;3993size_t offset =0;39943995/* the rule list is NULL terminated, count them first */3996for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3997/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3998 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;39994000 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);40014002 offset =0;4003for(i =0; i < nr_rules; i++) {4004assert(offset < total_len);4005 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4006 offset +=snprintf(scanf_fmts[i], total_len - offset,4007 ref_rev_parse_rules[i],2,"%s") +1;4008}4009}40104011/* bail out if there are no rules */4012if(!nr_rules)4013returnxstrdup(refname);40144015/* buffer for scanf result, at most refname must fit */4016 short_name =xstrdup(refname);40174018/* skip first rule, it will always match */4019for(i = nr_rules -1; i >0; --i) {4020int j;4021int rules_to_fail = i;4022int short_name_len;40234024if(1!=sscanf(refname, scanf_fmts[i], short_name))4025continue;40264027 short_name_len =strlen(short_name);40284029/*4030 * in strict mode, all (except the matched one) rules4031 * must fail to resolve to a valid non-ambiguous ref4032 */4033if(strict)4034 rules_to_fail = nr_rules;40354036/*4037 * check if the short name resolves to a valid ref,4038 * but use only rules prior to the matched one4039 */4040for(j =0; j < rules_to_fail; j++) {4041const char*rule = ref_rev_parse_rules[j];4042char refname[PATH_MAX];40434044/* skip matched rule */4045if(i == j)4046continue;40474048/*4049 * the short name is ambiguous, if it resolves4050 * (with this previous rule) to a valid ref4051 * read_ref() returns 0 on success4052 */4053mksnpath(refname,sizeof(refname),4054 rule, short_name_len, short_name);4055if(ref_exists(refname))4056break;4057}40584059/*4060 * short name is non-ambiguous if all previous rules4061 * haven't resolved to a valid ref4062 */4063if(j == rules_to_fail)4064return short_name;4065}40664067free(short_name);4068returnxstrdup(refname);4069}40704071static struct string_list *hide_refs;40724073intparse_hide_refs_config(const char*var,const char*value,const char*section)4074{4075if(!strcmp("transfer.hiderefs", var) ||4076/* NEEDSWORK: use parse_config_key() once both are merged */4077(starts_with(var, section) && var[strlen(section)] =='.'&&4078!strcmp(var +strlen(section),".hiderefs"))) {4079char*ref;4080int len;40814082if(!value)4083returnconfig_error_nonbool(var);4084 ref =xstrdup(value);4085 len =strlen(ref);4086while(len && ref[len -1] =='/')4087 ref[--len] ='\0';4088if(!hide_refs) {4089 hide_refs =xcalloc(1,sizeof(*hide_refs));4090 hide_refs->strdup_strings =1;4091}4092string_list_append(hide_refs, ref);4093}4094return0;4095}40964097intref_is_hidden(const char*refname)4098{4099struct string_list_item *item;41004101if(!hide_refs)4102return0;4103for_each_string_list_item(item, hide_refs) {4104int len;4105if(!starts_with(refname, item->string))4106continue;4107 len =strlen(item->string);4108if(!refname[len] || refname[len] =='/')4109return1;4110}4111return0;4112}41134114struct expire_reflog_cb {4115unsigned int flags;4116 reflog_expiry_should_prune_fn *should_prune_fn;4117void*policy_cb;4118FILE*newlog;4119unsigned char last_kept_sha1[20];4120};41214122static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4123const char*email,unsigned long timestamp,int tz,4124const char*message,void*cb_data)4125{4126struct expire_reflog_cb *cb = cb_data;4127struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41284129if(cb->flags & EXPIRE_REFLOGS_REWRITE)4130 osha1 = cb->last_kept_sha1;41314132if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4133 message, policy_cb)) {4134if(!cb->newlog)4135printf("would prune%s", message);4136else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4137printf("prune%s", message);4138}else{4139if(cb->newlog) {4140fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4141sha1_to_hex(osha1),sha1_to_hex(nsha1),4142 email, timestamp, tz, message);4143hashcpy(cb->last_kept_sha1, nsha1);4144}4145if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4146printf("keep%s", message);4147}4148return0;4149}41504151intreflog_expire(const char*refname,const unsigned char*sha1,4152unsigned int flags,4153 reflog_expiry_prepare_fn prepare_fn,4154 reflog_expiry_should_prune_fn should_prune_fn,4155 reflog_expiry_cleanup_fn cleanup_fn,4156void*policy_cb_data)4157{4158static struct lock_file reflog_lock;4159struct expire_reflog_cb cb;4160struct ref_lock *lock;4161char*log_file;4162int status =0;4163int type;4164struct strbuf err = STRBUF_INIT;41654166memset(&cb,0,sizeof(cb));4167 cb.flags = flags;4168 cb.policy_cb = policy_cb_data;4169 cb.should_prune_fn = should_prune_fn;41704171/*4172 * The reflog file is locked by holding the lock on the4173 * reference itself, plus we might need to update the4174 * reference if --updateref was specified:4175 */4176 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4177if(!lock) {4178error("cannot lock ref '%s':%s", refname, err.buf);4179strbuf_release(&err);4180return-1;4181}4182if(!reflog_exists(refname)) {4183unlock_ref(lock);4184return0;4185}41864187 log_file =git_pathdup("logs/%s", refname);4188if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4189/*4190 * Even though holding $GIT_DIR/logs/$reflog.lock has4191 * no locking implications, we use the lock_file4192 * machinery here anyway because it does a lot of the4193 * work we need, including cleaning up if the program4194 * exits unexpectedly.4195 */4196if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4197struct strbuf err = STRBUF_INIT;4198unable_to_lock_message(log_file, errno, &err);4199error("%s", err.buf);4200strbuf_release(&err);4201goto failure;4202}4203 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4204if(!cb.newlog) {4205error("cannot fdopen%s(%s)",4206 reflog_lock.filename.buf,strerror(errno));4207goto failure;4208}4209}42104211(*prepare_fn)(refname, sha1, cb.policy_cb);4212for_each_reflog_ent(refname, expire_reflog_ent, &cb);4213(*cleanup_fn)(cb.policy_cb);42144215if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4216/*4217 * It doesn't make sense to adjust a reference pointed4218 * to by a symbolic ref based on expiring entries in4219 * the symbolic reference's reflog. Nor can we update4220 * a reference if there are no remaining reflog4221 * entries.4222 */4223int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4224!(type & REF_ISSYMREF) &&4225!is_null_sha1(cb.last_kept_sha1);42264227if(close_lock_file(&reflog_lock)) {4228 status |=error("couldn't write%s:%s", log_file,4229strerror(errno));4230}else if(update &&4231(write_in_full(lock->lock_fd,4232sha1_to_hex(cb.last_kept_sha1),40) !=40||4233write_str_in_full(lock->lock_fd,"\n") !=1||4234close_ref(lock) <0)) {4235 status |=error("couldn't write%s",4236 lock->lk->filename.buf);4237rollback_lock_file(&reflog_lock);4238}else if(commit_lock_file(&reflog_lock)) {4239 status |=error("unable to commit reflog '%s' (%s)",4240 log_file,strerror(errno));4241}else if(update &&commit_ref(lock)) {4242 status |=error("couldn't set%s", lock->ref_name);4243}4244}4245free(log_file);4246unlock_ref(lock);4247return status;42484249 failure:4250rollback_lock_file(&reflog_lock);4251free(log_file);4252unlock_ref(lock);4253return-1;4254}