1#include"cache.h" 2#include"refs.h" 3#include"object.h" 4#include"tag.h" 5#include"dir.h" 6 7/* 8 * Make sure "ref" is something reasonable to have under ".git/refs/"; 9 * We do not like it if: 10 * 11 * - any path component of it begins with ".", or 12 * - it has double dots "..", or 13 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 14 * - it ends with a "/". 15 * - it ends with ".lock" 16 * - it contains a "\" (backslash) 17 */ 18 19/* Return true iff ch is not allowed in reference names. */ 20staticinlineintbad_ref_char(int ch) 21{ 22if(((unsigned) ch) <=' '|| ch ==0x7f|| 23 ch =='~'|| ch =='^'|| ch ==':'|| ch =='\\') 24return1; 25/* 2.13 Pattern Matching Notation */ 26if(ch =='*'|| ch =='?'|| ch =='[')/* Unsupported */ 27return1; 28return0; 29} 30 31/* 32 * Try to read one refname component from the front of refname. Return 33 * the length of the component found, or -1 if the component is not 34 * legal. 35 */ 36static intcheck_refname_component(const char*refname,int flags) 37{ 38const char*cp; 39char last ='\0'; 40 41for(cp = refname; ; cp++) { 42char ch = *cp; 43if(ch =='\0'|| ch =='/') 44break; 45if(bad_ref_char(ch)) 46return-1;/* Illegal character in refname. */ 47if(last =='.'&& ch =='.') 48return-1;/* Refname contains "..". */ 49if(last =='@'&& ch =='{') 50return-1;/* Refname contains "@{". */ 51 last = ch; 52} 53if(cp == refname) 54return0;/* Component has zero length. */ 55if(refname[0] =='.') { 56if(!(flags & REFNAME_DOT_COMPONENT)) 57return-1;/* Component starts with '.'. */ 58/* 59 * Even if leading dots are allowed, don't allow "." 60 * as a component (".." is prevented by a rule above). 61 */ 62if(refname[1] =='\0') 63return-1;/* Component equals ".". */ 64} 65if(cp - refname >=5&& !memcmp(cp -5,".lock",5)) 66return-1;/* Refname ends with ".lock". */ 67return cp - refname; 68} 69 70intcheck_refname_format(const char*refname,int flags) 71{ 72int component_len, component_count =0; 73 74while(1) { 75/* We are at the start of a path component. */ 76 component_len =check_refname_component(refname, flags); 77if(component_len <=0) { 78if((flags & REFNAME_REFSPEC_PATTERN) && 79 refname[0] =='*'&& 80(refname[1] =='\0'|| refname[1] =='/')) { 81/* Accept one wildcard as a full refname component. */ 82 flags &= ~REFNAME_REFSPEC_PATTERN; 83 component_len =1; 84}else{ 85return-1; 86} 87} 88 component_count++; 89if(refname[component_len] =='\0') 90break; 91/* Skip to next component. */ 92 refname += component_len +1; 93} 94 95if(refname[component_len -1] =='.') 96return-1;/* Refname ends with '.'. */ 97if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 98return-1;/* Refname has only one component. */ 99return0; 100} 101 102struct ref_entry; 103 104/* 105 * Information used (along with the information in ref_entry) to 106 * describe a single cached reference. This data structure only 107 * occurs embedded in a union in struct ref_entry, and only when 108 * (ref_entry->flag & REF_DIR) is zero. 109 */ 110struct ref_value { 111unsigned char sha1[20]; 112unsigned char peeled[20]; 113}; 114 115struct ref_cache; 116 117/* 118 * Information used (along with the information in ref_entry) to 119 * describe a level in the hierarchy of references. This data 120 * structure only occurs embedded in a union in struct ref_entry, and 121 * only when (ref_entry.flag & REF_DIR) is set. In that case, 122 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 123 * in the directory have already been read: 124 * 125 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 126 * or packed references, already read. 127 * 128 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 129 * references that hasn't been read yet (nor has any of its 130 * subdirectories). 131 * 132 * Entries within a directory are stored within a growable array of 133 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 134 * sorted are sorted by their component name in strcmp() order and the 135 * remaining entries are unsorted. 136 * 137 * Loose references are read lazily, one directory at a time. When a 138 * directory of loose references is read, then all of the references 139 * in that directory are stored, and REF_INCOMPLETE stubs are created 140 * for any subdirectories, but the subdirectories themselves are not 141 * read. The reading is triggered by get_ref_dir(). 142 */ 143struct ref_dir { 144int nr, alloc; 145 146/* 147 * Entries with index 0 <= i < sorted are sorted by name. New 148 * entries are appended to the list unsorted, and are sorted 149 * only when required; thus we avoid the need to sort the list 150 * after the addition of every reference. 151 */ 152int sorted; 153 154/* A pointer to the ref_cache that contains this ref_dir. */ 155struct ref_cache *ref_cache; 156 157struct ref_entry **entries; 158}; 159 160/* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */ 161#define REF_KNOWS_PEELED 0x08 162 163/* ref_entry represents a directory of references */ 164#define REF_DIR 0x10 165 166/* 167 * Entry has not yet been read from disk (used only for REF_DIR 168 * entries representing loose references) 169 */ 170#define REF_INCOMPLETE 0x20 171 172/* 173 * A ref_entry represents either a reference or a "subdirectory" of 174 * references. 175 * 176 * Each directory in the reference namespace is represented by a 177 * ref_entry with (flags & REF_DIR) set and containing a subdir member 178 * that holds the entries in that directory that have been read so 179 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 180 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 181 * used for loose reference directories. 182 * 183 * References are represented by a ref_entry with (flags & REF_DIR) 184 * unset and a value member that describes the reference's value. The 185 * flag member is at the ref_entry level, but it is also needed to 186 * interpret the contents of the value field (in other words, a 187 * ref_value object is not very much use without the enclosing 188 * ref_entry). 189 * 190 * Reference names cannot end with slash and directories' names are 191 * always stored with a trailing slash (except for the top-level 192 * directory, which is always denoted by ""). This has two nice 193 * consequences: (1) when the entries in each subdir are sorted 194 * lexicographically by name (as they usually are), the references in 195 * a whole tree can be generated in lexicographic order by traversing 196 * the tree in left-to-right, depth-first order; (2) the names of 197 * references and subdirectories cannot conflict, and therefore the 198 * presence of an empty subdirectory does not block the creation of a 199 * similarly-named reference. (The fact that reference names with the 200 * same leading components can conflict *with each other* is a 201 * separate issue that is regulated by is_refname_available().) 202 * 203 * Please note that the name field contains the fully-qualified 204 * reference (or subdirectory) name. Space could be saved by only 205 * storing the relative names. But that would require the full names 206 * to be generated on the fly when iterating in do_for_each_ref(), and 207 * would break callback functions, who have always been able to assume 208 * that the name strings that they are passed will not be freed during 209 * the iteration. 210 */ 211struct ref_entry { 212unsigned char flag;/* ISSYMREF? ISPACKED? */ 213union{ 214struct ref_value value;/* if not (flags&REF_DIR) */ 215struct ref_dir subdir;/* if (flags&REF_DIR) */ 216} u; 217/* 218 * The full name of the reference (e.g., "refs/heads/master") 219 * or the full name of the directory with a trailing slash 220 * (e.g., "refs/heads/"): 221 */ 222char name[FLEX_ARRAY]; 223}; 224 225static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 226 227static struct ref_dir *get_ref_dir(struct ref_entry *entry) 228{ 229struct ref_dir *dir; 230assert(entry->flag & REF_DIR); 231 dir = &entry->u.subdir; 232if(entry->flag & REF_INCOMPLETE) { 233read_loose_refs(entry->name, dir); 234 entry->flag &= ~REF_INCOMPLETE; 235} 236return dir; 237} 238 239static struct ref_entry *create_ref_entry(const char*refname, 240const unsigned char*sha1,int flag, 241int check_name) 242{ 243int len; 244struct ref_entry *ref; 245 246if(check_name && 247check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 248die("Reference has invalid format: '%s'", refname); 249 len =strlen(refname) +1; 250 ref =xmalloc(sizeof(struct ref_entry) + len); 251hashcpy(ref->u.value.sha1, sha1); 252hashclr(ref->u.value.peeled); 253memcpy(ref->name, refname, len); 254 ref->flag = flag; 255return ref; 256} 257 258static voidclear_ref_dir(struct ref_dir *dir); 259 260static voidfree_ref_entry(struct ref_entry *entry) 261{ 262if(entry->flag & REF_DIR) { 263/* 264 * Do not use get_ref_dir() here, as that might 265 * trigger the reading of loose refs. 266 */ 267clear_ref_dir(&entry->u.subdir); 268} 269free(entry); 270} 271 272/* 273 * Add a ref_entry to the end of dir (unsorted). Entry is always 274 * stored directly in dir; no recursion into subdirectories is 275 * done. 276 */ 277static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 278{ 279ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 280 dir->entries[dir->nr++] = entry; 281/* optimize for the case that entries are added in order */ 282if(dir->nr ==1|| 283(dir->nr == dir->sorted +1&& 284strcmp(dir->entries[dir->nr -2]->name, 285 dir->entries[dir->nr -1]->name) <0)) 286 dir->sorted = dir->nr; 287} 288 289/* 290 * Clear and free all entries in dir, recursively. 291 */ 292static voidclear_ref_dir(struct ref_dir *dir) 293{ 294int i; 295for(i =0; i < dir->nr; i++) 296free_ref_entry(dir->entries[i]); 297free(dir->entries); 298 dir->sorted = dir->nr = dir->alloc =0; 299 dir->entries = NULL; 300} 301 302/* 303 * Create a struct ref_entry object for the specified dirname. 304 * dirname is the name of the directory with a trailing slash (e.g., 305 * "refs/heads/") or "" for the top-level directory. 306 */ 307static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 308const char*dirname,size_t len, 309int incomplete) 310{ 311struct ref_entry *direntry; 312 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 313memcpy(direntry->name, dirname, len); 314 direntry->name[len] ='\0'; 315 direntry->u.subdir.ref_cache = ref_cache; 316 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 317return direntry; 318} 319 320static intref_entry_cmp(const void*a,const void*b) 321{ 322struct ref_entry *one = *(struct ref_entry **)a; 323struct ref_entry *two = *(struct ref_entry **)b; 324returnstrcmp(one->name, two->name); 325} 326 327static voidsort_ref_dir(struct ref_dir *dir); 328 329struct string_slice { 330size_t len; 331const char*str; 332}; 333 334static intref_entry_cmp_sslice(const void*key_,const void*ent_) 335{ 336struct string_slice *key = (struct string_slice *)key_; 337struct ref_entry *ent = *(struct ref_entry **)ent_; 338int entlen =strlen(ent->name); 339int cmplen = key->len < entlen ? key->len : entlen; 340int cmp =memcmp(key->str, ent->name, cmplen); 341if(cmp) 342return cmp; 343return key->len - entlen; 344} 345 346/* 347 * Return the entry with the given refname from the ref_dir 348 * (non-recursively), sorting dir if necessary. Return NULL if no 349 * such entry is found. dir must already be complete. 350 */ 351static struct ref_entry *search_ref_dir(struct ref_dir *dir, 352const char*refname,size_t len) 353{ 354struct ref_entry **r; 355struct string_slice key; 356 357if(refname == NULL || !dir->nr) 358return NULL; 359 360sort_ref_dir(dir); 361 key.len = len; 362 key.str = refname; 363 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 364 ref_entry_cmp_sslice); 365 366if(r == NULL) 367return NULL; 368 369return*r; 370} 371 372/* 373 * Search for a directory entry directly within dir (without 374 * recursing). Sort dir if necessary. subdirname must be a directory 375 * name (i.e., end in '/'). If mkdir is set, then create the 376 * directory if it is missing; otherwise, return NULL if the desired 377 * directory cannot be found. dir must already be complete. 378 */ 379static struct ref_dir *search_for_subdir(struct ref_dir *dir, 380const char*subdirname,size_t len, 381int mkdir) 382{ 383struct ref_entry *entry =search_ref_dir(dir, subdirname, len); 384if(!entry) { 385if(!mkdir) 386return NULL; 387/* 388 * Since dir is complete, the absence of a subdir 389 * means that the subdir really doesn't exist; 390 * therefore, create an empty record for it but mark 391 * the record complete. 392 */ 393 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 394add_entry_to_dir(dir, entry); 395} 396returnget_ref_dir(entry); 397} 398 399/* 400 * If refname is a reference name, find the ref_dir within the dir 401 * tree that should hold refname. If refname is a directory name 402 * (i.e., ends in '/'), then return that ref_dir itself. dir must 403 * represent the top-level directory and must already be complete. 404 * Sort ref_dirs and recurse into subdirectories as necessary. If 405 * mkdir is set, then create any missing directories; otherwise, 406 * return NULL if the desired directory cannot be found. 407 */ 408static struct ref_dir *find_containing_dir(struct ref_dir *dir, 409const char*refname,int mkdir) 410{ 411const char*slash; 412for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 413size_t dirnamelen = slash - refname +1; 414struct ref_dir *subdir; 415 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 416if(!subdir) { 417 dir = NULL; 418break; 419} 420 dir = subdir; 421} 422 423return dir; 424} 425 426/* 427 * Find the value entry with the given name in dir, sorting ref_dirs 428 * and recursing into subdirectories as necessary. If the name is not 429 * found or it corresponds to a directory entry, return NULL. 430 */ 431static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 432{ 433struct ref_entry *entry; 434 dir =find_containing_dir(dir, refname,0); 435if(!dir) 436return NULL; 437 entry =search_ref_dir(dir, refname,strlen(refname)); 438return(entry && !(entry->flag & REF_DIR)) ? entry : NULL; 439} 440 441/* 442 * Add a ref_entry to the ref_dir (unsorted), recursing into 443 * subdirectories as necessary. dir must represent the top-level 444 * directory. Return 0 on success. 445 */ 446static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 447{ 448 dir =find_containing_dir(dir, ref->name,1); 449if(!dir) 450return-1; 451add_entry_to_dir(dir, ref); 452return0; 453} 454 455/* 456 * Emit a warning and return true iff ref1 and ref2 have the same name 457 * and the same sha1. Die if they have the same name but different 458 * sha1s. 459 */ 460static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 461{ 462if(strcmp(ref1->name, ref2->name)) 463return0; 464 465/* Duplicate name; make sure that they don't conflict: */ 466 467if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 468/* This is impossible by construction */ 469die("Reference directory conflict:%s", ref1->name); 470 471if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 472die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 473 474warning("Duplicated ref:%s", ref1->name); 475return1; 476} 477 478/* 479 * Sort the entries in dir non-recursively (if they are not already 480 * sorted) and remove any duplicate entries. 481 */ 482static voidsort_ref_dir(struct ref_dir *dir) 483{ 484int i, j; 485struct ref_entry *last = NULL; 486 487/* 488 * This check also prevents passing a zero-length array to qsort(), 489 * which is a problem on some platforms. 490 */ 491if(dir->sorted == dir->nr) 492return; 493 494qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 495 496/* Remove any duplicates: */ 497for(i =0, j =0; j < dir->nr; j++) { 498struct ref_entry *entry = dir->entries[j]; 499if(last &&is_dup_ref(last, entry)) 500free_ref_entry(entry); 501else 502 last = dir->entries[i++] = entry; 503} 504 dir->sorted = dir->nr = i; 505} 506 507#define DO_FOR_EACH_INCLUDE_BROKEN 01 508 509static struct ref_entry *current_ref; 510 511static intdo_one_ref(const char*base, each_ref_fn fn,int trim, 512int flags,void*cb_data,struct ref_entry *entry) 513{ 514int retval; 515if(prefixcmp(entry->name, base)) 516return0; 517 518if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) { 519if(entry->flag & REF_ISBROKEN) 520return0;/* ignore broken refs e.g. dangling symref */ 521if(!has_sha1_file(entry->u.value.sha1)) { 522error("%sdoes not point to a valid object!", entry->name); 523return0; 524} 525} 526 current_ref = entry; 527 retval =fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data); 528 current_ref = NULL; 529return retval; 530} 531 532/* 533 * Call fn for each reference in dir that has index in the range 534 * offset <= index < dir->nr. Recurse into subdirectories that are in 535 * that index range, sorting them before iterating. This function 536 * does not sort dir itself; it should be sorted beforehand. 537 */ 538static intdo_for_each_ref_in_dir(struct ref_dir *dir,int offset, 539const char*base, 540 each_ref_fn fn,int trim,int flags,void*cb_data) 541{ 542int i; 543assert(dir->sorted == dir->nr); 544for(i = offset; i < dir->nr; i++) { 545struct ref_entry *entry = dir->entries[i]; 546int retval; 547if(entry->flag & REF_DIR) { 548struct ref_dir *subdir =get_ref_dir(entry); 549sort_ref_dir(subdir); 550 retval =do_for_each_ref_in_dir(subdir,0, 551 base, fn, trim, flags, cb_data); 552}else{ 553 retval =do_one_ref(base, fn, trim, flags, cb_data, entry); 554} 555if(retval) 556return retval; 557} 558return0; 559} 560 561/* 562 * Call fn for each reference in the union of dir1 and dir2, in order 563 * by refname. Recurse into subdirectories. If a value entry appears 564 * in both dir1 and dir2, then only process the version that is in 565 * dir2. The input dirs must already be sorted, but subdirs will be 566 * sorted as needed. 567 */ 568static intdo_for_each_ref_in_dirs(struct ref_dir *dir1, 569struct ref_dir *dir2, 570const char*base, each_ref_fn fn,int trim, 571int flags,void*cb_data) 572{ 573int retval; 574int i1 =0, i2 =0; 575 576assert(dir1->sorted == dir1->nr); 577assert(dir2->sorted == dir2->nr); 578while(1) { 579struct ref_entry *e1, *e2; 580int cmp; 581if(i1 == dir1->nr) { 582returndo_for_each_ref_in_dir(dir2, i2, 583 base, fn, trim, flags, cb_data); 584} 585if(i2 == dir2->nr) { 586returndo_for_each_ref_in_dir(dir1, i1, 587 base, fn, trim, flags, cb_data); 588} 589 e1 = dir1->entries[i1]; 590 e2 = dir2->entries[i2]; 591 cmp =strcmp(e1->name, e2->name); 592if(cmp ==0) { 593if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 594/* Both are directories; descend them in parallel. */ 595struct ref_dir *subdir1 =get_ref_dir(e1); 596struct ref_dir *subdir2 =get_ref_dir(e2); 597sort_ref_dir(subdir1); 598sort_ref_dir(subdir2); 599 retval =do_for_each_ref_in_dirs( 600 subdir1, subdir2, 601 base, fn, trim, flags, cb_data); 602 i1++; 603 i2++; 604}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 605/* Both are references; ignore the one from dir1. */ 606 retval =do_one_ref(base, fn, trim, flags, cb_data, e2); 607 i1++; 608 i2++; 609}else{ 610die("conflict between reference and directory:%s", 611 e1->name); 612} 613}else{ 614struct ref_entry *e; 615if(cmp <0) { 616 e = e1; 617 i1++; 618}else{ 619 e = e2; 620 i2++; 621} 622if(e->flag & REF_DIR) { 623struct ref_dir *subdir =get_ref_dir(e); 624sort_ref_dir(subdir); 625 retval =do_for_each_ref_in_dir( 626 subdir,0, 627 base, fn, trim, flags, cb_data); 628}else{ 629 retval =do_one_ref(base, fn, trim, flags, cb_data, e); 630} 631} 632if(retval) 633return retval; 634} 635if(i1 < dir1->nr) 636returndo_for_each_ref_in_dir(dir1, i1, 637 base, fn, trim, flags, cb_data); 638if(i2 < dir2->nr) 639returndo_for_each_ref_in_dir(dir2, i2, 640 base, fn, trim, flags, cb_data); 641return0; 642} 643 644/* 645 * Return true iff refname1 and refname2 conflict with each other. 646 * Two reference names conflict if one of them exactly matches the 647 * leading components of the other; e.g., "foo/bar" conflicts with 648 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 649 * "foo/barbados". 650 */ 651static intnames_conflict(const char*refname1,const char*refname2) 652{ 653for(; *refname1 && *refname1 == *refname2; refname1++, refname2++) 654; 655return(*refname1 =='\0'&& *refname2 =='/') 656|| (*refname1 =='/'&& *refname2 =='\0'); 657} 658 659struct name_conflict_cb { 660const char*refname; 661const char*oldrefname; 662const char*conflicting_refname; 663}; 664 665static intname_conflict_fn(const char*existingrefname,const unsigned char*sha1, 666int flags,void*cb_data) 667{ 668struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data; 669if(data->oldrefname && !strcmp(data->oldrefname, existingrefname)) 670return0; 671if(names_conflict(data->refname, existingrefname)) { 672 data->conflicting_refname = existingrefname; 673return1; 674} 675return0; 676} 677 678/* 679 * Return true iff a reference named refname could be created without 680 * conflicting with the name of an existing reference in array. If 681 * oldrefname is non-NULL, ignore potential conflicts with oldrefname 682 * (e.g., because oldrefname is scheduled for deletion in the same 683 * operation). 684 */ 685static intis_refname_available(const char*refname,const char*oldrefname, 686struct ref_dir *dir) 687{ 688struct name_conflict_cb data; 689 data.refname = refname; 690 data.oldrefname = oldrefname; 691 data.conflicting_refname = NULL; 692 693sort_ref_dir(dir); 694if(do_for_each_ref_in_dir(dir,0,"", name_conflict_fn, 6950, DO_FOR_EACH_INCLUDE_BROKEN, 696&data)) { 697error("'%s' exists; cannot create '%s'", 698 data.conflicting_refname, refname); 699return0; 700} 701return1; 702} 703 704/* 705 * Future: need to be in "struct repository" 706 * when doing a full libification. 707 */ 708static struct ref_cache { 709struct ref_cache *next; 710struct ref_entry *loose; 711struct ref_entry *packed; 712/* The submodule name, or "" for the main repo. */ 713char name[FLEX_ARRAY]; 714} *ref_cache; 715 716static voidclear_packed_ref_cache(struct ref_cache *refs) 717{ 718if(refs->packed) { 719free_ref_entry(refs->packed); 720 refs->packed = NULL; 721} 722} 723 724static voidclear_loose_ref_cache(struct ref_cache *refs) 725{ 726if(refs->loose) { 727free_ref_entry(refs->loose); 728 refs->loose = NULL; 729} 730} 731 732static struct ref_cache *create_ref_cache(const char*submodule) 733{ 734int len; 735struct ref_cache *refs; 736if(!submodule) 737 submodule =""; 738 len =strlen(submodule) +1; 739 refs =xcalloc(1,sizeof(struct ref_cache) + len); 740memcpy(refs->name, submodule, len); 741return refs; 742} 743 744/* 745 * Return a pointer to a ref_cache for the specified submodule. For 746 * the main repository, use submodule==NULL. The returned structure 747 * will be allocated and initialized but not necessarily populated; it 748 * should not be freed. 749 */ 750static struct ref_cache *get_ref_cache(const char*submodule) 751{ 752struct ref_cache *refs = ref_cache; 753if(!submodule) 754 submodule =""; 755while(refs) { 756if(!strcmp(submodule, refs->name)) 757return refs; 758 refs = refs->next; 759} 760 761 refs =create_ref_cache(submodule); 762 refs->next = ref_cache; 763 ref_cache = refs; 764return refs; 765} 766 767voidinvalidate_ref_cache(const char*submodule) 768{ 769struct ref_cache *refs =get_ref_cache(submodule); 770clear_packed_ref_cache(refs); 771clear_loose_ref_cache(refs); 772} 773 774/* 775 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 776 * Return a pointer to the refname within the line (null-terminated), 777 * or NULL if there was a problem. 778 */ 779static const char*parse_ref_line(char*line,unsigned char*sha1) 780{ 781/* 782 * 42: the answer to everything. 783 * 784 * In this case, it happens to be the answer to 785 * 40 (length of sha1 hex representation) 786 * +1 (space in between hex and name) 787 * +1 (newline at the end of the line) 788 */ 789int len =strlen(line) -42; 790 791if(len <=0) 792return NULL; 793if(get_sha1_hex(line, sha1) <0) 794return NULL; 795if(!isspace(line[40])) 796return NULL; 797 line +=41; 798if(isspace(*line)) 799return NULL; 800if(line[len] !='\n') 801return NULL; 802 line[len] =0; 803 804return line; 805} 806 807/* 808 * Read f, which is a packed-refs file, into dir. 809 * 810 * A comment line of the form "# pack-refs with: " may contain zero or 811 * more traits. We interpret the traits as follows: 812 * 813 * No traits: 814 * 815 * Probably no references are peeled. But if the file contains a 816 * peeled value for a reference, we will use it. 817 * 818 * peeled: 819 * 820 * References under "refs/tags/", if they *can* be peeled, *are* 821 * peeled in this file. References outside of "refs/tags/" are 822 * probably not peeled even if they could have been, but if we find 823 * a peeled value for such a reference we will use it. 824 * 825 * fully-peeled: 826 * 827 * All references in the file that can be peeled are peeled. 828 * Inversely (and this is more important), any references in the 829 * file for which no peeled value is recorded is not peelable. This 830 * trait should typically be written alongside "peeled" for 831 * compatibility with older clients, but we do not require it 832 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 833 */ 834static voidread_packed_refs(FILE*f,struct ref_dir *dir) 835{ 836struct ref_entry *last = NULL; 837char refline[PATH_MAX]; 838enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 839 840while(fgets(refline,sizeof(refline), f)) { 841unsigned char sha1[20]; 842const char*refname; 843static const char header[] ="# pack-refs with:"; 844 845if(!strncmp(refline, header,sizeof(header)-1)) { 846const char*traits = refline +sizeof(header) -1; 847if(strstr(traits," fully-peeled ")) 848 peeled = PEELED_FULLY; 849else if(strstr(traits," peeled ")) 850 peeled = PEELED_TAGS; 851/* perhaps other traits later as well */ 852continue; 853} 854 855 refname =parse_ref_line(refline, sha1); 856if(refname) { 857 last =create_ref_entry(refname, sha1, REF_ISPACKED,1); 858if(peeled == PEELED_FULLY || 859(peeled == PEELED_TAGS && !prefixcmp(refname,"refs/tags/"))) 860 last->flag |= REF_KNOWS_PEELED; 861add_ref(dir, last); 862continue; 863} 864if(last && 865 refline[0] =='^'&& 866strlen(refline) ==42&& 867 refline[41] =='\n'&& 868!get_sha1_hex(refline +1, sha1)) { 869hashcpy(last->u.value.peeled, sha1); 870/* 871 * Regardless of what the file header said, 872 * we definitely know the value of *this* 873 * reference: 874 */ 875 last->flag |= REF_KNOWS_PEELED; 876} 877} 878} 879 880static struct ref_dir *get_packed_refs(struct ref_cache *refs) 881{ 882if(!refs->packed) { 883const char*packed_refs_file; 884FILE*f; 885 886 refs->packed =create_dir_entry(refs,"",0,0); 887if(*refs->name) 888 packed_refs_file =git_path_submodule(refs->name,"packed-refs"); 889else 890 packed_refs_file =git_path("packed-refs"); 891 f =fopen(packed_refs_file,"r"); 892if(f) { 893read_packed_refs(f,get_ref_dir(refs->packed)); 894fclose(f); 895} 896} 897returnget_ref_dir(refs->packed); 898} 899 900voidadd_packed_ref(const char*refname,const unsigned char*sha1) 901{ 902add_ref(get_packed_refs(get_ref_cache(NULL)), 903create_ref_entry(refname, sha1, REF_ISPACKED,1)); 904} 905 906/* 907 * Read the loose references from the namespace dirname into dir 908 * (without recursing). dirname must end with '/'. dir must be the 909 * directory entry corresponding to dirname. 910 */ 911static voidread_loose_refs(const char*dirname,struct ref_dir *dir) 912{ 913struct ref_cache *refs = dir->ref_cache; 914DIR*d; 915const char*path; 916struct dirent *de; 917int dirnamelen =strlen(dirname); 918struct strbuf refname; 919 920if(*refs->name) 921 path =git_path_submodule(refs->name,"%s", dirname); 922else 923 path =git_path("%s", dirname); 924 925 d =opendir(path); 926if(!d) 927return; 928 929strbuf_init(&refname, dirnamelen +257); 930strbuf_add(&refname, dirname, dirnamelen); 931 932while((de =readdir(d)) != NULL) { 933unsigned char sha1[20]; 934struct stat st; 935int flag; 936const char*refdir; 937 938if(de->d_name[0] =='.') 939continue; 940if(has_extension(de->d_name,".lock")) 941continue; 942strbuf_addstr(&refname, de->d_name); 943 refdir = *refs->name 944?git_path_submodule(refs->name,"%s", refname.buf) 945:git_path("%s", refname.buf); 946if(stat(refdir, &st) <0) { 947;/* silently ignore */ 948}else if(S_ISDIR(st.st_mode)) { 949strbuf_addch(&refname,'/'); 950add_entry_to_dir(dir, 951create_dir_entry(refs, refname.buf, 952 refname.len,1)); 953}else{ 954if(*refs->name) { 955hashclr(sha1); 956 flag =0; 957if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) { 958hashclr(sha1); 959 flag |= REF_ISBROKEN; 960} 961}else if(read_ref_full(refname.buf, sha1,1, &flag)) { 962hashclr(sha1); 963 flag |= REF_ISBROKEN; 964} 965add_entry_to_dir(dir, 966create_ref_entry(refname.buf, sha1, flag,1)); 967} 968strbuf_setlen(&refname, dirnamelen); 969} 970strbuf_release(&refname); 971closedir(d); 972} 973 974static struct ref_dir *get_loose_refs(struct ref_cache *refs) 975{ 976if(!refs->loose) { 977/* 978 * Mark the top-level directory complete because we 979 * are about to read the only subdirectory that can 980 * hold references: 981 */ 982 refs->loose =create_dir_entry(refs,"",0,0); 983/* 984 * Create an incomplete entry for "refs/": 985 */ 986add_entry_to_dir(get_ref_dir(refs->loose), 987create_dir_entry(refs,"refs/",5,1)); 988} 989returnget_ref_dir(refs->loose); 990} 991 992/* We allow "recursive" symbolic refs. Only within reason, though */ 993#define MAXDEPTH 5 994#define MAXREFLEN (1024) 995 996/* 997 * Called by resolve_gitlink_ref_recursive() after it failed to read 998 * from the loose refs in ref_cache refs. Find <refname> in the 999 * packed-refs file for the submodule.1000 */1001static intresolve_gitlink_packed_ref(struct ref_cache *refs,1002const char*refname,unsigned char*sha1)1003{1004struct ref_entry *ref;1005struct ref_dir *dir =get_packed_refs(refs);10061007 ref =find_ref(dir, refname);1008if(ref == NULL)1009return-1;10101011memcpy(sha1, ref->u.value.sha1,20);1012return0;1013}10141015static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1016const char*refname,unsigned char*sha1,1017int recursion)1018{1019int fd, len;1020char buffer[128], *p;1021char*path;10221023if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1024return-1;1025 path = *refs->name1026?git_path_submodule(refs->name,"%s", refname)1027:git_path("%s", refname);1028 fd =open(path, O_RDONLY);1029if(fd <0)1030returnresolve_gitlink_packed_ref(refs, refname, sha1);10311032 len =read(fd, buffer,sizeof(buffer)-1);1033close(fd);1034if(len <0)1035return-1;1036while(len &&isspace(buffer[len-1]))1037 len--;1038 buffer[len] =0;10391040/* Was it a detached head or an old-fashioned symlink? */1041if(!get_sha1_hex(buffer, sha1))1042return0;10431044/* Symref? */1045if(strncmp(buffer,"ref:",4))1046return-1;1047 p = buffer +4;1048while(isspace(*p))1049 p++;10501051returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1052}10531054intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1055{1056int len =strlen(path), retval;1057char*submodule;1058struct ref_cache *refs;10591060while(len && path[len-1] =='/')1061 len--;1062if(!len)1063return-1;1064 submodule =xstrndup(path, len);1065 refs =get_ref_cache(submodule);1066free(submodule);10671068 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1069return retval;1070}10711072/*1073 * Try to read ref from the packed references. On success, set sha11074 * and return 0; otherwise, return -1.1075 */1076static intget_packed_ref(const char*refname,unsigned char*sha1)1077{1078struct ref_dir *packed =get_packed_refs(get_ref_cache(NULL));1079struct ref_entry *entry =find_ref(packed, refname);1080if(entry) {1081hashcpy(sha1, entry->u.value.sha1);1082return0;1083}1084return-1;1085}10861087const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1088{1089int depth = MAXDEPTH;1090 ssize_t len;1091char buffer[256];1092static char refname_buffer[256];10931094if(flag)1095*flag =0;10961097if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))1098return NULL;10991100for(;;) {1101char path[PATH_MAX];1102struct stat st;1103char*buf;1104int fd;11051106if(--depth <0)1107return NULL;11081109git_snpath(path,sizeof(path),"%s", refname);11101111if(lstat(path, &st) <0) {1112if(errno != ENOENT)1113return NULL;1114/*1115 * The loose reference file does not exist;1116 * check for a packed reference.1117 */1118if(!get_packed_ref(refname, sha1)) {1119if(flag)1120*flag |= REF_ISPACKED;1121return refname;1122}1123/* The reference is not a packed reference, either. */1124if(reading) {1125return NULL;1126}else{1127hashclr(sha1);1128return refname;1129}1130}11311132/* Follow "normalized" - ie "refs/.." symlinks by hand */1133if(S_ISLNK(st.st_mode)) {1134 len =readlink(path, buffer,sizeof(buffer)-1);1135if(len <0)1136return NULL;1137 buffer[len] =0;1138if(!prefixcmp(buffer,"refs/") &&1139!check_refname_format(buffer,0)) {1140strcpy(refname_buffer, buffer);1141 refname = refname_buffer;1142if(flag)1143*flag |= REF_ISSYMREF;1144continue;1145}1146}11471148/* Is it a directory? */1149if(S_ISDIR(st.st_mode)) {1150 errno = EISDIR;1151return NULL;1152}11531154/*1155 * Anything else, just open it and try to use it as1156 * a ref1157 */1158 fd =open(path, O_RDONLY);1159if(fd <0)1160return NULL;1161 len =read_in_full(fd, buffer,sizeof(buffer)-1);1162close(fd);1163if(len <0)1164return NULL;1165while(len &&isspace(buffer[len-1]))1166 len--;1167 buffer[len] ='\0';11681169/*1170 * Is it a symbolic ref?1171 */1172if(prefixcmp(buffer,"ref:"))1173break;1174if(flag)1175*flag |= REF_ISSYMREF;1176 buf = buffer +4;1177while(isspace(*buf))1178 buf++;1179if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1180if(flag)1181*flag |= REF_ISBROKEN;1182return NULL;1183}1184 refname =strcpy(refname_buffer, buf);1185}1186/* Please note that FETCH_HEAD has a second line containing other data. */1187if(get_sha1_hex(buffer, sha1) || (buffer[40] !='\0'&& !isspace(buffer[40]))) {1188if(flag)1189*flag |= REF_ISBROKEN;1190return NULL;1191}1192return refname;1193}11941195char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1196{1197const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1198return ret ?xstrdup(ret) : NULL;1199}12001201/* The argument to filter_refs */1202struct ref_filter {1203const char*pattern;1204 each_ref_fn *fn;1205void*cb_data;1206};12071208intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1209{1210if(resolve_ref_unsafe(refname, sha1, reading, flags))1211return0;1212return-1;1213}12141215intread_ref(const char*refname,unsigned char*sha1)1216{1217returnread_ref_full(refname, sha1,1, NULL);1218}12191220intref_exists(const char*refname)1221{1222unsigned char sha1[20];1223return!!resolve_ref_unsafe(refname, sha1,1, NULL);1224}12251226static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1227void*data)1228{1229struct ref_filter *filter = (struct ref_filter *)data;1230if(fnmatch(filter->pattern, refname,0))1231return0;1232return filter->fn(refname, sha1, flags, filter->cb_data);1233}12341235intpeel_ref(const char*refname,unsigned char*sha1)1236{1237int flag;1238unsigned char base[20];1239struct object *o;12401241if(current_ref && (current_ref->name == refname1242|| !strcmp(current_ref->name, refname))) {1243if(current_ref->flag & REF_KNOWS_PEELED) {1244if(is_null_sha1(current_ref->u.value.peeled))1245return-1;1246hashcpy(sha1, current_ref->u.value.peeled);1247return0;1248}1249hashcpy(base, current_ref->u.value.sha1);1250goto fallback;1251}12521253if(read_ref_full(refname, base,1, &flag))1254return-1;12551256if((flag & REF_ISPACKED)) {1257struct ref_dir *dir =get_packed_refs(get_ref_cache(NULL));1258struct ref_entry *r =find_ref(dir, refname);12591260if(r != NULL && r->flag & REF_KNOWS_PEELED) {1261hashcpy(sha1, r->u.value.peeled);1262return0;1263}1264}12651266fallback:1267 o =lookup_unknown_object(base);1268if(o->type == OBJ_NONE) {1269int type =sha1_object_info(base, NULL);1270if(type <0)1271return-1;1272 o->type = type;1273}12741275if(o->type == OBJ_TAG) {1276 o =deref_tag_noverify(o);1277if(o) {1278hashcpy(sha1, o->sha1);1279return0;1280}1281}1282return-1;1283}12841285struct warn_if_dangling_data {1286FILE*fp;1287const char*refname;1288const char*msg_fmt;1289};12901291static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1292int flags,void*cb_data)1293{1294struct warn_if_dangling_data *d = cb_data;1295const char*resolves_to;1296unsigned char junk[20];12971298if(!(flags & REF_ISSYMREF))1299return0;13001301 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1302if(!resolves_to ||strcmp(resolves_to, d->refname))1303return0;13041305fprintf(d->fp, d->msg_fmt, refname);1306fputc('\n', d->fp);1307return0;1308}13091310voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1311{1312struct warn_if_dangling_data data;13131314 data.fp = fp;1315 data.refname = refname;1316 data.msg_fmt = msg_fmt;1317for_each_rawref(warn_if_dangling_symref, &data);1318}13191320static intdo_for_each_ref(const char*submodule,const char*base, each_ref_fn fn,1321int trim,int flags,void*cb_data)1322{1323struct ref_cache *refs =get_ref_cache(submodule);1324struct ref_dir *packed_dir =get_packed_refs(refs);1325struct ref_dir *loose_dir =get_loose_refs(refs);1326int retval =0;13271328if(base && *base) {1329 packed_dir =find_containing_dir(packed_dir, base,0);1330 loose_dir =find_containing_dir(loose_dir, base,0);1331}13321333if(packed_dir && loose_dir) {1334sort_ref_dir(packed_dir);1335sort_ref_dir(loose_dir);1336 retval =do_for_each_ref_in_dirs(1337 packed_dir, loose_dir,1338 base, fn, trim, flags, cb_data);1339}else if(packed_dir) {1340sort_ref_dir(packed_dir);1341 retval =do_for_each_ref_in_dir(1342 packed_dir,0,1343 base, fn, trim, flags, cb_data);1344}else if(loose_dir) {1345sort_ref_dir(loose_dir);1346 retval =do_for_each_ref_in_dir(1347 loose_dir,0,1348 base, fn, trim, flags, cb_data);1349}13501351return retval;1352}13531354static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1355{1356unsigned char sha1[20];1357int flag;13581359if(submodule) {1360if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1361returnfn("HEAD", sha1,0, cb_data);13621363return0;1364}13651366if(!read_ref_full("HEAD", sha1,1, &flag))1367returnfn("HEAD", sha1, flag, cb_data);13681369return0;1370}13711372inthead_ref(each_ref_fn fn,void*cb_data)1373{1374returndo_head_ref(NULL, fn, cb_data);1375}13761377inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1378{1379returndo_head_ref(submodule, fn, cb_data);1380}13811382intfor_each_ref(each_ref_fn fn,void*cb_data)1383{1384returndo_for_each_ref(NULL,"", fn,0,0, cb_data);1385}13861387intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1388{1389returndo_for_each_ref(submodule,"", fn,0,0, cb_data);1390}13911392intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1393{1394returndo_for_each_ref(NULL, prefix, fn,strlen(prefix),0, cb_data);1395}13961397intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1398 each_ref_fn fn,void*cb_data)1399{1400returndo_for_each_ref(submodule, prefix, fn,strlen(prefix),0, cb_data);1401}14021403intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1404{1405returnfor_each_ref_in("refs/tags/", fn, cb_data);1406}14071408intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1409{1410returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1411}14121413intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1414{1415returnfor_each_ref_in("refs/heads/", fn, cb_data);1416}14171418intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1419{1420returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1421}14221423intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1424{1425returnfor_each_ref_in("refs/remotes/", fn, cb_data);1426}14271428intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1429{1430returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1431}14321433intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1434{1435returndo_for_each_ref(NULL,"refs/replace/", fn,13,0, cb_data);1436}14371438inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1439{1440struct strbuf buf = STRBUF_INIT;1441int ret =0;1442unsigned char sha1[20];1443int flag;14441445strbuf_addf(&buf,"%sHEAD",get_git_namespace());1446if(!read_ref_full(buf.buf, sha1,1, &flag))1447 ret =fn(buf.buf, sha1, flag, cb_data);1448strbuf_release(&buf);14491450return ret;1451}14521453intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1454{1455struct strbuf buf = STRBUF_INIT;1456int ret;1457strbuf_addf(&buf,"%srefs/",get_git_namespace());1458 ret =do_for_each_ref(NULL, buf.buf, fn,0,0, cb_data);1459strbuf_release(&buf);1460return ret;1461}14621463intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1464const char*prefix,void*cb_data)1465{1466struct strbuf real_pattern = STRBUF_INIT;1467struct ref_filter filter;1468int ret;14691470if(!prefix &&prefixcmp(pattern,"refs/"))1471strbuf_addstr(&real_pattern,"refs/");1472else if(prefix)1473strbuf_addstr(&real_pattern, prefix);1474strbuf_addstr(&real_pattern, pattern);14751476if(!has_glob_specials(pattern)) {1477/* Append implied '/' '*' if not present. */1478if(real_pattern.buf[real_pattern.len -1] !='/')1479strbuf_addch(&real_pattern,'/');1480/* No need to check for '*', there is none. */1481strbuf_addch(&real_pattern,'*');1482}14831484 filter.pattern = real_pattern.buf;1485 filter.fn = fn;1486 filter.cb_data = cb_data;1487 ret =for_each_ref(filter_refs, &filter);14881489strbuf_release(&real_pattern);1490return ret;1491}14921493intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1494{1495returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1496}14971498intfor_each_rawref(each_ref_fn fn,void*cb_data)1499{1500returndo_for_each_ref(NULL,"", fn,0,1501 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1502}15031504const char*prettify_refname(const char*name)1505{1506return name + (1507!prefixcmp(name,"refs/heads/") ?11:1508!prefixcmp(name,"refs/tags/") ?10:1509!prefixcmp(name,"refs/remotes/") ?13:15100);1511}15121513const char*ref_rev_parse_rules[] = {1514"%.*s",1515"refs/%.*s",1516"refs/tags/%.*s",1517"refs/heads/%.*s",1518"refs/remotes/%.*s",1519"refs/remotes/%.*s/HEAD",1520 NULL1521};15221523intrefname_match(const char*abbrev_name,const char*full_name,const char**rules)1524{1525const char**p;1526const int abbrev_name_len =strlen(abbrev_name);15271528for(p = rules; *p; p++) {1529if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {1530return1;1531}1532}15331534return0;1535}15361537static struct ref_lock *verify_lock(struct ref_lock *lock,1538const unsigned char*old_sha1,int mustexist)1539{1540if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {1541error("Can't verify ref%s", lock->ref_name);1542unlock_ref(lock);1543return NULL;1544}1545if(hashcmp(lock->old_sha1, old_sha1)) {1546error("Ref%sis at%sbut expected%s", lock->ref_name,1547sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));1548unlock_ref(lock);1549return NULL;1550}1551return lock;1552}15531554static intremove_empty_directories(const char*file)1555{1556/* we want to create a file but there is a directory there;1557 * if that is an empty directory (or a directory that contains1558 * only empty directories), remove them.1559 */1560struct strbuf path;1561int result;15621563strbuf_init(&path,20);1564strbuf_addstr(&path, file);15651566 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);15671568strbuf_release(&path);15691570return result;1571}15721573/*1574 * *string and *len will only be substituted, and *string returned (for1575 * later free()ing) if the string passed in is a magic short-hand form1576 * to name a branch.1577 */1578static char*substitute_branch_name(const char**string,int*len)1579{1580struct strbuf buf = STRBUF_INIT;1581int ret =interpret_branch_name(*string, &buf);15821583if(ret == *len) {1584size_t size;1585*string =strbuf_detach(&buf, &size);1586*len = size;1587return(char*)*string;1588}15891590return NULL;1591}15921593intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)1594{1595char*last_branch =substitute_branch_name(&str, &len);1596const char**p, *r;1597int refs_found =0;15981599*ref = NULL;1600for(p = ref_rev_parse_rules; *p; p++) {1601char fullref[PATH_MAX];1602unsigned char sha1_from_ref[20];1603unsigned char*this_result;1604int flag;16051606 this_result = refs_found ? sha1_from_ref : sha1;1607mksnpath(fullref,sizeof(fullref), *p, len, str);1608 r =resolve_ref_unsafe(fullref, this_result,1, &flag);1609if(r) {1610if(!refs_found++)1611*ref =xstrdup(r);1612if(!warn_ambiguous_refs)1613break;1614}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {1615warning("ignoring dangling symref%s.", fullref);1616}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {1617warning("ignoring broken ref%s.", fullref);1618}1619}1620free(last_branch);1621return refs_found;1622}16231624intdwim_log(const char*str,int len,unsigned char*sha1,char**log)1625{1626char*last_branch =substitute_branch_name(&str, &len);1627const char**p;1628int logs_found =0;16291630*log = NULL;1631for(p = ref_rev_parse_rules; *p; p++) {1632struct stat st;1633unsigned char hash[20];1634char path[PATH_MAX];1635const char*ref, *it;16361637mksnpath(path,sizeof(path), *p, len, str);1638 ref =resolve_ref_unsafe(path, hash,1, NULL);1639if(!ref)1640continue;1641if(!stat(git_path("logs/%s", path), &st) &&1642S_ISREG(st.st_mode))1643 it = path;1644else if(strcmp(ref, path) &&1645!stat(git_path("logs/%s", ref), &st) &&1646S_ISREG(st.st_mode))1647 it = ref;1648else1649continue;1650if(!logs_found++) {1651*log =xstrdup(it);1652hashcpy(sha1, hash);1653}1654if(!warn_ambiguous_refs)1655break;1656}1657free(last_branch);1658return logs_found;1659}16601661static struct ref_lock *lock_ref_sha1_basic(const char*refname,1662const unsigned char*old_sha1,1663int flags,int*type_p)1664{1665char*ref_file;1666const char*orig_refname = refname;1667struct ref_lock *lock;1668int last_errno =0;1669int type, lflags;1670int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1671int missing =0;16721673 lock =xcalloc(1,sizeof(struct ref_lock));1674 lock->lock_fd = -1;16751676 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);1677if(!refname && errno == EISDIR) {1678/* we are trying to lock foo but we used to1679 * have foo/bar which now does not exist;1680 * it is normal for the empty directory 'foo'1681 * to remain.1682 */1683 ref_file =git_path("%s", orig_refname);1684if(remove_empty_directories(ref_file)) {1685 last_errno = errno;1686error("there are still refs under '%s'", orig_refname);1687goto error_return;1688}1689 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);1690}1691if(type_p)1692*type_p = type;1693if(!refname) {1694 last_errno = errno;1695error("unable to resolve reference%s:%s",1696 orig_refname,strerror(errno));1697goto error_return;1698}1699 missing =is_null_sha1(lock->old_sha1);1700/* When the ref did not exist and we are creating it,1701 * make sure there is no existing ref that is packed1702 * whose name begins with our refname, nor a ref whose1703 * name is a proper prefix of our refname.1704 */1705if(missing &&1706!is_refname_available(refname, NULL,get_packed_refs(get_ref_cache(NULL)))) {1707 last_errno = ENOTDIR;1708goto error_return;1709}17101711 lock->lk =xcalloc(1,sizeof(struct lock_file));17121713 lflags = LOCK_DIE_ON_ERROR;1714if(flags & REF_NODEREF) {1715 refname = orig_refname;1716 lflags |= LOCK_NODEREF;1717}1718 lock->ref_name =xstrdup(refname);1719 lock->orig_ref_name =xstrdup(orig_refname);1720 ref_file =git_path("%s", refname);1721if(missing)1722 lock->force_write =1;1723if((flags & REF_NODEREF) && (type & REF_ISSYMREF))1724 lock->force_write =1;17251726if(safe_create_leading_directories(ref_file)) {1727 last_errno = errno;1728error("unable to create directory for%s", ref_file);1729goto error_return;1730}17311732 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);1733return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;17341735 error_return:1736unlock_ref(lock);1737 errno = last_errno;1738return NULL;1739}17401741struct ref_lock *lock_ref_sha1(const char*refname,const unsigned char*old_sha1)1742{1743char refpath[PATH_MAX];1744if(check_refname_format(refname,0))1745return NULL;1746strcpy(refpath,mkpath("refs/%s", refname));1747returnlock_ref_sha1_basic(refpath, old_sha1,0, NULL);1748}17491750struct ref_lock *lock_any_ref_for_update(const char*refname,1751const unsigned char*old_sha1,int flags)1752{1753if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))1754return NULL;1755returnlock_ref_sha1_basic(refname, old_sha1, flags, NULL);1756}17571758struct repack_without_ref_sb {1759const char*refname;1760int fd;1761};17621763static intrepack_without_ref_fn(const char*refname,const unsigned char*sha1,1764int flags,void*cb_data)1765{1766struct repack_without_ref_sb *data = cb_data;1767char line[PATH_MAX +100];1768int len;17691770if(!strcmp(data->refname, refname))1771return0;1772 len =snprintf(line,sizeof(line),"%s %s\n",1773sha1_to_hex(sha1), refname);1774/* this should not happen but just being defensive */1775if(len >sizeof(line))1776die("too long a refname '%s'", refname);1777write_or_die(data->fd, line, len);1778return0;1779}17801781static struct lock_file packlock;17821783static intrepack_without_ref(const char*refname)1784{1785struct repack_without_ref_sb data;1786struct ref_cache *refs =get_ref_cache(NULL);1787struct ref_dir *packed =get_packed_refs(refs);1788if(find_ref(packed, refname) == NULL)1789return0;1790 data.refname = refname;1791 data.fd =hold_lock_file_for_update(&packlock,git_path("packed-refs"),0);1792if(data.fd <0) {1793unable_to_lock_error(git_path("packed-refs"), errno);1794returnerror("cannot delete '%s' from packed refs", refname);1795}1796clear_packed_ref_cache(refs);1797 packed =get_packed_refs(refs);1798do_for_each_ref_in_dir(packed,0,"", repack_without_ref_fn,0,0, &data);1799returncommit_lock_file(&packlock);1800}18011802intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)1803{1804struct ref_lock *lock;1805int err, i =0, ret =0, flag =0;18061807 lock =lock_ref_sha1_basic(refname, sha1, delopt, &flag);1808if(!lock)1809return1;1810if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {1811/* loose */1812 i =strlen(lock->lk->filename) -5;/* .lock */1813 lock->lk->filename[i] =0;1814 err =unlink_or_warn(lock->lk->filename);1815if(err && errno != ENOENT)1816 ret =1;18171818 lock->lk->filename[i] ='.';1819}1820/* removing the loose one could have resurrected an earlier1821 * packed one. Also, if it was not loose we need to repack1822 * without it.1823 */1824 ret |=repack_without_ref(lock->ref_name);18251826unlink_or_warn(git_path("logs/%s", lock->ref_name));1827invalidate_ref_cache(NULL);1828unlock_ref(lock);1829return ret;1830}18311832/*1833 * People using contrib's git-new-workdir have .git/logs/refs ->1834 * /some/other/path/.git/logs/refs, and that may live on another device.1835 *1836 * IOW, to avoid cross device rename errors, the temporary renamed log must1837 * live into logs/refs.1838 */1839#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"18401841intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)1842{1843unsigned char sha1[20], orig_sha1[20];1844int flag =0, logmoved =0;1845struct ref_lock *lock;1846struct stat loginfo;1847int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);1848const char*symref = NULL;1849struct ref_cache *refs =get_ref_cache(NULL);18501851if(log &&S_ISLNK(loginfo.st_mode))1852returnerror("reflog for%sis a symlink", oldrefname);18531854 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);1855if(flag & REF_ISSYMREF)1856returnerror("refname%sis a symbolic ref, renaming it is not supported",1857 oldrefname);1858if(!symref)1859returnerror("refname%snot found", oldrefname);18601861if(!is_refname_available(newrefname, oldrefname,get_packed_refs(refs)))1862return1;18631864if(!is_refname_available(newrefname, oldrefname,get_loose_refs(refs)))1865return1;18661867if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))1868returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",1869 oldrefname,strerror(errno));18701871if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {1872error("unable to delete old%s", oldrefname);1873goto rollback;1874}18751876if(!read_ref_full(newrefname, sha1,1, &flag) &&1877delete_ref(newrefname, sha1, REF_NODEREF)) {1878if(errno==EISDIR) {1879if(remove_empty_directories(git_path("%s", newrefname))) {1880error("Directory not empty:%s", newrefname);1881goto rollback;1882}1883}else{1884error("unable to delete existing%s", newrefname);1885goto rollback;1886}1887}18881889if(log &&safe_create_leading_directories(git_path("logs/%s", newrefname))) {1890error("unable to create directory for%s", newrefname);1891goto rollback;1892}18931894 retry:1895if(log &&rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {1896if(errno==EISDIR || errno==ENOTDIR) {1897/*1898 * rename(a, b) when b is an existing1899 * directory ought to result in ISDIR, but1900 * Solaris 5.8 gives ENOTDIR. Sheesh.1901 */1902if(remove_empty_directories(git_path("logs/%s", newrefname))) {1903error("Directory not empty: logs/%s", newrefname);1904goto rollback;1905}1906goto retry;1907}else{1908error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",1909 newrefname,strerror(errno));1910goto rollback;1911}1912}1913 logmoved = log;19141915 lock =lock_ref_sha1_basic(newrefname, NULL,0, NULL);1916if(!lock) {1917error("unable to lock%sfor update", newrefname);1918goto rollback;1919}1920 lock->force_write =1;1921hashcpy(lock->old_sha1, orig_sha1);1922if(write_ref_sha1(lock, orig_sha1, logmsg)) {1923error("unable to write current sha1 into%s", newrefname);1924goto rollback;1925}19261927return0;19281929 rollback:1930 lock =lock_ref_sha1_basic(oldrefname, NULL,0, NULL);1931if(!lock) {1932error("unable to lock%sfor rollback", oldrefname);1933goto rollbacklog;1934}19351936 lock->force_write =1;1937 flag = log_all_ref_updates;1938 log_all_ref_updates =0;1939if(write_ref_sha1(lock, orig_sha1, NULL))1940error("unable to write current sha1 into%s", oldrefname);1941 log_all_ref_updates = flag;19421943 rollbacklog:1944if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))1945error("unable to restore logfile%sfrom%s:%s",1946 oldrefname, newrefname,strerror(errno));1947if(!logmoved && log &&1948rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))1949error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",1950 oldrefname,strerror(errno));19511952return1;1953}19541955intclose_ref(struct ref_lock *lock)1956{1957if(close_lock_file(lock->lk))1958return-1;1959 lock->lock_fd = -1;1960return0;1961}19621963intcommit_ref(struct ref_lock *lock)1964{1965if(commit_lock_file(lock->lk))1966return-1;1967 lock->lock_fd = -1;1968return0;1969}19701971voidunlock_ref(struct ref_lock *lock)1972{1973/* Do not free lock->lk -- atexit() still looks at them */1974if(lock->lk)1975rollback_lock_file(lock->lk);1976free(lock->ref_name);1977free(lock->orig_ref_name);1978free(lock);1979}19801981/*1982 * copy the reflog message msg to buf, which has been allocated sufficiently1983 * large, while cleaning up the whitespaces. Especially, convert LF to space,1984 * because reflog file is one line per entry.1985 */1986static intcopy_msg(char*buf,const char*msg)1987{1988char*cp = buf;1989char c;1990int wasspace =1;19911992*cp++ ='\t';1993while((c = *msg++)) {1994if(wasspace &&isspace(c))1995continue;1996 wasspace =isspace(c);1997if(wasspace)1998 c =' ';1999*cp++ = c;2000}2001while(buf < cp &&isspace(cp[-1]))2002 cp--;2003*cp++ ='\n';2004return cp - buf;2005}20062007intlog_ref_setup(const char*refname,char*logfile,int bufsize)2008{2009int logfd, oflags = O_APPEND | O_WRONLY;20102011git_snpath(logfile, bufsize,"logs/%s", refname);2012if(log_all_ref_updates &&2013(!prefixcmp(refname,"refs/heads/") ||2014!prefixcmp(refname,"refs/remotes/") ||2015!prefixcmp(refname,"refs/notes/") ||2016!strcmp(refname,"HEAD"))) {2017if(safe_create_leading_directories(logfile) <0)2018returnerror("unable to create directory for%s",2019 logfile);2020 oflags |= O_CREAT;2021}20222023 logfd =open(logfile, oflags,0666);2024if(logfd <0) {2025if(!(oflags & O_CREAT) && errno == ENOENT)2026return0;20272028if((oflags & O_CREAT) && errno == EISDIR) {2029if(remove_empty_directories(logfile)) {2030returnerror("There are still logs under '%s'",2031 logfile);2032}2033 logfd =open(logfile, oflags,0666);2034}20352036if(logfd <0)2037returnerror("Unable to append to%s:%s",2038 logfile,strerror(errno));2039}20402041adjust_shared_perm(logfile);2042close(logfd);2043return0;2044}20452046static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2047const unsigned char*new_sha1,const char*msg)2048{2049int logfd, result, written, oflags = O_APPEND | O_WRONLY;2050unsigned maxlen, len;2051int msglen;2052char log_file[PATH_MAX];2053char*logrec;2054const char*committer;20552056if(log_all_ref_updates <0)2057 log_all_ref_updates = !is_bare_repository();20582059 result =log_ref_setup(refname, log_file,sizeof(log_file));2060if(result)2061return result;20622063 logfd =open(log_file, oflags);2064if(logfd <0)2065return0;2066 msglen = msg ?strlen(msg) :0;2067 committer =git_committer_info(0);2068 maxlen =strlen(committer) + msglen +100;2069 logrec =xmalloc(maxlen);2070 len =sprintf(logrec,"%s %s %s\n",2071sha1_to_hex(old_sha1),2072sha1_to_hex(new_sha1),2073 committer);2074if(msglen)2075 len +=copy_msg(logrec + len -1, msg) -1;2076 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2077free(logrec);2078if(close(logfd) !=0|| written != len)2079returnerror("Unable to append to%s", log_file);2080return0;2081}20822083static intis_branch(const char*refname)2084{2085return!strcmp(refname,"HEAD") || !prefixcmp(refname,"refs/heads/");2086}20872088intwrite_ref_sha1(struct ref_lock *lock,2089const unsigned char*sha1,const char*logmsg)2090{2091static char term ='\n';2092struct object *o;20932094if(!lock)2095return-1;2096if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2097unlock_ref(lock);2098return0;2099}2100 o =parse_object(sha1);2101if(!o) {2102error("Trying to write ref%swith nonexistent object%s",2103 lock->ref_name,sha1_to_hex(sha1));2104unlock_ref(lock);2105return-1;2106}2107if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2108error("Trying to write non-commit object%sto branch%s",2109sha1_to_hex(sha1), lock->ref_name);2110unlock_ref(lock);2111return-1;2112}2113if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||2114write_in_full(lock->lock_fd, &term,1) !=12115||close_ref(lock) <0) {2116error("Couldn't write%s", lock->lk->filename);2117unlock_ref(lock);2118return-1;2119}2120clear_loose_ref_cache(get_ref_cache(NULL));2121if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||2122(strcmp(lock->ref_name, lock->orig_ref_name) &&2123log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {2124unlock_ref(lock);2125return-1;2126}2127if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2128/*2129 * Special hack: If a branch is updated directly and HEAD2130 * points to it (may happen on the remote side of a push2131 * for example) then logically the HEAD reflog should be2132 * updated too.2133 * A generic solution implies reverse symref information,2134 * but finding all symrefs pointing to the given branch2135 * would be rather costly for this rare event (the direct2136 * update of a branch) to be worth it. So let's cheat and2137 * check with HEAD only which should cover 99% of all usage2138 * scenarios (even 100% of the default ones).2139 */2140unsigned char head_sha1[20];2141int head_flag;2142const char*head_ref;2143 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);2144if(head_ref && (head_flag & REF_ISSYMREF) &&2145!strcmp(head_ref, lock->ref_name))2146log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);2147}2148if(commit_ref(lock)) {2149error("Couldn't set%s", lock->ref_name);2150unlock_ref(lock);2151return-1;2152}2153unlock_ref(lock);2154return0;2155}21562157intcreate_symref(const char*ref_target,const char*refs_heads_master,2158const char*logmsg)2159{2160const char*lockpath;2161char ref[1000];2162int fd, len, written;2163char*git_HEAD =git_pathdup("%s", ref_target);2164unsigned char old_sha1[20], new_sha1[20];21652166if(logmsg &&read_ref(ref_target, old_sha1))2167hashclr(old_sha1);21682169if(safe_create_leading_directories(git_HEAD) <0)2170returnerror("unable to create directory for%s", git_HEAD);21712172#ifndef NO_SYMLINK_HEAD2173if(prefer_symlink_refs) {2174unlink(git_HEAD);2175if(!symlink(refs_heads_master, git_HEAD))2176goto done;2177fprintf(stderr,"no symlink - falling back to symbolic ref\n");2178}2179#endif21802181 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);2182if(sizeof(ref) <= len) {2183error("refname too long:%s", refs_heads_master);2184goto error_free_return;2185}2186 lockpath =mkpath("%s.lock", git_HEAD);2187 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);2188if(fd <0) {2189error("Unable to open%sfor writing", lockpath);2190goto error_free_return;2191}2192 written =write_in_full(fd, ref, len);2193if(close(fd) !=0|| written != len) {2194error("Unable to write to%s", lockpath);2195goto error_unlink_return;2196}2197if(rename(lockpath, git_HEAD) <0) {2198error("Unable to create%s", git_HEAD);2199goto error_unlink_return;2200}2201if(adjust_shared_perm(git_HEAD)) {2202error("Unable to fix permissions on%s", lockpath);2203 error_unlink_return:2204unlink_or_warn(lockpath);2205 error_free_return:2206free(git_HEAD);2207return-1;2208}22092210#ifndef NO_SYMLINK_HEAD2211 done:2212#endif2213if(logmsg && !read_ref(refs_heads_master, new_sha1))2214log_ref_write(ref_target, old_sha1, new_sha1, logmsg);22152216free(git_HEAD);2217return0;2218}22192220static char*ref_msg(const char*line,const char*endp)2221{2222const char*ep;2223 line +=82;2224 ep =memchr(line,'\n', endp - line);2225if(!ep)2226 ep = endp;2227returnxmemdupz(line, ep - line);2228}22292230intread_ref_at(const char*refname,unsigned long at_time,int cnt,2231unsigned char*sha1,char**msg,2232unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)2233{2234const char*logfile, *logdata, *logend, *rec, *lastgt, *lastrec;2235char*tz_c;2236int logfd, tz, reccnt =0;2237struct stat st;2238unsigned long date;2239unsigned char logged_sha1[20];2240void*log_mapped;2241size_t mapsz;22422243 logfile =git_path("logs/%s", refname);2244 logfd =open(logfile, O_RDONLY,0);2245if(logfd <0)2246die_errno("Unable to read log '%s'", logfile);2247fstat(logfd, &st);2248if(!st.st_size)2249die("Log%sis empty.", logfile);2250 mapsz =xsize_t(st.st_size);2251 log_mapped =xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd,0);2252 logdata = log_mapped;2253close(logfd);22542255 lastrec = NULL;2256 rec = logend = logdata + st.st_size;2257while(logdata < rec) {2258 reccnt++;2259if(logdata < rec && *(rec-1) =='\n')2260 rec--;2261 lastgt = NULL;2262while(logdata < rec && *(rec-1) !='\n') {2263 rec--;2264if(*rec =='>')2265 lastgt = rec;2266}2267if(!lastgt)2268die("Log%sis corrupt.", logfile);2269 date =strtoul(lastgt +1, &tz_c,10);2270if(date <= at_time || cnt ==0) {2271 tz =strtoul(tz_c, NULL,10);2272if(msg)2273*msg =ref_msg(rec, logend);2274if(cutoff_time)2275*cutoff_time = date;2276if(cutoff_tz)2277*cutoff_tz = tz;2278if(cutoff_cnt)2279*cutoff_cnt = reccnt -1;2280if(lastrec) {2281if(get_sha1_hex(lastrec, logged_sha1))2282die("Log%sis corrupt.", logfile);2283if(get_sha1_hex(rec +41, sha1))2284die("Log%sis corrupt.", logfile);2285if(hashcmp(logged_sha1, sha1)) {2286warning("Log%shas gap after%s.",2287 logfile,show_date(date, tz, DATE_RFC2822));2288}2289}2290else if(date == at_time) {2291if(get_sha1_hex(rec +41, sha1))2292die("Log%sis corrupt.", logfile);2293}2294else{2295if(get_sha1_hex(rec +41, logged_sha1))2296die("Log%sis corrupt.", logfile);2297if(hashcmp(logged_sha1, sha1)) {2298warning("Log%sunexpectedly ended on%s.",2299 logfile,show_date(date, tz, DATE_RFC2822));2300}2301}2302munmap(log_mapped, mapsz);2303return0;2304}2305 lastrec = rec;2306if(cnt >0)2307 cnt--;2308}23092310 rec = logdata;2311while(rec < logend && *rec !='>'&& *rec !='\n')2312 rec++;2313if(rec == logend || *rec =='\n')2314die("Log%sis corrupt.", logfile);2315 date =strtoul(rec +1, &tz_c,10);2316 tz =strtoul(tz_c, NULL,10);2317if(get_sha1_hex(logdata, sha1))2318die("Log%sis corrupt.", logfile);2319if(is_null_sha1(sha1)) {2320if(get_sha1_hex(logdata +41, sha1))2321die("Log%sis corrupt.", logfile);2322}2323if(msg)2324*msg =ref_msg(logdata, logend);2325munmap(log_mapped, mapsz);23262327if(cutoff_time)2328*cutoff_time = date;2329if(cutoff_tz)2330*cutoff_tz = tz;2331if(cutoff_cnt)2332*cutoff_cnt = reccnt;2333return1;2334}23352336intfor_each_recent_reflog_ent(const char*refname, each_reflog_ent_fn fn,long ofs,void*cb_data)2337{2338const char*logfile;2339FILE*logfp;2340struct strbuf sb = STRBUF_INIT;2341int ret =0;23422343 logfile =git_path("logs/%s", refname);2344 logfp =fopen(logfile,"r");2345if(!logfp)2346return-1;23472348if(ofs) {2349struct stat statbuf;2350if(fstat(fileno(logfp), &statbuf) ||2351 statbuf.st_size < ofs ||2352fseek(logfp, -ofs, SEEK_END) ||2353strbuf_getwholeline(&sb, logfp,'\n')) {2354fclose(logfp);2355strbuf_release(&sb);2356return-1;2357}2358}23592360while(!strbuf_getwholeline(&sb, logfp,'\n')) {2361unsigned char osha1[20], nsha1[20];2362char*email_end, *message;2363unsigned long timestamp;2364int tz;23652366/* old SP new SP name <email> SP time TAB msg LF */2367if(sb.len <83|| sb.buf[sb.len -1] !='\n'||2368get_sha1_hex(sb.buf, osha1) || sb.buf[40] !=' '||2369get_sha1_hex(sb.buf +41, nsha1) || sb.buf[81] !=' '||2370!(email_end =strchr(sb.buf +82,'>')) ||2371 email_end[1] !=' '||2372!(timestamp =strtoul(email_end +2, &message,10)) ||2373!message || message[0] !=' '||2374(message[1] !='+'&& message[1] !='-') ||2375!isdigit(message[2]) || !isdigit(message[3]) ||2376!isdigit(message[4]) || !isdigit(message[5]))2377continue;/* corrupt? */2378 email_end[1] ='\0';2379 tz =strtol(message +1, NULL,10);2380if(message[6] !='\t')2381 message +=6;2382else2383 message +=7;2384 ret =fn(osha1, nsha1, sb.buf +82, timestamp, tz, message,2385 cb_data);2386if(ret)2387break;2388}2389fclose(logfp);2390strbuf_release(&sb);2391return ret;2392}23932394intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2395{2396returnfor_each_recent_reflog_ent(refname, fn,0, cb_data);2397}23982399/*2400 * Call fn for each reflog in the namespace indicated by name. name2401 * must be empty or end with '/'. Name will be used as a scratch2402 * space, but its contents will be restored before return.2403 */2404static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)2405{2406DIR*d =opendir(git_path("logs/%s", name->buf));2407int retval =0;2408struct dirent *de;2409int oldlen = name->len;24102411if(!d)2412return name->len ? errno :0;24132414while((de =readdir(d)) != NULL) {2415struct stat st;24162417if(de->d_name[0] =='.')2418continue;2419if(has_extension(de->d_name,".lock"))2420continue;2421strbuf_addstr(name, de->d_name);2422if(stat(git_path("logs/%s", name->buf), &st) <0) {2423;/* silently ignore */2424}else{2425if(S_ISDIR(st.st_mode)) {2426strbuf_addch(name,'/');2427 retval =do_for_each_reflog(name, fn, cb_data);2428}else{2429unsigned char sha1[20];2430if(read_ref_full(name->buf, sha1,0, NULL))2431 retval =error("bad ref for%s", name->buf);2432else2433 retval =fn(name->buf, sha1,0, cb_data);2434}2435if(retval)2436break;2437}2438strbuf_setlen(name, oldlen);2439}2440closedir(d);2441return retval;2442}24432444intfor_each_reflog(each_ref_fn fn,void*cb_data)2445{2446int retval;2447struct strbuf name;2448strbuf_init(&name, PATH_MAX);2449 retval =do_for_each_reflog(&name, fn, cb_data);2450strbuf_release(&name);2451return retval;2452}24532454intupdate_ref(const char*action,const char*refname,2455const unsigned char*sha1,const unsigned char*oldval,2456int flags,enum action_on_err onerr)2457{2458static struct ref_lock *lock;2459 lock =lock_any_ref_for_update(refname, oldval, flags);2460if(!lock) {2461const char*str ="Cannot lock the ref '%s'.";2462switch(onerr) {2463case MSG_ON_ERR:error(str, refname);break;2464case DIE_ON_ERR:die(str, refname);break;2465case QUIET_ON_ERR:break;2466}2467return1;2468}2469if(write_ref_sha1(lock, sha1, action) <0) {2470const char*str ="Cannot update the ref '%s'.";2471switch(onerr) {2472case MSG_ON_ERR:error(str, refname);break;2473case DIE_ON_ERR:die(str, refname);break;2474case QUIET_ON_ERR:break;2475}2476return1;2477}2478return0;2479}24802481struct ref *find_ref_by_name(const struct ref *list,const char*name)2482{2483for( ; list; list = list->next)2484if(!strcmp(list->name, name))2485return(struct ref *)list;2486return NULL;2487}24882489/*2490 * generate a format suitable for scanf from a ref_rev_parse_rules2491 * rule, that is replace the "%.*s" spec with a "%s" spec2492 */2493static voidgen_scanf_fmt(char*scanf_fmt,const char*rule)2494{2495char*spec;24962497 spec =strstr(rule,"%.*s");2498if(!spec ||strstr(spec +4,"%.*s"))2499die("invalid rule in ref_rev_parse_rules:%s", rule);25002501/* copy all until spec */2502strncpy(scanf_fmt, rule, spec - rule);2503 scanf_fmt[spec - rule] ='\0';2504/* copy new spec */2505strcat(scanf_fmt,"%s");2506/* copy remaining rule */2507strcat(scanf_fmt, spec +4);25082509return;2510}25112512char*shorten_unambiguous_ref(const char*refname,int strict)2513{2514int i;2515static char**scanf_fmts;2516static int nr_rules;2517char*short_name;25182519/* pre generate scanf formats from ref_rev_parse_rules[] */2520if(!nr_rules) {2521size_t total_len =0;25222523/* the rule list is NULL terminated, count them first */2524for(; ref_rev_parse_rules[nr_rules]; nr_rules++)2525/* no +1 because strlen("%s") < strlen("%.*s") */2526 total_len +=strlen(ref_rev_parse_rules[nr_rules]);25272528 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);25292530 total_len =0;2531for(i =0; i < nr_rules; i++) {2532 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules]2533+ total_len;2534gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);2535 total_len +=strlen(ref_rev_parse_rules[i]);2536}2537}25382539/* bail out if there are no rules */2540if(!nr_rules)2541returnxstrdup(refname);25422543/* buffer for scanf result, at most refname must fit */2544 short_name =xstrdup(refname);25452546/* skip first rule, it will always match */2547for(i = nr_rules -1; i >0; --i) {2548int j;2549int rules_to_fail = i;2550int short_name_len;25512552if(1!=sscanf(refname, scanf_fmts[i], short_name))2553continue;25542555 short_name_len =strlen(short_name);25562557/*2558 * in strict mode, all (except the matched one) rules2559 * must fail to resolve to a valid non-ambiguous ref2560 */2561if(strict)2562 rules_to_fail = nr_rules;25632564/*2565 * check if the short name resolves to a valid ref,2566 * but use only rules prior to the matched one2567 */2568for(j =0; j < rules_to_fail; j++) {2569const char*rule = ref_rev_parse_rules[j];2570char refname[PATH_MAX];25712572/* skip matched rule */2573if(i == j)2574continue;25752576/*2577 * the short name is ambiguous, if it resolves2578 * (with this previous rule) to a valid ref2579 * read_ref() returns 0 on success2580 */2581mksnpath(refname,sizeof(refname),2582 rule, short_name_len, short_name);2583if(ref_exists(refname))2584break;2585}25862587/*2588 * short name is non-ambiguous if all previous rules2589 * haven't resolved to a valid ref2590 */2591if(j == rules_to_fail)2592return short_name;2593}25942595free(short_name);2596returnxstrdup(refname);2597}