1#include"cache.h" 2#include"refs.h" 3#include"object.h" 4#include"tag.h" 5#include"dir.h" 6#include"string-list.h" 7 8/* 9 * Make sure "ref" is something reasonable to have under ".git/refs/"; 10 * We do not like it if: 11 * 12 * - any path component of it begins with ".", or 13 * - it has double dots "..", or 14 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 15 * - it ends with a "/". 16 * - it ends with ".lock" 17 * - it contains a "\" (backslash) 18 */ 19 20/* Return true iff ch is not allowed in reference names. */ 21staticinlineintbad_ref_char(int ch) 22{ 23if(((unsigned) ch) <=' '|| ch ==0x7f|| 24 ch =='~'|| ch =='^'|| ch ==':'|| ch =='\\') 25return1; 26/* 2.13 Pattern Matching Notation */ 27if(ch =='*'|| ch =='?'|| ch =='[')/* Unsupported */ 28return1; 29return0; 30} 31 32/* 33 * Try to read one refname component from the front of refname. Return 34 * the length of the component found, or -1 if the component is not 35 * legal. 36 */ 37static intcheck_refname_component(const char*refname,int flags) 38{ 39const char*cp; 40char last ='\0'; 41 42for(cp = refname; ; cp++) { 43char ch = *cp; 44if(ch =='\0'|| ch =='/') 45break; 46if(bad_ref_char(ch)) 47return-1;/* Illegal character in refname. */ 48if(last =='.'&& ch =='.') 49return-1;/* Refname contains "..". */ 50if(last =='@'&& ch =='{') 51return-1;/* Refname contains "@{". */ 52 last = ch; 53} 54if(cp == refname) 55return0;/* Component has zero length. */ 56if(refname[0] =='.') { 57if(!(flags & REFNAME_DOT_COMPONENT)) 58return-1;/* Component starts with '.'. */ 59/* 60 * Even if leading dots are allowed, don't allow "." 61 * as a component (".." is prevented by a rule above). 62 */ 63if(refname[1] =='\0') 64return-1;/* Component equals ".". */ 65} 66if(cp - refname >=5&& !memcmp(cp -5,".lock",5)) 67return-1;/* Refname ends with ".lock". */ 68return cp - refname; 69} 70 71intcheck_refname_format(const char*refname,int flags) 72{ 73int component_len, component_count =0; 74 75if(!strcmp(refname,"@")) 76/* Refname is a single character '@'. */ 77return-1; 78 79while(1) { 80/* We are at the start of a path component. */ 81 component_len =check_refname_component(refname, flags); 82if(component_len <=0) { 83if((flags & REFNAME_REFSPEC_PATTERN) && 84 refname[0] =='*'&& 85(refname[1] =='\0'|| refname[1] =='/')) { 86/* Accept one wildcard as a full refname component. */ 87 flags &= ~REFNAME_REFSPEC_PATTERN; 88 component_len =1; 89}else{ 90return-1; 91} 92} 93 component_count++; 94if(refname[component_len] =='\0') 95break; 96/* Skip to next component. */ 97 refname += component_len +1; 98} 99 100if(refname[component_len -1] =='.') 101return-1;/* Refname ends with '.'. */ 102if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 103return-1;/* Refname has only one component. */ 104return0; 105} 106 107struct ref_entry; 108 109/* 110 * Information used (along with the information in ref_entry) to 111 * describe a single cached reference. This data structure only 112 * occurs embedded in a union in struct ref_entry, and only when 113 * (ref_entry->flag & REF_DIR) is zero. 114 */ 115struct ref_value { 116unsigned char sha1[20]; 117unsigned char peeled[20]; 118}; 119 120struct ref_cache; 121 122/* 123 * Information used (along with the information in ref_entry) to 124 * describe a level in the hierarchy of references. This data 125 * structure only occurs embedded in a union in struct ref_entry, and 126 * only when (ref_entry.flag & REF_DIR) is set. In that case, 127 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 128 * in the directory have already been read: 129 * 130 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 131 * or packed references, already read. 132 * 133 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 134 * references that hasn't been read yet (nor has any of its 135 * subdirectories). 136 * 137 * Entries within a directory are stored within a growable array of 138 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 139 * sorted are sorted by their component name in strcmp() order and the 140 * remaining entries are unsorted. 141 * 142 * Loose references are read lazily, one directory at a time. When a 143 * directory of loose references is read, then all of the references 144 * in that directory are stored, and REF_INCOMPLETE stubs are created 145 * for any subdirectories, but the subdirectories themselves are not 146 * read. The reading is triggered by get_ref_dir(). 147 */ 148struct ref_dir { 149int nr, alloc; 150 151/* 152 * Entries with index 0 <= i < sorted are sorted by name. New 153 * entries are appended to the list unsorted, and are sorted 154 * only when required; thus we avoid the need to sort the list 155 * after the addition of every reference. 156 */ 157int sorted; 158 159/* A pointer to the ref_cache that contains this ref_dir. */ 160struct ref_cache *ref_cache; 161 162struct ref_entry **entries; 163}; 164 165/* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */ 166#define REF_KNOWS_PEELED 0x08 167 168/* ref_entry represents a directory of references */ 169#define REF_DIR 0x10 170 171/* 172 * Entry has not yet been read from disk (used only for REF_DIR 173 * entries representing loose references) 174 */ 175#define REF_INCOMPLETE 0x20 176 177/* 178 * A ref_entry represents either a reference or a "subdirectory" of 179 * references. 180 * 181 * Each directory in the reference namespace is represented by a 182 * ref_entry with (flags & REF_DIR) set and containing a subdir member 183 * that holds the entries in that directory that have been read so 184 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 185 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 186 * used for loose reference directories. 187 * 188 * References are represented by a ref_entry with (flags & REF_DIR) 189 * unset and a value member that describes the reference's value. The 190 * flag member is at the ref_entry level, but it is also needed to 191 * interpret the contents of the value field (in other words, a 192 * ref_value object is not very much use without the enclosing 193 * ref_entry). 194 * 195 * Reference names cannot end with slash and directories' names are 196 * always stored with a trailing slash (except for the top-level 197 * directory, which is always denoted by ""). This has two nice 198 * consequences: (1) when the entries in each subdir are sorted 199 * lexicographically by name (as they usually are), the references in 200 * a whole tree can be generated in lexicographic order by traversing 201 * the tree in left-to-right, depth-first order; (2) the names of 202 * references and subdirectories cannot conflict, and therefore the 203 * presence of an empty subdirectory does not block the creation of a 204 * similarly-named reference. (The fact that reference names with the 205 * same leading components can conflict *with each other* is a 206 * separate issue that is regulated by is_refname_available().) 207 * 208 * Please note that the name field contains the fully-qualified 209 * reference (or subdirectory) name. Space could be saved by only 210 * storing the relative names. But that would require the full names 211 * to be generated on the fly when iterating in do_for_each_ref(), and 212 * would break callback functions, who have always been able to assume 213 * that the name strings that they are passed will not be freed during 214 * the iteration. 215 */ 216struct ref_entry { 217unsigned char flag;/* ISSYMREF? ISPACKED? */ 218union{ 219struct ref_value value;/* if not (flags&REF_DIR) */ 220struct ref_dir subdir;/* if (flags&REF_DIR) */ 221} u; 222/* 223 * The full name of the reference (e.g., "refs/heads/master") 224 * or the full name of the directory with a trailing slash 225 * (e.g., "refs/heads/"): 226 */ 227char name[FLEX_ARRAY]; 228}; 229 230static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 231 232static struct ref_dir *get_ref_dir(struct ref_entry *entry) 233{ 234struct ref_dir *dir; 235assert(entry->flag & REF_DIR); 236 dir = &entry->u.subdir; 237if(entry->flag & REF_INCOMPLETE) { 238read_loose_refs(entry->name, dir); 239 entry->flag &= ~REF_INCOMPLETE; 240} 241return dir; 242} 243 244static struct ref_entry *create_ref_entry(const char*refname, 245const unsigned char*sha1,int flag, 246int check_name) 247{ 248int len; 249struct ref_entry *ref; 250 251if(check_name && 252check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 253die("Reference has invalid format: '%s'", refname); 254 len =strlen(refname) +1; 255 ref =xmalloc(sizeof(struct ref_entry) + len); 256hashcpy(ref->u.value.sha1, sha1); 257hashclr(ref->u.value.peeled); 258memcpy(ref->name, refname, len); 259 ref->flag = flag; 260return ref; 261} 262 263static voidclear_ref_dir(struct ref_dir *dir); 264 265static voidfree_ref_entry(struct ref_entry *entry) 266{ 267if(entry->flag & REF_DIR) { 268/* 269 * Do not use get_ref_dir() here, as that might 270 * trigger the reading of loose refs. 271 */ 272clear_ref_dir(&entry->u.subdir); 273} 274free(entry); 275} 276 277/* 278 * Add a ref_entry to the end of dir (unsorted). Entry is always 279 * stored directly in dir; no recursion into subdirectories is 280 * done. 281 */ 282static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 283{ 284ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 285 dir->entries[dir->nr++] = entry; 286/* optimize for the case that entries are added in order */ 287if(dir->nr ==1|| 288(dir->nr == dir->sorted +1&& 289strcmp(dir->entries[dir->nr -2]->name, 290 dir->entries[dir->nr -1]->name) <0)) 291 dir->sorted = dir->nr; 292} 293 294/* 295 * Clear and free all entries in dir, recursively. 296 */ 297static voidclear_ref_dir(struct ref_dir *dir) 298{ 299int i; 300for(i =0; i < dir->nr; i++) 301free_ref_entry(dir->entries[i]); 302free(dir->entries); 303 dir->sorted = dir->nr = dir->alloc =0; 304 dir->entries = NULL; 305} 306 307/* 308 * Create a struct ref_entry object for the specified dirname. 309 * dirname is the name of the directory with a trailing slash (e.g., 310 * "refs/heads/") or "" for the top-level directory. 311 */ 312static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 313const char*dirname,size_t len, 314int incomplete) 315{ 316struct ref_entry *direntry; 317 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 318memcpy(direntry->name, dirname, len); 319 direntry->name[len] ='\0'; 320 direntry->u.subdir.ref_cache = ref_cache; 321 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 322return direntry; 323} 324 325static intref_entry_cmp(const void*a,const void*b) 326{ 327struct ref_entry *one = *(struct ref_entry **)a; 328struct ref_entry *two = *(struct ref_entry **)b; 329returnstrcmp(one->name, two->name); 330} 331 332static voidsort_ref_dir(struct ref_dir *dir); 333 334struct string_slice { 335size_t len; 336const char*str; 337}; 338 339static intref_entry_cmp_sslice(const void*key_,const void*ent_) 340{ 341const struct string_slice *key = key_; 342const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 343int cmp =strncmp(key->str, ent->name, key->len); 344if(cmp) 345return cmp; 346return'\0'- (unsigned char)ent->name[key->len]; 347} 348 349/* 350 * Return the entry with the given refname from the ref_dir 351 * (non-recursively), sorting dir if necessary. Return NULL if no 352 * such entry is found. dir must already be complete. 353 */ 354static struct ref_entry *search_ref_dir(struct ref_dir *dir, 355const char*refname,size_t len) 356{ 357struct ref_entry **r; 358struct string_slice key; 359 360if(refname == NULL || !dir->nr) 361return NULL; 362 363sort_ref_dir(dir); 364 key.len = len; 365 key.str = refname; 366 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 367 ref_entry_cmp_sslice); 368 369if(r == NULL) 370return NULL; 371 372return*r; 373} 374 375/* 376 * Search for a directory entry directly within dir (without 377 * recursing). Sort dir if necessary. subdirname must be a directory 378 * name (i.e., end in '/'). If mkdir is set, then create the 379 * directory if it is missing; otherwise, return NULL if the desired 380 * directory cannot be found. dir must already be complete. 381 */ 382static struct ref_dir *search_for_subdir(struct ref_dir *dir, 383const char*subdirname,size_t len, 384int mkdir) 385{ 386struct ref_entry *entry =search_ref_dir(dir, subdirname, len); 387if(!entry) { 388if(!mkdir) 389return NULL; 390/* 391 * Since dir is complete, the absence of a subdir 392 * means that the subdir really doesn't exist; 393 * therefore, create an empty record for it but mark 394 * the record complete. 395 */ 396 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 397add_entry_to_dir(dir, entry); 398} 399returnget_ref_dir(entry); 400} 401 402/* 403 * If refname is a reference name, find the ref_dir within the dir 404 * tree that should hold refname. If refname is a directory name 405 * (i.e., ends in '/'), then return that ref_dir itself. dir must 406 * represent the top-level directory and must already be complete. 407 * Sort ref_dirs and recurse into subdirectories as necessary. If 408 * mkdir is set, then create any missing directories; otherwise, 409 * return NULL if the desired directory cannot be found. 410 */ 411static struct ref_dir *find_containing_dir(struct ref_dir *dir, 412const char*refname,int mkdir) 413{ 414const char*slash; 415for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 416size_t dirnamelen = slash - refname +1; 417struct ref_dir *subdir; 418 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 419if(!subdir) { 420 dir = NULL; 421break; 422} 423 dir = subdir; 424} 425 426return dir; 427} 428 429/* 430 * Find the value entry with the given name in dir, sorting ref_dirs 431 * and recursing into subdirectories as necessary. If the name is not 432 * found or it corresponds to a directory entry, return NULL. 433 */ 434static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 435{ 436struct ref_entry *entry; 437 dir =find_containing_dir(dir, refname,0); 438if(!dir) 439return NULL; 440 entry =search_ref_dir(dir, refname,strlen(refname)); 441return(entry && !(entry->flag & REF_DIR)) ? entry : NULL; 442} 443 444/* 445 * Add a ref_entry to the ref_dir (unsorted), recursing into 446 * subdirectories as necessary. dir must represent the top-level 447 * directory. Return 0 on success. 448 */ 449static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 450{ 451 dir =find_containing_dir(dir, ref->name,1); 452if(!dir) 453return-1; 454add_entry_to_dir(dir, ref); 455return0; 456} 457 458/* 459 * Emit a warning and return true iff ref1 and ref2 have the same name 460 * and the same sha1. Die if they have the same name but different 461 * sha1s. 462 */ 463static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 464{ 465if(strcmp(ref1->name, ref2->name)) 466return0; 467 468/* Duplicate name; make sure that they don't conflict: */ 469 470if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 471/* This is impossible by construction */ 472die("Reference directory conflict:%s", ref1->name); 473 474if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 475die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 476 477warning("Duplicated ref:%s", ref1->name); 478return1; 479} 480 481/* 482 * Sort the entries in dir non-recursively (if they are not already 483 * sorted) and remove any duplicate entries. 484 */ 485static voidsort_ref_dir(struct ref_dir *dir) 486{ 487int i, j; 488struct ref_entry *last = NULL; 489 490/* 491 * This check also prevents passing a zero-length array to qsort(), 492 * which is a problem on some platforms. 493 */ 494if(dir->sorted == dir->nr) 495return; 496 497qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 498 499/* Remove any duplicates: */ 500for(i =0, j =0; j < dir->nr; j++) { 501struct ref_entry *entry = dir->entries[j]; 502if(last &&is_dup_ref(last, entry)) 503free_ref_entry(entry); 504else 505 last = dir->entries[i++] = entry; 506} 507 dir->sorted = dir->nr = i; 508} 509 510#define DO_FOR_EACH_INCLUDE_BROKEN 01 511 512static struct ref_entry *current_ref; 513 514static intdo_one_ref(const char*base, each_ref_fn fn,int trim, 515int flags,void*cb_data,struct ref_entry *entry) 516{ 517int retval; 518if(prefixcmp(entry->name, base)) 519return0; 520 521if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) { 522if(entry->flag & REF_ISBROKEN) 523return0;/* ignore broken refs e.g. dangling symref */ 524if(!has_sha1_file(entry->u.value.sha1)) { 525error("%sdoes not point to a valid object!", entry->name); 526return0; 527} 528} 529 current_ref = entry; 530 retval =fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data); 531 current_ref = NULL; 532return retval; 533} 534 535/* 536 * Call fn for each reference in dir that has index in the range 537 * offset <= index < dir->nr. Recurse into subdirectories that are in 538 * that index range, sorting them before iterating. This function 539 * does not sort dir itself; it should be sorted beforehand. 540 */ 541static intdo_for_each_ref_in_dir(struct ref_dir *dir,int offset, 542const char*base, 543 each_ref_fn fn,int trim,int flags,void*cb_data) 544{ 545int i; 546assert(dir->sorted == dir->nr); 547for(i = offset; i < dir->nr; i++) { 548struct ref_entry *entry = dir->entries[i]; 549int retval; 550if(entry->flag & REF_DIR) { 551struct ref_dir *subdir =get_ref_dir(entry); 552sort_ref_dir(subdir); 553 retval =do_for_each_ref_in_dir(subdir,0, 554 base, fn, trim, flags, cb_data); 555}else{ 556 retval =do_one_ref(base, fn, trim, flags, cb_data, entry); 557} 558if(retval) 559return retval; 560} 561return0; 562} 563 564/* 565 * Call fn for each reference in the union of dir1 and dir2, in order 566 * by refname. Recurse into subdirectories. If a value entry appears 567 * in both dir1 and dir2, then only process the version that is in 568 * dir2. The input dirs must already be sorted, but subdirs will be 569 * sorted as needed. 570 */ 571static intdo_for_each_ref_in_dirs(struct ref_dir *dir1, 572struct ref_dir *dir2, 573const char*base, each_ref_fn fn,int trim, 574int flags,void*cb_data) 575{ 576int retval; 577int i1 =0, i2 =0; 578 579assert(dir1->sorted == dir1->nr); 580assert(dir2->sorted == dir2->nr); 581while(1) { 582struct ref_entry *e1, *e2; 583int cmp; 584if(i1 == dir1->nr) { 585returndo_for_each_ref_in_dir(dir2, i2, 586 base, fn, trim, flags, cb_data); 587} 588if(i2 == dir2->nr) { 589returndo_for_each_ref_in_dir(dir1, i1, 590 base, fn, trim, flags, cb_data); 591} 592 e1 = dir1->entries[i1]; 593 e2 = dir2->entries[i2]; 594 cmp =strcmp(e1->name, e2->name); 595if(cmp ==0) { 596if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 597/* Both are directories; descend them in parallel. */ 598struct ref_dir *subdir1 =get_ref_dir(e1); 599struct ref_dir *subdir2 =get_ref_dir(e2); 600sort_ref_dir(subdir1); 601sort_ref_dir(subdir2); 602 retval =do_for_each_ref_in_dirs( 603 subdir1, subdir2, 604 base, fn, trim, flags, cb_data); 605 i1++; 606 i2++; 607}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 608/* Both are references; ignore the one from dir1. */ 609 retval =do_one_ref(base, fn, trim, flags, cb_data, e2); 610 i1++; 611 i2++; 612}else{ 613die("conflict between reference and directory:%s", 614 e1->name); 615} 616}else{ 617struct ref_entry *e; 618if(cmp <0) { 619 e = e1; 620 i1++; 621}else{ 622 e = e2; 623 i2++; 624} 625if(e->flag & REF_DIR) { 626struct ref_dir *subdir =get_ref_dir(e); 627sort_ref_dir(subdir); 628 retval =do_for_each_ref_in_dir( 629 subdir,0, 630 base, fn, trim, flags, cb_data); 631}else{ 632 retval =do_one_ref(base, fn, trim, flags, cb_data, e); 633} 634} 635if(retval) 636return retval; 637} 638if(i1 < dir1->nr) 639returndo_for_each_ref_in_dir(dir1, i1, 640 base, fn, trim, flags, cb_data); 641if(i2 < dir2->nr) 642returndo_for_each_ref_in_dir(dir2, i2, 643 base, fn, trim, flags, cb_data); 644return0; 645} 646 647/* 648 * Return true iff refname1 and refname2 conflict with each other. 649 * Two reference names conflict if one of them exactly matches the 650 * leading components of the other; e.g., "foo/bar" conflicts with 651 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 652 * "foo/barbados". 653 */ 654static intnames_conflict(const char*refname1,const char*refname2) 655{ 656for(; *refname1 && *refname1 == *refname2; refname1++, refname2++) 657; 658return(*refname1 =='\0'&& *refname2 =='/') 659|| (*refname1 =='/'&& *refname2 =='\0'); 660} 661 662struct name_conflict_cb { 663const char*refname; 664const char*oldrefname; 665const char*conflicting_refname; 666}; 667 668static intname_conflict_fn(const char*existingrefname,const unsigned char*sha1, 669int flags,void*cb_data) 670{ 671struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data; 672if(data->oldrefname && !strcmp(data->oldrefname, existingrefname)) 673return0; 674if(names_conflict(data->refname, existingrefname)) { 675 data->conflicting_refname = existingrefname; 676return1; 677} 678return0; 679} 680 681/* 682 * Return true iff a reference named refname could be created without 683 * conflicting with the name of an existing reference in array. If 684 * oldrefname is non-NULL, ignore potential conflicts with oldrefname 685 * (e.g., because oldrefname is scheduled for deletion in the same 686 * operation). 687 */ 688static intis_refname_available(const char*refname,const char*oldrefname, 689struct ref_dir *dir) 690{ 691struct name_conflict_cb data; 692 data.refname = refname; 693 data.oldrefname = oldrefname; 694 data.conflicting_refname = NULL; 695 696sort_ref_dir(dir); 697if(do_for_each_ref_in_dir(dir,0,"", name_conflict_fn, 6980, DO_FOR_EACH_INCLUDE_BROKEN, 699&data)) { 700error("'%s' exists; cannot create '%s'", 701 data.conflicting_refname, refname); 702return0; 703} 704return1; 705} 706 707/* 708 * Future: need to be in "struct repository" 709 * when doing a full libification. 710 */ 711static struct ref_cache { 712struct ref_cache *next; 713struct ref_entry *loose; 714struct ref_entry *packed; 715/* The submodule name, or "" for the main repo. */ 716char name[FLEX_ARRAY]; 717} *ref_cache; 718 719static voidclear_packed_ref_cache(struct ref_cache *refs) 720{ 721if(refs->packed) { 722free_ref_entry(refs->packed); 723 refs->packed = NULL; 724} 725} 726 727static voidclear_loose_ref_cache(struct ref_cache *refs) 728{ 729if(refs->loose) { 730free_ref_entry(refs->loose); 731 refs->loose = NULL; 732} 733} 734 735static struct ref_cache *create_ref_cache(const char*submodule) 736{ 737int len; 738struct ref_cache *refs; 739if(!submodule) 740 submodule =""; 741 len =strlen(submodule) +1; 742 refs =xcalloc(1,sizeof(struct ref_cache) + len); 743memcpy(refs->name, submodule, len); 744return refs; 745} 746 747/* 748 * Return a pointer to a ref_cache for the specified submodule. For 749 * the main repository, use submodule==NULL. The returned structure 750 * will be allocated and initialized but not necessarily populated; it 751 * should not be freed. 752 */ 753static struct ref_cache *get_ref_cache(const char*submodule) 754{ 755struct ref_cache *refs = ref_cache; 756if(!submodule) 757 submodule =""; 758while(refs) { 759if(!strcmp(submodule, refs->name)) 760return refs; 761 refs = refs->next; 762} 763 764 refs =create_ref_cache(submodule); 765 refs->next = ref_cache; 766 ref_cache = refs; 767return refs; 768} 769 770voidinvalidate_ref_cache(const char*submodule) 771{ 772struct ref_cache *refs =get_ref_cache(submodule); 773clear_packed_ref_cache(refs); 774clear_loose_ref_cache(refs); 775} 776 777/* 778 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 779 * Return a pointer to the refname within the line (null-terminated), 780 * or NULL if there was a problem. 781 */ 782static const char*parse_ref_line(char*line,unsigned char*sha1) 783{ 784/* 785 * 42: the answer to everything. 786 * 787 * In this case, it happens to be the answer to 788 * 40 (length of sha1 hex representation) 789 * +1 (space in between hex and name) 790 * +1 (newline at the end of the line) 791 */ 792int len =strlen(line) -42; 793 794if(len <=0) 795return NULL; 796if(get_sha1_hex(line, sha1) <0) 797return NULL; 798if(!isspace(line[40])) 799return NULL; 800 line +=41; 801if(isspace(*line)) 802return NULL; 803if(line[len] !='\n') 804return NULL; 805 line[len] =0; 806 807return line; 808} 809 810/* 811 * Read f, which is a packed-refs file, into dir. 812 * 813 * A comment line of the form "# pack-refs with: " may contain zero or 814 * more traits. We interpret the traits as follows: 815 * 816 * No traits: 817 * 818 * Probably no references are peeled. But if the file contains a 819 * peeled value for a reference, we will use it. 820 * 821 * peeled: 822 * 823 * References under "refs/tags/", if they *can* be peeled, *are* 824 * peeled in this file. References outside of "refs/tags/" are 825 * probably not peeled even if they could have been, but if we find 826 * a peeled value for such a reference we will use it. 827 * 828 * fully-peeled: 829 * 830 * All references in the file that can be peeled are peeled. 831 * Inversely (and this is more important), any references in the 832 * file for which no peeled value is recorded is not peelable. This 833 * trait should typically be written alongside "peeled" for 834 * compatibility with older clients, but we do not require it 835 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 836 */ 837static voidread_packed_refs(FILE*f,struct ref_dir *dir) 838{ 839struct ref_entry *last = NULL; 840char refline[PATH_MAX]; 841enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 842 843while(fgets(refline,sizeof(refline), f)) { 844unsigned char sha1[20]; 845const char*refname; 846static const char header[] ="# pack-refs with:"; 847 848if(!strncmp(refline, header,sizeof(header)-1)) { 849const char*traits = refline +sizeof(header) -1; 850if(strstr(traits," fully-peeled ")) 851 peeled = PEELED_FULLY; 852else if(strstr(traits," peeled ")) 853 peeled = PEELED_TAGS; 854/* perhaps other traits later as well */ 855continue; 856} 857 858 refname =parse_ref_line(refline, sha1); 859if(refname) { 860 last =create_ref_entry(refname, sha1, REF_ISPACKED,1); 861if(peeled == PEELED_FULLY || 862(peeled == PEELED_TAGS && !prefixcmp(refname,"refs/tags/"))) 863 last->flag |= REF_KNOWS_PEELED; 864add_ref(dir, last); 865continue; 866} 867if(last && 868 refline[0] =='^'&& 869strlen(refline) ==42&& 870 refline[41] =='\n'&& 871!get_sha1_hex(refline +1, sha1)) { 872hashcpy(last->u.value.peeled, sha1); 873/* 874 * Regardless of what the file header said, 875 * we definitely know the value of *this* 876 * reference: 877 */ 878 last->flag |= REF_KNOWS_PEELED; 879} 880} 881} 882 883static struct ref_dir *get_packed_refs(struct ref_cache *refs) 884{ 885if(!refs->packed) { 886const char*packed_refs_file; 887FILE*f; 888 889 refs->packed =create_dir_entry(refs,"",0,0); 890if(*refs->name) 891 packed_refs_file =git_path_submodule(refs->name,"packed-refs"); 892else 893 packed_refs_file =git_path("packed-refs"); 894 f =fopen(packed_refs_file,"r"); 895if(f) { 896read_packed_refs(f,get_ref_dir(refs->packed)); 897fclose(f); 898} 899} 900returnget_ref_dir(refs->packed); 901} 902 903voidadd_packed_ref(const char*refname,const unsigned char*sha1) 904{ 905add_ref(get_packed_refs(get_ref_cache(NULL)), 906create_ref_entry(refname, sha1, REF_ISPACKED,1)); 907} 908 909/* 910 * Read the loose references from the namespace dirname into dir 911 * (without recursing). dirname must end with '/'. dir must be the 912 * directory entry corresponding to dirname. 913 */ 914static voidread_loose_refs(const char*dirname,struct ref_dir *dir) 915{ 916struct ref_cache *refs = dir->ref_cache; 917DIR*d; 918const char*path; 919struct dirent *de; 920int dirnamelen =strlen(dirname); 921struct strbuf refname; 922 923if(*refs->name) 924 path =git_path_submodule(refs->name,"%s", dirname); 925else 926 path =git_path("%s", dirname); 927 928 d =opendir(path); 929if(!d) 930return; 931 932strbuf_init(&refname, dirnamelen +257); 933strbuf_add(&refname, dirname, dirnamelen); 934 935while((de =readdir(d)) != NULL) { 936unsigned char sha1[20]; 937struct stat st; 938int flag; 939const char*refdir; 940 941if(de->d_name[0] =='.') 942continue; 943if(has_extension(de->d_name,".lock")) 944continue; 945strbuf_addstr(&refname, de->d_name); 946 refdir = *refs->name 947?git_path_submodule(refs->name,"%s", refname.buf) 948:git_path("%s", refname.buf); 949if(stat(refdir, &st) <0) { 950;/* silently ignore */ 951}else if(S_ISDIR(st.st_mode)) { 952strbuf_addch(&refname,'/'); 953add_entry_to_dir(dir, 954create_dir_entry(refs, refname.buf, 955 refname.len,1)); 956}else{ 957if(*refs->name) { 958hashclr(sha1); 959 flag =0; 960if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) { 961hashclr(sha1); 962 flag |= REF_ISBROKEN; 963} 964}else if(read_ref_full(refname.buf, sha1,1, &flag)) { 965hashclr(sha1); 966 flag |= REF_ISBROKEN; 967} 968add_entry_to_dir(dir, 969create_ref_entry(refname.buf, sha1, flag,1)); 970} 971strbuf_setlen(&refname, dirnamelen); 972} 973strbuf_release(&refname); 974closedir(d); 975} 976 977static struct ref_dir *get_loose_refs(struct ref_cache *refs) 978{ 979if(!refs->loose) { 980/* 981 * Mark the top-level directory complete because we 982 * are about to read the only subdirectory that can 983 * hold references: 984 */ 985 refs->loose =create_dir_entry(refs,"",0,0); 986/* 987 * Create an incomplete entry for "refs/": 988 */ 989add_entry_to_dir(get_ref_dir(refs->loose), 990create_dir_entry(refs,"refs/",5,1)); 991} 992returnget_ref_dir(refs->loose); 993} 994 995/* We allow "recursive" symbolic refs. Only within reason, though */ 996#define MAXDEPTH 5 997#define MAXREFLEN (1024) 998 999/*1000 * Called by resolve_gitlink_ref_recursive() after it failed to read1001 * from the loose refs in ref_cache refs. Find <refname> in the1002 * packed-refs file for the submodule.1003 */1004static intresolve_gitlink_packed_ref(struct ref_cache *refs,1005const char*refname,unsigned char*sha1)1006{1007struct ref_entry *ref;1008struct ref_dir *dir =get_packed_refs(refs);10091010 ref =find_ref(dir, refname);1011if(ref == NULL)1012return-1;10131014memcpy(sha1, ref->u.value.sha1,20);1015return0;1016}10171018static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1019const char*refname,unsigned char*sha1,1020int recursion)1021{1022int fd, len;1023char buffer[128], *p;1024char*path;10251026if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1027return-1;1028 path = *refs->name1029?git_path_submodule(refs->name,"%s", refname)1030:git_path("%s", refname);1031 fd =open(path, O_RDONLY);1032if(fd <0)1033returnresolve_gitlink_packed_ref(refs, refname, sha1);10341035 len =read(fd, buffer,sizeof(buffer)-1);1036close(fd);1037if(len <0)1038return-1;1039while(len &&isspace(buffer[len-1]))1040 len--;1041 buffer[len] =0;10421043/* Was it a detached head or an old-fashioned symlink? */1044if(!get_sha1_hex(buffer, sha1))1045return0;10461047/* Symref? */1048if(strncmp(buffer,"ref:",4))1049return-1;1050 p = buffer +4;1051while(isspace(*p))1052 p++;10531054returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1055}10561057intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1058{1059int len =strlen(path), retval;1060char*submodule;1061struct ref_cache *refs;10621063while(len && path[len-1] =='/')1064 len--;1065if(!len)1066return-1;1067 submodule =xstrndup(path, len);1068 refs =get_ref_cache(submodule);1069free(submodule);10701071 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1072return retval;1073}10741075/*1076 * Try to read ref from the packed references. On success, set sha11077 * and return 0; otherwise, return -1.1078 */1079static intget_packed_ref(const char*refname,unsigned char*sha1)1080{1081struct ref_dir *packed =get_packed_refs(get_ref_cache(NULL));1082struct ref_entry *entry =find_ref(packed, refname);1083if(entry) {1084hashcpy(sha1, entry->u.value.sha1);1085return0;1086}1087return-1;1088}10891090const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1091{1092int depth = MAXDEPTH;1093 ssize_t len;1094char buffer[256];1095static char refname_buffer[256];10961097if(flag)1098*flag =0;10991100if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))1101return NULL;11021103for(;;) {1104char path[PATH_MAX];1105struct stat st;1106char*buf;1107int fd;11081109if(--depth <0)1110return NULL;11111112git_snpath(path,sizeof(path),"%s", refname);11131114if(lstat(path, &st) <0) {1115if(errno != ENOENT)1116return NULL;1117/*1118 * The loose reference file does not exist;1119 * check for a packed reference.1120 */1121if(!get_packed_ref(refname, sha1)) {1122if(flag)1123*flag |= REF_ISPACKED;1124return refname;1125}1126/* The reference is not a packed reference, either. */1127if(reading) {1128return NULL;1129}else{1130hashclr(sha1);1131return refname;1132}1133}11341135/* Follow "normalized" - ie "refs/.." symlinks by hand */1136if(S_ISLNK(st.st_mode)) {1137 len =readlink(path, buffer,sizeof(buffer)-1);1138if(len <0)1139return NULL;1140 buffer[len] =0;1141if(!prefixcmp(buffer,"refs/") &&1142!check_refname_format(buffer,0)) {1143strcpy(refname_buffer, buffer);1144 refname = refname_buffer;1145if(flag)1146*flag |= REF_ISSYMREF;1147continue;1148}1149}11501151/* Is it a directory? */1152if(S_ISDIR(st.st_mode)) {1153 errno = EISDIR;1154return NULL;1155}11561157/*1158 * Anything else, just open it and try to use it as1159 * a ref1160 */1161 fd =open(path, O_RDONLY);1162if(fd <0)1163return NULL;1164 len =read_in_full(fd, buffer,sizeof(buffer)-1);1165close(fd);1166if(len <0)1167return NULL;1168while(len &&isspace(buffer[len-1]))1169 len--;1170 buffer[len] ='\0';11711172/*1173 * Is it a symbolic ref?1174 */1175if(prefixcmp(buffer,"ref:"))1176break;1177if(flag)1178*flag |= REF_ISSYMREF;1179 buf = buffer +4;1180while(isspace(*buf))1181 buf++;1182if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1183if(flag)1184*flag |= REF_ISBROKEN;1185return NULL;1186}1187 refname =strcpy(refname_buffer, buf);1188}1189/* Please note that FETCH_HEAD has a second line containing other data. */1190if(get_sha1_hex(buffer, sha1) || (buffer[40] !='\0'&& !isspace(buffer[40]))) {1191if(flag)1192*flag |= REF_ISBROKEN;1193return NULL;1194}1195return refname;1196}11971198char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1199{1200const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1201return ret ?xstrdup(ret) : NULL;1202}12031204/* The argument to filter_refs */1205struct ref_filter {1206const char*pattern;1207 each_ref_fn *fn;1208void*cb_data;1209};12101211intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1212{1213if(resolve_ref_unsafe(refname, sha1, reading, flags))1214return0;1215return-1;1216}12171218intread_ref(const char*refname,unsigned char*sha1)1219{1220returnread_ref_full(refname, sha1,1, NULL);1221}12221223intref_exists(const char*refname)1224{1225unsigned char sha1[20];1226return!!resolve_ref_unsafe(refname, sha1,1, NULL);1227}12281229static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1230void*data)1231{1232struct ref_filter *filter = (struct ref_filter *)data;1233if(fnmatch(filter->pattern, refname,0))1234return0;1235return filter->fn(refname, sha1, flags, filter->cb_data);1236}12371238intpeel_ref(const char*refname,unsigned char*sha1)1239{1240int flag;1241unsigned char base[20];1242struct object *o;12431244if(current_ref && (current_ref->name == refname1245|| !strcmp(current_ref->name, refname))) {1246if(current_ref->flag & REF_KNOWS_PEELED) {1247if(is_null_sha1(current_ref->u.value.peeled))1248return-1;1249hashcpy(sha1, current_ref->u.value.peeled);1250return0;1251}1252hashcpy(base, current_ref->u.value.sha1);1253goto fallback;1254}12551256if(read_ref_full(refname, base,1, &flag))1257return-1;12581259if((flag & REF_ISPACKED)) {1260struct ref_dir *dir =get_packed_refs(get_ref_cache(NULL));1261struct ref_entry *r =find_ref(dir, refname);12621263if(r != NULL && r->flag & REF_KNOWS_PEELED) {1264hashcpy(sha1, r->u.value.peeled);1265return0;1266}1267}12681269fallback:1270 o =lookup_unknown_object(base);1271if(o->type == OBJ_NONE) {1272int type =sha1_object_info(base, NULL);1273if(type <0)1274return-1;1275 o->type = type;1276}12771278if(o->type == OBJ_TAG) {1279 o =deref_tag_noverify(o);1280if(o) {1281hashcpy(sha1, o->sha1);1282return0;1283}1284}1285return-1;1286}12871288struct warn_if_dangling_data {1289FILE*fp;1290const char*refname;1291const char*msg_fmt;1292};12931294static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1295int flags,void*cb_data)1296{1297struct warn_if_dangling_data *d = cb_data;1298const char*resolves_to;1299unsigned char junk[20];13001301if(!(flags & REF_ISSYMREF))1302return0;13031304 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1305if(!resolves_to ||strcmp(resolves_to, d->refname))1306return0;13071308fprintf(d->fp, d->msg_fmt, refname);1309fputc('\n', d->fp);1310return0;1311}13121313voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1314{1315struct warn_if_dangling_data data;13161317 data.fp = fp;1318 data.refname = refname;1319 data.msg_fmt = msg_fmt;1320for_each_rawref(warn_if_dangling_symref, &data);1321}13221323static intdo_for_each_ref(const char*submodule,const char*base, each_ref_fn fn,1324int trim,int flags,void*cb_data)1325{1326struct ref_cache *refs =get_ref_cache(submodule);1327struct ref_dir *packed_dir =get_packed_refs(refs);1328struct ref_dir *loose_dir =get_loose_refs(refs);1329int retval =0;13301331if(base && *base) {1332 packed_dir =find_containing_dir(packed_dir, base,0);1333 loose_dir =find_containing_dir(loose_dir, base,0);1334}13351336if(packed_dir && loose_dir) {1337sort_ref_dir(packed_dir);1338sort_ref_dir(loose_dir);1339 retval =do_for_each_ref_in_dirs(1340 packed_dir, loose_dir,1341 base, fn, trim, flags, cb_data);1342}else if(packed_dir) {1343sort_ref_dir(packed_dir);1344 retval =do_for_each_ref_in_dir(1345 packed_dir,0,1346 base, fn, trim, flags, cb_data);1347}else if(loose_dir) {1348sort_ref_dir(loose_dir);1349 retval =do_for_each_ref_in_dir(1350 loose_dir,0,1351 base, fn, trim, flags, cb_data);1352}13531354return retval;1355}13561357static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1358{1359unsigned char sha1[20];1360int flag;13611362if(submodule) {1363if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1364returnfn("HEAD", sha1,0, cb_data);13651366return0;1367}13681369if(!read_ref_full("HEAD", sha1,1, &flag))1370returnfn("HEAD", sha1, flag, cb_data);13711372return0;1373}13741375inthead_ref(each_ref_fn fn,void*cb_data)1376{1377returndo_head_ref(NULL, fn, cb_data);1378}13791380inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1381{1382returndo_head_ref(submodule, fn, cb_data);1383}13841385intfor_each_ref(each_ref_fn fn,void*cb_data)1386{1387returndo_for_each_ref(NULL,"", fn,0,0, cb_data);1388}13891390intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1391{1392returndo_for_each_ref(submodule,"", fn,0,0, cb_data);1393}13941395intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1396{1397returndo_for_each_ref(NULL, prefix, fn,strlen(prefix),0, cb_data);1398}13991400intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1401 each_ref_fn fn,void*cb_data)1402{1403returndo_for_each_ref(submodule, prefix, fn,strlen(prefix),0, cb_data);1404}14051406intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1407{1408returnfor_each_ref_in("refs/tags/", fn, cb_data);1409}14101411intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1412{1413returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1414}14151416intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1417{1418returnfor_each_ref_in("refs/heads/", fn, cb_data);1419}14201421intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1422{1423returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1424}14251426intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1427{1428returnfor_each_ref_in("refs/remotes/", fn, cb_data);1429}14301431intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1432{1433returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1434}14351436intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1437{1438returndo_for_each_ref(NULL,"refs/replace/", fn,13,0, cb_data);1439}14401441inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1442{1443struct strbuf buf = STRBUF_INIT;1444int ret =0;1445unsigned char sha1[20];1446int flag;14471448strbuf_addf(&buf,"%sHEAD",get_git_namespace());1449if(!read_ref_full(buf.buf, sha1,1, &flag))1450 ret =fn(buf.buf, sha1, flag, cb_data);1451strbuf_release(&buf);14521453return ret;1454}14551456intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1457{1458struct strbuf buf = STRBUF_INIT;1459int ret;1460strbuf_addf(&buf,"%srefs/",get_git_namespace());1461 ret =do_for_each_ref(NULL, buf.buf, fn,0,0, cb_data);1462strbuf_release(&buf);1463return ret;1464}14651466intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1467const char*prefix,void*cb_data)1468{1469struct strbuf real_pattern = STRBUF_INIT;1470struct ref_filter filter;1471int ret;14721473if(!prefix &&prefixcmp(pattern,"refs/"))1474strbuf_addstr(&real_pattern,"refs/");1475else if(prefix)1476strbuf_addstr(&real_pattern, prefix);1477strbuf_addstr(&real_pattern, pattern);14781479if(!has_glob_specials(pattern)) {1480/* Append implied '/' '*' if not present. */1481if(real_pattern.buf[real_pattern.len -1] !='/')1482strbuf_addch(&real_pattern,'/');1483/* No need to check for '*', there is none. */1484strbuf_addch(&real_pattern,'*');1485}14861487 filter.pattern = real_pattern.buf;1488 filter.fn = fn;1489 filter.cb_data = cb_data;1490 ret =for_each_ref(filter_refs, &filter);14911492strbuf_release(&real_pattern);1493return ret;1494}14951496intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1497{1498returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1499}15001501intfor_each_rawref(each_ref_fn fn,void*cb_data)1502{1503returndo_for_each_ref(NULL,"", fn,0,1504 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1505}15061507const char*prettify_refname(const char*name)1508{1509return name + (1510!prefixcmp(name,"refs/heads/") ?11:1511!prefixcmp(name,"refs/tags/") ?10:1512!prefixcmp(name,"refs/remotes/") ?13:15130);1514}15151516const char*ref_rev_parse_rules[] = {1517"%.*s",1518"refs/%.*s",1519"refs/tags/%.*s",1520"refs/heads/%.*s",1521"refs/remotes/%.*s",1522"refs/remotes/%.*s/HEAD",1523 NULL1524};15251526intrefname_match(const char*abbrev_name,const char*full_name,const char**rules)1527{1528const char**p;1529const int abbrev_name_len =strlen(abbrev_name);15301531for(p = rules; *p; p++) {1532if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {1533return1;1534}1535}15361537return0;1538}15391540static struct ref_lock *verify_lock(struct ref_lock *lock,1541const unsigned char*old_sha1,int mustexist)1542{1543if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {1544error("Can't verify ref%s", lock->ref_name);1545unlock_ref(lock);1546return NULL;1547}1548if(hashcmp(lock->old_sha1, old_sha1)) {1549error("Ref%sis at%sbut expected%s", lock->ref_name,1550sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));1551unlock_ref(lock);1552return NULL;1553}1554return lock;1555}15561557static intremove_empty_directories(const char*file)1558{1559/* we want to create a file but there is a directory there;1560 * if that is an empty directory (or a directory that contains1561 * only empty directories), remove them.1562 */1563struct strbuf path;1564int result;15651566strbuf_init(&path,20);1567strbuf_addstr(&path, file);15681569 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);15701571strbuf_release(&path);15721573return result;1574}15751576/*1577 * *string and *len will only be substituted, and *string returned (for1578 * later free()ing) if the string passed in is a magic short-hand form1579 * to name a branch.1580 */1581static char*substitute_branch_name(const char**string,int*len)1582{1583struct strbuf buf = STRBUF_INIT;1584int ret =interpret_branch_name(*string, &buf);15851586if(ret == *len) {1587size_t size;1588*string =strbuf_detach(&buf, &size);1589*len = size;1590return(char*)*string;1591}15921593return NULL;1594}15951596intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)1597{1598char*last_branch =substitute_branch_name(&str, &len);1599const char**p, *r;1600int refs_found =0;16011602*ref = NULL;1603for(p = ref_rev_parse_rules; *p; p++) {1604char fullref[PATH_MAX];1605unsigned char sha1_from_ref[20];1606unsigned char*this_result;1607int flag;16081609 this_result = refs_found ? sha1_from_ref : sha1;1610mksnpath(fullref,sizeof(fullref), *p, len, str);1611 r =resolve_ref_unsafe(fullref, this_result,1, &flag);1612if(r) {1613if(!refs_found++)1614*ref =xstrdup(r);1615if(!warn_ambiguous_refs)1616break;1617}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {1618warning("ignoring dangling symref%s.", fullref);1619}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {1620warning("ignoring broken ref%s.", fullref);1621}1622}1623free(last_branch);1624return refs_found;1625}16261627intdwim_log(const char*str,int len,unsigned char*sha1,char**log)1628{1629char*last_branch =substitute_branch_name(&str, &len);1630const char**p;1631int logs_found =0;16321633*log = NULL;1634for(p = ref_rev_parse_rules; *p; p++) {1635struct stat st;1636unsigned char hash[20];1637char path[PATH_MAX];1638const char*ref, *it;16391640mksnpath(path,sizeof(path), *p, len, str);1641 ref =resolve_ref_unsafe(path, hash,1, NULL);1642if(!ref)1643continue;1644if(!stat(git_path("logs/%s", path), &st) &&1645S_ISREG(st.st_mode))1646 it = path;1647else if(strcmp(ref, path) &&1648!stat(git_path("logs/%s", ref), &st) &&1649S_ISREG(st.st_mode))1650 it = ref;1651else1652continue;1653if(!logs_found++) {1654*log =xstrdup(it);1655hashcpy(sha1, hash);1656}1657if(!warn_ambiguous_refs)1658break;1659}1660free(last_branch);1661return logs_found;1662}16631664static struct ref_lock *lock_ref_sha1_basic(const char*refname,1665const unsigned char*old_sha1,1666int flags,int*type_p)1667{1668char*ref_file;1669const char*orig_refname = refname;1670struct ref_lock *lock;1671int last_errno =0;1672int type, lflags;1673int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1674int missing =0;16751676 lock =xcalloc(1,sizeof(struct ref_lock));1677 lock->lock_fd = -1;16781679 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);1680if(!refname && errno == EISDIR) {1681/* we are trying to lock foo but we used to1682 * have foo/bar which now does not exist;1683 * it is normal for the empty directory 'foo'1684 * to remain.1685 */1686 ref_file =git_path("%s", orig_refname);1687if(remove_empty_directories(ref_file)) {1688 last_errno = errno;1689error("there are still refs under '%s'", orig_refname);1690goto error_return;1691}1692 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);1693}1694if(type_p)1695*type_p = type;1696if(!refname) {1697 last_errno = errno;1698error("unable to resolve reference%s:%s",1699 orig_refname,strerror(errno));1700goto error_return;1701}1702 missing =is_null_sha1(lock->old_sha1);1703/* When the ref did not exist and we are creating it,1704 * make sure there is no existing ref that is packed1705 * whose name begins with our refname, nor a ref whose1706 * name is a proper prefix of our refname.1707 */1708if(missing &&1709!is_refname_available(refname, NULL,get_packed_refs(get_ref_cache(NULL)))) {1710 last_errno = ENOTDIR;1711goto error_return;1712}17131714 lock->lk =xcalloc(1,sizeof(struct lock_file));17151716 lflags = LOCK_DIE_ON_ERROR;1717if(flags & REF_NODEREF) {1718 refname = orig_refname;1719 lflags |= LOCK_NODEREF;1720}1721 lock->ref_name =xstrdup(refname);1722 lock->orig_ref_name =xstrdup(orig_refname);1723 ref_file =git_path("%s", refname);1724if(missing)1725 lock->force_write =1;1726if((flags & REF_NODEREF) && (type & REF_ISSYMREF))1727 lock->force_write =1;17281729if(safe_create_leading_directories(ref_file)) {1730 last_errno = errno;1731error("unable to create directory for%s", ref_file);1732goto error_return;1733}17341735 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);1736return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;17371738 error_return:1739unlock_ref(lock);1740 errno = last_errno;1741return NULL;1742}17431744struct ref_lock *lock_ref_sha1(const char*refname,const unsigned char*old_sha1)1745{1746char refpath[PATH_MAX];1747if(check_refname_format(refname,0))1748return NULL;1749strcpy(refpath,mkpath("refs/%s", refname));1750returnlock_ref_sha1_basic(refpath, old_sha1,0, NULL);1751}17521753struct ref_lock *lock_any_ref_for_update(const char*refname,1754const unsigned char*old_sha1,int flags)1755{1756if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))1757return NULL;1758returnlock_ref_sha1_basic(refname, old_sha1, flags, NULL);1759}17601761struct repack_without_ref_sb {1762const char*refname;1763int fd;1764};17651766static intrepack_without_ref_fn(const char*refname,const unsigned char*sha1,1767int flags,void*cb_data)1768{1769struct repack_without_ref_sb *data = cb_data;1770char line[PATH_MAX +100];1771int len;17721773if(!strcmp(data->refname, refname))1774return0;1775 len =snprintf(line,sizeof(line),"%s %s\n",1776sha1_to_hex(sha1), refname);1777/* this should not happen but just being defensive */1778if(len >sizeof(line))1779die("too long a refname '%s'", refname);1780write_or_die(data->fd, line, len);1781return0;1782}17831784static struct lock_file packlock;17851786static intrepack_without_ref(const char*refname)1787{1788struct repack_without_ref_sb data;1789struct ref_cache *refs =get_ref_cache(NULL);1790struct ref_dir *packed =get_packed_refs(refs);1791if(find_ref(packed, refname) == NULL)1792return0;1793 data.refname = refname;1794 data.fd =hold_lock_file_for_update(&packlock,git_path("packed-refs"),0);1795if(data.fd <0) {1796unable_to_lock_error(git_path("packed-refs"), errno);1797returnerror("cannot delete '%s' from packed refs", refname);1798}1799clear_packed_ref_cache(refs);1800 packed =get_packed_refs(refs);1801do_for_each_ref_in_dir(packed,0,"", repack_without_ref_fn,0,0, &data);1802returncommit_lock_file(&packlock);1803}18041805intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)1806{1807struct ref_lock *lock;1808int err, i =0, ret =0, flag =0;18091810 lock =lock_ref_sha1_basic(refname, sha1, delopt, &flag);1811if(!lock)1812return1;1813if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {1814/* loose */1815 i =strlen(lock->lk->filename) -5;/* .lock */1816 lock->lk->filename[i] =0;1817 err =unlink_or_warn(lock->lk->filename);1818if(err && errno != ENOENT)1819 ret =1;18201821 lock->lk->filename[i] ='.';1822}1823/* removing the loose one could have resurrected an earlier1824 * packed one. Also, if it was not loose we need to repack1825 * without it.1826 */1827 ret |=repack_without_ref(lock->ref_name);18281829unlink_or_warn(git_path("logs/%s", lock->ref_name));1830invalidate_ref_cache(NULL);1831unlock_ref(lock);1832return ret;1833}18341835/*1836 * People using contrib's git-new-workdir have .git/logs/refs ->1837 * /some/other/path/.git/logs/refs, and that may live on another device.1838 *1839 * IOW, to avoid cross device rename errors, the temporary renamed log must1840 * live into logs/refs.1841 */1842#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"18431844intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)1845{1846unsigned char sha1[20], orig_sha1[20];1847int flag =0, logmoved =0;1848struct ref_lock *lock;1849struct stat loginfo;1850int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);1851const char*symref = NULL;1852struct ref_cache *refs =get_ref_cache(NULL);18531854if(log &&S_ISLNK(loginfo.st_mode))1855returnerror("reflog for%sis a symlink", oldrefname);18561857 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);1858if(flag & REF_ISSYMREF)1859returnerror("refname%sis a symbolic ref, renaming it is not supported",1860 oldrefname);1861if(!symref)1862returnerror("refname%snot found", oldrefname);18631864if(!is_refname_available(newrefname, oldrefname,get_packed_refs(refs)))1865return1;18661867if(!is_refname_available(newrefname, oldrefname,get_loose_refs(refs)))1868return1;18691870if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))1871returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",1872 oldrefname,strerror(errno));18731874if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {1875error("unable to delete old%s", oldrefname);1876goto rollback;1877}18781879if(!read_ref_full(newrefname, sha1,1, &flag) &&1880delete_ref(newrefname, sha1, REF_NODEREF)) {1881if(errno==EISDIR) {1882if(remove_empty_directories(git_path("%s", newrefname))) {1883error("Directory not empty:%s", newrefname);1884goto rollback;1885}1886}else{1887error("unable to delete existing%s", newrefname);1888goto rollback;1889}1890}18911892if(log &&safe_create_leading_directories(git_path("logs/%s", newrefname))) {1893error("unable to create directory for%s", newrefname);1894goto rollback;1895}18961897 retry:1898if(log &&rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {1899if(errno==EISDIR || errno==ENOTDIR) {1900/*1901 * rename(a, b) when b is an existing1902 * directory ought to result in ISDIR, but1903 * Solaris 5.8 gives ENOTDIR. Sheesh.1904 */1905if(remove_empty_directories(git_path("logs/%s", newrefname))) {1906error("Directory not empty: logs/%s", newrefname);1907goto rollback;1908}1909goto retry;1910}else{1911error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",1912 newrefname,strerror(errno));1913goto rollback;1914}1915}1916 logmoved = log;19171918 lock =lock_ref_sha1_basic(newrefname, NULL,0, NULL);1919if(!lock) {1920error("unable to lock%sfor update", newrefname);1921goto rollback;1922}1923 lock->force_write =1;1924hashcpy(lock->old_sha1, orig_sha1);1925if(write_ref_sha1(lock, orig_sha1, logmsg)) {1926error("unable to write current sha1 into%s", newrefname);1927goto rollback;1928}19291930return0;19311932 rollback:1933 lock =lock_ref_sha1_basic(oldrefname, NULL,0, NULL);1934if(!lock) {1935error("unable to lock%sfor rollback", oldrefname);1936goto rollbacklog;1937}19381939 lock->force_write =1;1940 flag = log_all_ref_updates;1941 log_all_ref_updates =0;1942if(write_ref_sha1(lock, orig_sha1, NULL))1943error("unable to write current sha1 into%s", oldrefname);1944 log_all_ref_updates = flag;19451946 rollbacklog:1947if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))1948error("unable to restore logfile%sfrom%s:%s",1949 oldrefname, newrefname,strerror(errno));1950if(!logmoved && log &&1951rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))1952error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",1953 oldrefname,strerror(errno));19541955return1;1956}19571958intclose_ref(struct ref_lock *lock)1959{1960if(close_lock_file(lock->lk))1961return-1;1962 lock->lock_fd = -1;1963return0;1964}19651966intcommit_ref(struct ref_lock *lock)1967{1968if(commit_lock_file(lock->lk))1969return-1;1970 lock->lock_fd = -1;1971return0;1972}19731974voidunlock_ref(struct ref_lock *lock)1975{1976/* Do not free lock->lk -- atexit() still looks at them */1977if(lock->lk)1978rollback_lock_file(lock->lk);1979free(lock->ref_name);1980free(lock->orig_ref_name);1981free(lock);1982}19831984/*1985 * copy the reflog message msg to buf, which has been allocated sufficiently1986 * large, while cleaning up the whitespaces. Especially, convert LF to space,1987 * because reflog file is one line per entry.1988 */1989static intcopy_msg(char*buf,const char*msg)1990{1991char*cp = buf;1992char c;1993int wasspace =1;19941995*cp++ ='\t';1996while((c = *msg++)) {1997if(wasspace &&isspace(c))1998continue;1999 wasspace =isspace(c);2000if(wasspace)2001 c =' ';2002*cp++ = c;2003}2004while(buf < cp &&isspace(cp[-1]))2005 cp--;2006*cp++ ='\n';2007return cp - buf;2008}20092010intlog_ref_setup(const char*refname,char*logfile,int bufsize)2011{2012int logfd, oflags = O_APPEND | O_WRONLY;20132014git_snpath(logfile, bufsize,"logs/%s", refname);2015if(log_all_ref_updates &&2016(!prefixcmp(refname,"refs/heads/") ||2017!prefixcmp(refname,"refs/remotes/") ||2018!prefixcmp(refname,"refs/notes/") ||2019!strcmp(refname,"HEAD"))) {2020if(safe_create_leading_directories(logfile) <0)2021returnerror("unable to create directory for%s",2022 logfile);2023 oflags |= O_CREAT;2024}20252026 logfd =open(logfile, oflags,0666);2027if(logfd <0) {2028if(!(oflags & O_CREAT) && errno == ENOENT)2029return0;20302031if((oflags & O_CREAT) && errno == EISDIR) {2032if(remove_empty_directories(logfile)) {2033returnerror("There are still logs under '%s'",2034 logfile);2035}2036 logfd =open(logfile, oflags,0666);2037}20382039if(logfd <0)2040returnerror("Unable to append to%s:%s",2041 logfile,strerror(errno));2042}20432044adjust_shared_perm(logfile);2045close(logfd);2046return0;2047}20482049static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2050const unsigned char*new_sha1,const char*msg)2051{2052int logfd, result, written, oflags = O_APPEND | O_WRONLY;2053unsigned maxlen, len;2054int msglen;2055char log_file[PATH_MAX];2056char*logrec;2057const char*committer;20582059if(log_all_ref_updates <0)2060 log_all_ref_updates = !is_bare_repository();20612062 result =log_ref_setup(refname, log_file,sizeof(log_file));2063if(result)2064return result;20652066 logfd =open(log_file, oflags);2067if(logfd <0)2068return0;2069 msglen = msg ?strlen(msg) :0;2070 committer =git_committer_info(0);2071 maxlen =strlen(committer) + msglen +100;2072 logrec =xmalloc(maxlen);2073 len =sprintf(logrec,"%s %s %s\n",2074sha1_to_hex(old_sha1),2075sha1_to_hex(new_sha1),2076 committer);2077if(msglen)2078 len +=copy_msg(logrec + len -1, msg) -1;2079 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2080free(logrec);2081if(close(logfd) !=0|| written != len)2082returnerror("Unable to append to%s", log_file);2083return0;2084}20852086static intis_branch(const char*refname)2087{2088return!strcmp(refname,"HEAD") || !prefixcmp(refname,"refs/heads/");2089}20902091intwrite_ref_sha1(struct ref_lock *lock,2092const unsigned char*sha1,const char*logmsg)2093{2094static char term ='\n';2095struct object *o;20962097if(!lock)2098return-1;2099if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2100unlock_ref(lock);2101return0;2102}2103 o =parse_object(sha1);2104if(!o) {2105error("Trying to write ref%swith nonexistent object%s",2106 lock->ref_name,sha1_to_hex(sha1));2107unlock_ref(lock);2108return-1;2109}2110if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2111error("Trying to write non-commit object%sto branch%s",2112sha1_to_hex(sha1), lock->ref_name);2113unlock_ref(lock);2114return-1;2115}2116if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||2117write_in_full(lock->lock_fd, &term,1) !=12118||close_ref(lock) <0) {2119error("Couldn't write%s", lock->lk->filename);2120unlock_ref(lock);2121return-1;2122}2123clear_loose_ref_cache(get_ref_cache(NULL));2124if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||2125(strcmp(lock->ref_name, lock->orig_ref_name) &&2126log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {2127unlock_ref(lock);2128return-1;2129}2130if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2131/*2132 * Special hack: If a branch is updated directly and HEAD2133 * points to it (may happen on the remote side of a push2134 * for example) then logically the HEAD reflog should be2135 * updated too.2136 * A generic solution implies reverse symref information,2137 * but finding all symrefs pointing to the given branch2138 * would be rather costly for this rare event (the direct2139 * update of a branch) to be worth it. So let's cheat and2140 * check with HEAD only which should cover 99% of all usage2141 * scenarios (even 100% of the default ones).2142 */2143unsigned char head_sha1[20];2144int head_flag;2145const char*head_ref;2146 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);2147if(head_ref && (head_flag & REF_ISSYMREF) &&2148!strcmp(head_ref, lock->ref_name))2149log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);2150}2151if(commit_ref(lock)) {2152error("Couldn't set%s", lock->ref_name);2153unlock_ref(lock);2154return-1;2155}2156unlock_ref(lock);2157return0;2158}21592160intcreate_symref(const char*ref_target,const char*refs_heads_master,2161const char*logmsg)2162{2163const char*lockpath;2164char ref[1000];2165int fd, len, written;2166char*git_HEAD =git_pathdup("%s", ref_target);2167unsigned char old_sha1[20], new_sha1[20];21682169if(logmsg &&read_ref(ref_target, old_sha1))2170hashclr(old_sha1);21712172if(safe_create_leading_directories(git_HEAD) <0)2173returnerror("unable to create directory for%s", git_HEAD);21742175#ifndef NO_SYMLINK_HEAD2176if(prefer_symlink_refs) {2177unlink(git_HEAD);2178if(!symlink(refs_heads_master, git_HEAD))2179goto done;2180fprintf(stderr,"no symlink - falling back to symbolic ref\n");2181}2182#endif21832184 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);2185if(sizeof(ref) <= len) {2186error("refname too long:%s", refs_heads_master);2187goto error_free_return;2188}2189 lockpath =mkpath("%s.lock", git_HEAD);2190 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);2191if(fd <0) {2192error("Unable to open%sfor writing", lockpath);2193goto error_free_return;2194}2195 written =write_in_full(fd, ref, len);2196if(close(fd) !=0|| written != len) {2197error("Unable to write to%s", lockpath);2198goto error_unlink_return;2199}2200if(rename(lockpath, git_HEAD) <0) {2201error("Unable to create%s", git_HEAD);2202goto error_unlink_return;2203}2204if(adjust_shared_perm(git_HEAD)) {2205error("Unable to fix permissions on%s", lockpath);2206 error_unlink_return:2207unlink_or_warn(lockpath);2208 error_free_return:2209free(git_HEAD);2210return-1;2211}22122213#ifndef NO_SYMLINK_HEAD2214 done:2215#endif2216if(logmsg && !read_ref(refs_heads_master, new_sha1))2217log_ref_write(ref_target, old_sha1, new_sha1, logmsg);22182219free(git_HEAD);2220return0;2221}22222223static char*ref_msg(const char*line,const char*endp)2224{2225const char*ep;2226 line +=82;2227 ep =memchr(line,'\n', endp - line);2228if(!ep)2229 ep = endp;2230returnxmemdupz(line, ep - line);2231}22322233intread_ref_at(const char*refname,unsigned long at_time,int cnt,2234unsigned char*sha1,char**msg,2235unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)2236{2237const char*logfile, *logdata, *logend, *rec, *lastgt, *lastrec;2238char*tz_c;2239int logfd, tz, reccnt =0;2240struct stat st;2241unsigned long date;2242unsigned char logged_sha1[20];2243void*log_mapped;2244size_t mapsz;22452246 logfile =git_path("logs/%s", refname);2247 logfd =open(logfile, O_RDONLY,0);2248if(logfd <0)2249die_errno("Unable to read log '%s'", logfile);2250fstat(logfd, &st);2251if(!st.st_size)2252die("Log%sis empty.", logfile);2253 mapsz =xsize_t(st.st_size);2254 log_mapped =xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd,0);2255 logdata = log_mapped;2256close(logfd);22572258 lastrec = NULL;2259 rec = logend = logdata + st.st_size;2260while(logdata < rec) {2261 reccnt++;2262if(logdata < rec && *(rec-1) =='\n')2263 rec--;2264 lastgt = NULL;2265while(logdata < rec && *(rec-1) !='\n') {2266 rec--;2267if(*rec =='>')2268 lastgt = rec;2269}2270if(!lastgt)2271die("Log%sis corrupt.", logfile);2272 date =strtoul(lastgt +1, &tz_c,10);2273if(date <= at_time || cnt ==0) {2274 tz =strtoul(tz_c, NULL,10);2275if(msg)2276*msg =ref_msg(rec, logend);2277if(cutoff_time)2278*cutoff_time = date;2279if(cutoff_tz)2280*cutoff_tz = tz;2281if(cutoff_cnt)2282*cutoff_cnt = reccnt -1;2283if(lastrec) {2284if(get_sha1_hex(lastrec, logged_sha1))2285die("Log%sis corrupt.", logfile);2286if(get_sha1_hex(rec +41, sha1))2287die("Log%sis corrupt.", logfile);2288if(hashcmp(logged_sha1, sha1)) {2289warning("Log%shas gap after%s.",2290 logfile,show_date(date, tz, DATE_RFC2822));2291}2292}2293else if(date == at_time) {2294if(get_sha1_hex(rec +41, sha1))2295die("Log%sis corrupt.", logfile);2296}2297else{2298if(get_sha1_hex(rec +41, logged_sha1))2299die("Log%sis corrupt.", logfile);2300if(hashcmp(logged_sha1, sha1)) {2301warning("Log%sunexpectedly ended on%s.",2302 logfile,show_date(date, tz, DATE_RFC2822));2303}2304}2305munmap(log_mapped, mapsz);2306return0;2307}2308 lastrec = rec;2309if(cnt >0)2310 cnt--;2311}23122313 rec = logdata;2314while(rec < logend && *rec !='>'&& *rec !='\n')2315 rec++;2316if(rec == logend || *rec =='\n')2317die("Log%sis corrupt.", logfile);2318 date =strtoul(rec +1, &tz_c,10);2319 tz =strtoul(tz_c, NULL,10);2320if(get_sha1_hex(logdata, sha1))2321die("Log%sis corrupt.", logfile);2322if(is_null_sha1(sha1)) {2323if(get_sha1_hex(logdata +41, sha1))2324die("Log%sis corrupt.", logfile);2325}2326if(msg)2327*msg =ref_msg(logdata, logend);2328munmap(log_mapped, mapsz);23292330if(cutoff_time)2331*cutoff_time = date;2332if(cutoff_tz)2333*cutoff_tz = tz;2334if(cutoff_cnt)2335*cutoff_cnt = reccnt;2336return1;2337}23382339static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2340{2341unsigned char osha1[20], nsha1[20];2342char*email_end, *message;2343unsigned long timestamp;2344int tz;23452346/* old SP new SP name <email> SP time TAB msg LF */2347if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2348get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2349get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2350!(email_end =strchr(sb->buf +82,'>')) ||2351 email_end[1] !=' '||2352!(timestamp =strtoul(email_end +2, &message,10)) ||2353!message || message[0] !=' '||2354(message[1] !='+'&& message[1] !='-') ||2355!isdigit(message[2]) || !isdigit(message[3]) ||2356!isdigit(message[4]) || !isdigit(message[5]))2357return0;/* corrupt? */2358 email_end[1] ='\0';2359 tz =strtol(message +1, NULL,10);2360if(message[6] !='\t')2361 message +=6;2362else2363 message +=7;2364returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2365}23662367static char*find_beginning_of_line(char*bob,char*scan)2368{2369while(bob < scan && *(--scan) !='\n')2370;/* keep scanning backwards */2371/*2372 * Return either beginning of the buffer, or LF at the end of2373 * the previous line.2374 */2375return scan;2376}23772378intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2379{2380struct strbuf sb = STRBUF_INIT;2381FILE*logfp;2382long pos;2383int ret =0, at_tail =1;23842385 logfp =fopen(git_path("logs/%s", refname),"r");2386if(!logfp)2387return-1;23882389/* Jump to the end */2390if(fseek(logfp,0, SEEK_END) <0)2391returnerror("cannot seek back reflog for%s:%s",2392 refname,strerror(errno));2393 pos =ftell(logfp);2394while(!ret &&0< pos) {2395int cnt;2396size_t nread;2397char buf[BUFSIZ];2398char*endp, *scanp;23992400/* Fill next block from the end */2401 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2402if(fseek(logfp, pos - cnt, SEEK_SET))2403returnerror("cannot seek back reflog for%s:%s",2404 refname,strerror(errno));2405 nread =fread(buf, cnt,1, logfp);2406if(nread !=1)2407returnerror("cannot read%dbytes from reflog for%s:%s",2408 cnt, refname,strerror(errno));2409 pos -= cnt;24102411 scanp = endp = buf + cnt;2412if(at_tail && scanp[-1] =='\n')2413/* Looking at the final LF at the end of the file */2414 scanp--;2415 at_tail =0;24162417while(buf < scanp) {2418/*2419 * terminating LF of the previous line, or the beginning2420 * of the buffer.2421 */2422char*bp;24232424 bp =find_beginning_of_line(buf, scanp);24252426if(*bp !='\n') {2427strbuf_splice(&sb,0,0, buf, endp - buf);2428if(pos)2429break;/* need to fill another block */2430 scanp = buf -1;/* leave loop */2431}else{2432/*2433 * (bp + 1) thru endp is the beginning of the2434 * current line we have in sb2435 */2436strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2437 scanp = bp;2438 endp = bp +1;2439}2440 ret =show_one_reflog_ent(&sb, fn, cb_data);2441strbuf_reset(&sb);2442if(ret)2443break;2444}24452446}2447if(!ret && sb.len)2448 ret =show_one_reflog_ent(&sb, fn, cb_data);24492450fclose(logfp);2451strbuf_release(&sb);2452return ret;2453}24542455intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2456{2457FILE*logfp;2458struct strbuf sb = STRBUF_INIT;2459int ret =0;24602461 logfp =fopen(git_path("logs/%s", refname),"r");2462if(!logfp)2463return-1;24642465while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2466 ret =show_one_reflog_ent(&sb, fn, cb_data);2467fclose(logfp);2468strbuf_release(&sb);2469return ret;2470}2471/*2472 * Call fn for each reflog in the namespace indicated by name. name2473 * must be empty or end with '/'. Name will be used as a scratch2474 * space, but its contents will be restored before return.2475 */2476static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)2477{2478DIR*d =opendir(git_path("logs/%s", name->buf));2479int retval =0;2480struct dirent *de;2481int oldlen = name->len;24822483if(!d)2484return name->len ? errno :0;24852486while((de =readdir(d)) != NULL) {2487struct stat st;24882489if(de->d_name[0] =='.')2490continue;2491if(has_extension(de->d_name,".lock"))2492continue;2493strbuf_addstr(name, de->d_name);2494if(stat(git_path("logs/%s", name->buf), &st) <0) {2495;/* silently ignore */2496}else{2497if(S_ISDIR(st.st_mode)) {2498strbuf_addch(name,'/');2499 retval =do_for_each_reflog(name, fn, cb_data);2500}else{2501unsigned char sha1[20];2502if(read_ref_full(name->buf, sha1,0, NULL))2503 retval =error("bad ref for%s", name->buf);2504else2505 retval =fn(name->buf, sha1,0, cb_data);2506}2507if(retval)2508break;2509}2510strbuf_setlen(name, oldlen);2511}2512closedir(d);2513return retval;2514}25152516intfor_each_reflog(each_ref_fn fn,void*cb_data)2517{2518int retval;2519struct strbuf name;2520strbuf_init(&name, PATH_MAX);2521 retval =do_for_each_reflog(&name, fn, cb_data);2522strbuf_release(&name);2523return retval;2524}25252526intupdate_ref(const char*action,const char*refname,2527const unsigned char*sha1,const unsigned char*oldval,2528int flags,enum action_on_err onerr)2529{2530static struct ref_lock *lock;2531 lock =lock_any_ref_for_update(refname, oldval, flags);2532if(!lock) {2533const char*str ="Cannot lock the ref '%s'.";2534switch(onerr) {2535case MSG_ON_ERR:error(str, refname);break;2536case DIE_ON_ERR:die(str, refname);break;2537case QUIET_ON_ERR:break;2538}2539return1;2540}2541if(write_ref_sha1(lock, sha1, action) <0) {2542const char*str ="Cannot update the ref '%s'.";2543switch(onerr) {2544case MSG_ON_ERR:error(str, refname);break;2545case DIE_ON_ERR:die(str, refname);break;2546case QUIET_ON_ERR:break;2547}2548return1;2549}2550return0;2551}25522553struct ref *find_ref_by_name(const struct ref *list,const char*name)2554{2555for( ; list; list = list->next)2556if(!strcmp(list->name, name))2557return(struct ref *)list;2558return NULL;2559}25602561/*2562 * generate a format suitable for scanf from a ref_rev_parse_rules2563 * rule, that is replace the "%.*s" spec with a "%s" spec2564 */2565static voidgen_scanf_fmt(char*scanf_fmt,const char*rule)2566{2567char*spec;25682569 spec =strstr(rule,"%.*s");2570if(!spec ||strstr(spec +4,"%.*s"))2571die("invalid rule in ref_rev_parse_rules:%s", rule);25722573/* copy all until spec */2574strncpy(scanf_fmt, rule, spec - rule);2575 scanf_fmt[spec - rule] ='\0';2576/* copy new spec */2577strcat(scanf_fmt,"%s");2578/* copy remaining rule */2579strcat(scanf_fmt, spec +4);25802581return;2582}25832584char*shorten_unambiguous_ref(const char*refname,int strict)2585{2586int i;2587static char**scanf_fmts;2588static int nr_rules;2589char*short_name;25902591/* pre generate scanf formats from ref_rev_parse_rules[] */2592if(!nr_rules) {2593size_t total_len =0;25942595/* the rule list is NULL terminated, count them first */2596for(; ref_rev_parse_rules[nr_rules]; nr_rules++)2597/* no +1 because strlen("%s") < strlen("%.*s") */2598 total_len +=strlen(ref_rev_parse_rules[nr_rules]);25992600 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);26012602 total_len =0;2603for(i =0; i < nr_rules; i++) {2604 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules]2605+ total_len;2606gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);2607 total_len +=strlen(ref_rev_parse_rules[i]);2608}2609}26102611/* bail out if there are no rules */2612if(!nr_rules)2613returnxstrdup(refname);26142615/* buffer for scanf result, at most refname must fit */2616 short_name =xstrdup(refname);26172618/* skip first rule, it will always match */2619for(i = nr_rules -1; i >0; --i) {2620int j;2621int rules_to_fail = i;2622int short_name_len;26232624if(1!=sscanf(refname, scanf_fmts[i], short_name))2625continue;26262627 short_name_len =strlen(short_name);26282629/*2630 * in strict mode, all (except the matched one) rules2631 * must fail to resolve to a valid non-ambiguous ref2632 */2633if(strict)2634 rules_to_fail = nr_rules;26352636/*2637 * check if the short name resolves to a valid ref,2638 * but use only rules prior to the matched one2639 */2640for(j =0; j < rules_to_fail; j++) {2641const char*rule = ref_rev_parse_rules[j];2642char refname[PATH_MAX];26432644/* skip matched rule */2645if(i == j)2646continue;26472648/*2649 * the short name is ambiguous, if it resolves2650 * (with this previous rule) to a valid ref2651 * read_ref() returns 0 on success2652 */2653mksnpath(refname,sizeof(refname),2654 rule, short_name_len, short_name);2655if(ref_exists(refname))2656break;2657}26582659/*2660 * short name is non-ambiguous if all previous rules2661 * haven't resolved to a valid ref2662 */2663if(j == rules_to_fail)2664return short_name;2665}26662667free(short_name);2668returnxstrdup(refname);2669}26702671static struct string_list *hide_refs;26722673intparse_hide_refs_config(const char*var,const char*value,const char*section)2674{2675if(!strcmp("transfer.hiderefs", var) ||2676/* NEEDSWORK: use parse_config_key() once both are merged */2677(!prefixcmp(var, section) && var[strlen(section)] =='.'&&2678!strcmp(var +strlen(section),".hiderefs"))) {2679char*ref;2680int len;26812682if(!value)2683returnconfig_error_nonbool(var);2684 ref =xstrdup(value);2685 len =strlen(ref);2686while(len && ref[len -1] =='/')2687 ref[--len] ='\0';2688if(!hide_refs) {2689 hide_refs =xcalloc(1,sizeof(*hide_refs));2690 hide_refs->strdup_strings =1;2691}2692string_list_append(hide_refs, ref);2693}2694return0;2695}26962697intref_is_hidden(const char*refname)2698{2699struct string_list_item *item;27002701if(!hide_refs)2702return0;2703for_each_string_list_item(item, hide_refs) {2704int len;2705if(prefixcmp(refname, item->string))2706continue;2707 len =strlen(item->string);2708if(!refname[len] || refname[len] =='/')2709return1;2710}2711return0;2712}