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 75while(1) { 76/* We are at the start of a path component. */ 77 component_len =check_refname_component(refname, flags); 78if(component_len <=0) { 79if((flags & REFNAME_REFSPEC_PATTERN) && 80 refname[0] =='*'&& 81(refname[1] =='\0'|| refname[1] =='/')) { 82/* Accept one wildcard as a full refname component. */ 83 flags &= ~REFNAME_REFSPEC_PATTERN; 84 component_len =1; 85}else{ 86return-1; 87} 88} 89 component_count++; 90if(refname[component_len] =='\0') 91break; 92/* Skip to next component. */ 93 refname += component_len +1; 94} 95 96if(refname[component_len -1] =='.') 97return-1;/* Refname ends with '.'. */ 98if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 99return-1;/* Refname has only one component. */ 100return0; 101} 102 103struct ref_entry; 104 105/* 106 * Information used (along with the information in ref_entry) to 107 * describe a single cached reference. This data structure only 108 * occurs embedded in a union in struct ref_entry, and only when 109 * (ref_entry->flag & REF_DIR) is zero. 110 */ 111struct ref_value { 112unsigned char sha1[20]; 113unsigned char peeled[20]; 114}; 115 116struct ref_cache; 117 118/* 119 * Information used (along with the information in ref_entry) to 120 * describe a level in the hierarchy of references. This data 121 * structure only occurs embedded in a union in struct ref_entry, and 122 * only when (ref_entry.flag & REF_DIR) is set. In that case, 123 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 124 * in the directory have already been read: 125 * 126 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 127 * or packed references, already read. 128 * 129 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 130 * references that hasn't been read yet (nor has any of its 131 * subdirectories). 132 * 133 * Entries within a directory are stored within a growable array of 134 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 135 * sorted are sorted by their component name in strcmp() order and the 136 * remaining entries are unsorted. 137 * 138 * Loose references are read lazily, one directory at a time. When a 139 * directory of loose references is read, then all of the references 140 * in that directory are stored, and REF_INCOMPLETE stubs are created 141 * for any subdirectories, but the subdirectories themselves are not 142 * read. The reading is triggered by get_ref_dir(). 143 */ 144struct ref_dir { 145int nr, alloc; 146 147/* 148 * Entries with index 0 <= i < sorted are sorted by name. New 149 * entries are appended to the list unsorted, and are sorted 150 * only when required; thus we avoid the need to sort the list 151 * after the addition of every reference. 152 */ 153int sorted; 154 155/* A pointer to the ref_cache that contains this ref_dir. */ 156struct ref_cache *ref_cache; 157 158struct ref_entry **entries; 159}; 160 161/* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */ 162#define REF_KNOWS_PEELED 0x08 163 164/* ref_entry represents a directory of references */ 165#define REF_DIR 0x10 166 167/* 168 * Entry has not yet been read from disk (used only for REF_DIR 169 * entries representing loose references) 170 */ 171#define REF_INCOMPLETE 0x20 172 173/* 174 * A ref_entry represents either a reference or a "subdirectory" of 175 * references. 176 * 177 * Each directory in the reference namespace is represented by a 178 * ref_entry with (flags & REF_DIR) set and containing a subdir member 179 * that holds the entries in that directory that have been read so 180 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 181 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 182 * used for loose reference directories. 183 * 184 * References are represented by a ref_entry with (flags & REF_DIR) 185 * unset and a value member that describes the reference's value. The 186 * flag member is at the ref_entry level, but it is also needed to 187 * interpret the contents of the value field (in other words, a 188 * ref_value object is not very much use without the enclosing 189 * ref_entry). 190 * 191 * Reference names cannot end with slash and directories' names are 192 * always stored with a trailing slash (except for the top-level 193 * directory, which is always denoted by ""). This has two nice 194 * consequences: (1) when the entries in each subdir are sorted 195 * lexicographically by name (as they usually are), the references in 196 * a whole tree can be generated in lexicographic order by traversing 197 * the tree in left-to-right, depth-first order; (2) the names of 198 * references and subdirectories cannot conflict, and therefore the 199 * presence of an empty subdirectory does not block the creation of a 200 * similarly-named reference. (The fact that reference names with the 201 * same leading components can conflict *with each other* is a 202 * separate issue that is regulated by is_refname_available().) 203 * 204 * Please note that the name field contains the fully-qualified 205 * reference (or subdirectory) name. Space could be saved by only 206 * storing the relative names. But that would require the full names 207 * to be generated on the fly when iterating in do_for_each_ref(), and 208 * would break callback functions, who have always been able to assume 209 * that the name strings that they are passed will not be freed during 210 * the iteration. 211 */ 212struct ref_entry { 213unsigned char flag;/* ISSYMREF? ISPACKED? */ 214union{ 215struct ref_value value;/* if not (flags&REF_DIR) */ 216struct ref_dir subdir;/* if (flags&REF_DIR) */ 217} u; 218/* 219 * The full name of the reference (e.g., "refs/heads/master") 220 * or the full name of the directory with a trailing slash 221 * (e.g., "refs/heads/"): 222 */ 223char name[FLEX_ARRAY]; 224}; 225 226static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 227 228static struct ref_dir *get_ref_dir(struct ref_entry *entry) 229{ 230struct ref_dir *dir; 231assert(entry->flag & REF_DIR); 232 dir = &entry->u.subdir; 233if(entry->flag & REF_INCOMPLETE) { 234read_loose_refs(entry->name, dir); 235 entry->flag &= ~REF_INCOMPLETE; 236} 237return dir; 238} 239 240static struct ref_entry *create_ref_entry(const char*refname, 241const unsigned char*sha1,int flag, 242int check_name) 243{ 244int len; 245struct ref_entry *ref; 246 247if(check_name && 248check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 249die("Reference has invalid format: '%s'", refname); 250 len =strlen(refname) +1; 251 ref =xmalloc(sizeof(struct ref_entry) + len); 252hashcpy(ref->u.value.sha1, sha1); 253hashclr(ref->u.value.peeled); 254memcpy(ref->name, refname, len); 255 ref->flag = flag; 256return ref; 257} 258 259static voidclear_ref_dir(struct ref_dir *dir); 260 261static voidfree_ref_entry(struct ref_entry *entry) 262{ 263if(entry->flag & REF_DIR) { 264/* 265 * Do not use get_ref_dir() here, as that might 266 * trigger the reading of loose refs. 267 */ 268clear_ref_dir(&entry->u.subdir); 269} 270free(entry); 271} 272 273/* 274 * Add a ref_entry to the end of dir (unsorted). Entry is always 275 * stored directly in dir; no recursion into subdirectories is 276 * done. 277 */ 278static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 279{ 280ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 281 dir->entries[dir->nr++] = entry; 282/* optimize for the case that entries are added in order */ 283if(dir->nr ==1|| 284(dir->nr == dir->sorted +1&& 285strcmp(dir->entries[dir->nr -2]->name, 286 dir->entries[dir->nr -1]->name) <0)) 287 dir->sorted = dir->nr; 288} 289 290/* 291 * Clear and free all entries in dir, recursively. 292 */ 293static voidclear_ref_dir(struct ref_dir *dir) 294{ 295int i; 296for(i =0; i < dir->nr; i++) 297free_ref_entry(dir->entries[i]); 298free(dir->entries); 299 dir->sorted = dir->nr = dir->alloc =0; 300 dir->entries = NULL; 301} 302 303/* 304 * Create a struct ref_entry object for the specified dirname. 305 * dirname is the name of the directory with a trailing slash (e.g., 306 * "refs/heads/") or "" for the top-level directory. 307 */ 308static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 309const char*dirname,size_t len, 310int incomplete) 311{ 312struct ref_entry *direntry; 313 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 314memcpy(direntry->name, dirname, len); 315 direntry->name[len] ='\0'; 316 direntry->u.subdir.ref_cache = ref_cache; 317 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 318return direntry; 319} 320 321static intref_entry_cmp(const void*a,const void*b) 322{ 323struct ref_entry *one = *(struct ref_entry **)a; 324struct ref_entry *two = *(struct ref_entry **)b; 325returnstrcmp(one->name, two->name); 326} 327 328static voidsort_ref_dir(struct ref_dir *dir); 329 330struct string_slice { 331size_t len; 332const char*str; 333}; 334 335static intref_entry_cmp_sslice(const void*key_,const void*ent_) 336{ 337const struct string_slice *key = key_; 338const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 339int cmp =strncmp(key->str, ent->name, key->len); 340if(cmp) 341return cmp; 342return'\0'- (unsigned char)ent->name[key->len]; 343} 344 345/* 346 * Return the entry with the given refname from the ref_dir 347 * (non-recursively), sorting dir if necessary. Return NULL if no 348 * such entry is found. dir must already be complete. 349 */ 350static struct ref_entry *search_ref_dir(struct ref_dir *dir, 351const char*refname,size_t len) 352{ 353struct ref_entry **r; 354struct string_slice key; 355 356if(refname == NULL || !dir->nr) 357return NULL; 358 359sort_ref_dir(dir); 360 key.len = len; 361 key.str = refname; 362 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 363 ref_entry_cmp_sslice); 364 365if(r == NULL) 366return NULL; 367 368return*r; 369} 370 371/* 372 * Search for a directory entry directly within dir (without 373 * recursing). Sort dir if necessary. subdirname must be a directory 374 * name (i.e., end in '/'). If mkdir is set, then create the 375 * directory if it is missing; otherwise, return NULL if the desired 376 * directory cannot be found. dir must already be complete. 377 */ 378static struct ref_dir *search_for_subdir(struct ref_dir *dir, 379const char*subdirname,size_t len, 380int mkdir) 381{ 382struct ref_entry *entry =search_ref_dir(dir, subdirname, len); 383if(!entry) { 384if(!mkdir) 385return NULL; 386/* 387 * Since dir is complete, the absence of a subdir 388 * means that the subdir really doesn't exist; 389 * therefore, create an empty record for it but mark 390 * the record complete. 391 */ 392 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 393add_entry_to_dir(dir, entry); 394} 395returnget_ref_dir(entry); 396} 397 398/* 399 * If refname is a reference name, find the ref_dir within the dir 400 * tree that should hold refname. If refname is a directory name 401 * (i.e., ends in '/'), then return that ref_dir itself. dir must 402 * represent the top-level directory and must already be complete. 403 * Sort ref_dirs and recurse into subdirectories as necessary. If 404 * mkdir is set, then create any missing directories; otherwise, 405 * return NULL if the desired directory cannot be found. 406 */ 407static struct ref_dir *find_containing_dir(struct ref_dir *dir, 408const char*refname,int mkdir) 409{ 410const char*slash; 411for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 412size_t dirnamelen = slash - refname +1; 413struct ref_dir *subdir; 414 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 415if(!subdir) { 416 dir = NULL; 417break; 418} 419 dir = subdir; 420} 421 422return dir; 423} 424 425/* 426 * Find the value entry with the given name in dir, sorting ref_dirs 427 * and recursing into subdirectories as necessary. If the name is not 428 * found or it corresponds to a directory entry, return NULL. 429 */ 430static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 431{ 432struct ref_entry *entry; 433 dir =find_containing_dir(dir, refname,0); 434if(!dir) 435return NULL; 436 entry =search_ref_dir(dir, refname,strlen(refname)); 437return(entry && !(entry->flag & REF_DIR)) ? entry : NULL; 438} 439 440/* 441 * Add a ref_entry to the ref_dir (unsorted), recursing into 442 * subdirectories as necessary. dir must represent the top-level 443 * directory. Return 0 on success. 444 */ 445static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 446{ 447 dir =find_containing_dir(dir, ref->name,1); 448if(!dir) 449return-1; 450add_entry_to_dir(dir, ref); 451return0; 452} 453 454/* 455 * Emit a warning and return true iff ref1 and ref2 have the same name 456 * and the same sha1. Die if they have the same name but different 457 * sha1s. 458 */ 459static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 460{ 461if(strcmp(ref1->name, ref2->name)) 462return0; 463 464/* Duplicate name; make sure that they don't conflict: */ 465 466if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 467/* This is impossible by construction */ 468die("Reference directory conflict:%s", ref1->name); 469 470if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 471die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 472 473warning("Duplicated ref:%s", ref1->name); 474return1; 475} 476 477/* 478 * Sort the entries in dir non-recursively (if they are not already 479 * sorted) and remove any duplicate entries. 480 */ 481static voidsort_ref_dir(struct ref_dir *dir) 482{ 483int i, j; 484struct ref_entry *last = NULL; 485 486/* 487 * This check also prevents passing a zero-length array to qsort(), 488 * which is a problem on some platforms. 489 */ 490if(dir->sorted == dir->nr) 491return; 492 493qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 494 495/* Remove any duplicates: */ 496for(i =0, j =0; j < dir->nr; j++) { 497struct ref_entry *entry = dir->entries[j]; 498if(last &&is_dup_ref(last, entry)) 499free_ref_entry(entry); 500else 501 last = dir->entries[i++] = entry; 502} 503 dir->sorted = dir->nr = i; 504} 505 506#define DO_FOR_EACH_INCLUDE_BROKEN 01 507 508static struct ref_entry *current_ref; 509 510static intdo_one_ref(const char*base, each_ref_fn fn,int trim, 511int flags,void*cb_data,struct ref_entry *entry) 512{ 513int retval; 514if(prefixcmp(entry->name, base)) 515return0; 516 517if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) { 518if(entry->flag & REF_ISBROKEN) 519return0;/* ignore broken refs e.g. dangling symref */ 520if(!has_sha1_file(entry->u.value.sha1)) { 521error("%sdoes not point to a valid object!", entry->name); 522return0; 523} 524} 525 current_ref = entry; 526 retval =fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data); 527 current_ref = NULL; 528return retval; 529} 530 531/* 532 * Call fn for each reference in dir that has index in the range 533 * offset <= index < dir->nr. Recurse into subdirectories that are in 534 * that index range, sorting them before iterating. This function 535 * does not sort dir itself; it should be sorted beforehand. 536 */ 537static intdo_for_each_ref_in_dir(struct ref_dir *dir,int offset, 538const char*base, 539 each_ref_fn fn,int trim,int flags,void*cb_data) 540{ 541int i; 542assert(dir->sorted == dir->nr); 543for(i = offset; i < dir->nr; i++) { 544struct ref_entry *entry = dir->entries[i]; 545int retval; 546if(entry->flag & REF_DIR) { 547struct ref_dir *subdir =get_ref_dir(entry); 548sort_ref_dir(subdir); 549 retval =do_for_each_ref_in_dir(subdir,0, 550 base, fn, trim, flags, cb_data); 551}else{ 552 retval =do_one_ref(base, fn, trim, flags, cb_data, entry); 553} 554if(retval) 555return retval; 556} 557return0; 558} 559 560/* 561 * Call fn for each reference in the union of dir1 and dir2, in order 562 * by refname. Recurse into subdirectories. If a value entry appears 563 * in both dir1 and dir2, then only process the version that is in 564 * dir2. The input dirs must already be sorted, but subdirs will be 565 * sorted as needed. 566 */ 567static intdo_for_each_ref_in_dirs(struct ref_dir *dir1, 568struct ref_dir *dir2, 569const char*base, each_ref_fn fn,int trim, 570int flags,void*cb_data) 571{ 572int retval; 573int i1 =0, i2 =0; 574 575assert(dir1->sorted == dir1->nr); 576assert(dir2->sorted == dir2->nr); 577while(1) { 578struct ref_entry *e1, *e2; 579int cmp; 580if(i1 == dir1->nr) { 581returndo_for_each_ref_in_dir(dir2, i2, 582 base, fn, trim, flags, cb_data); 583} 584if(i2 == dir2->nr) { 585returndo_for_each_ref_in_dir(dir1, i1, 586 base, fn, trim, flags, cb_data); 587} 588 e1 = dir1->entries[i1]; 589 e2 = dir2->entries[i2]; 590 cmp =strcmp(e1->name, e2->name); 591if(cmp ==0) { 592if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 593/* Both are directories; descend them in parallel. */ 594struct ref_dir *subdir1 =get_ref_dir(e1); 595struct ref_dir *subdir2 =get_ref_dir(e2); 596sort_ref_dir(subdir1); 597sort_ref_dir(subdir2); 598 retval =do_for_each_ref_in_dirs( 599 subdir1, subdir2, 600 base, fn, trim, flags, cb_data); 601 i1++; 602 i2++; 603}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 604/* Both are references; ignore the one from dir1. */ 605 retval =do_one_ref(base, fn, trim, flags, cb_data, e2); 606 i1++; 607 i2++; 608}else{ 609die("conflict between reference and directory:%s", 610 e1->name); 611} 612}else{ 613struct ref_entry *e; 614if(cmp <0) { 615 e = e1; 616 i1++; 617}else{ 618 e = e2; 619 i2++; 620} 621if(e->flag & REF_DIR) { 622struct ref_dir *subdir =get_ref_dir(e); 623sort_ref_dir(subdir); 624 retval =do_for_each_ref_in_dir( 625 subdir,0, 626 base, fn, trim, flags, cb_data); 627}else{ 628 retval =do_one_ref(base, fn, trim, flags, cb_data, e); 629} 630} 631if(retval) 632return retval; 633} 634if(i1 < dir1->nr) 635returndo_for_each_ref_in_dir(dir1, i1, 636 base, fn, trim, flags, cb_data); 637if(i2 < dir2->nr) 638returndo_for_each_ref_in_dir(dir2, i2, 639 base, fn, trim, flags, cb_data); 640return0; 641} 642 643/* 644 * Return true iff refname1 and refname2 conflict with each other. 645 * Two reference names conflict if one of them exactly matches the 646 * leading components of the other; e.g., "foo/bar" conflicts with 647 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 648 * "foo/barbados". 649 */ 650static intnames_conflict(const char*refname1,const char*refname2) 651{ 652for(; *refname1 && *refname1 == *refname2; refname1++, refname2++) 653; 654return(*refname1 =='\0'&& *refname2 =='/') 655|| (*refname1 =='/'&& *refname2 =='\0'); 656} 657 658struct name_conflict_cb { 659const char*refname; 660const char*oldrefname; 661const char*conflicting_refname; 662}; 663 664static intname_conflict_fn(const char*existingrefname,const unsigned char*sha1, 665int flags,void*cb_data) 666{ 667struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data; 668if(data->oldrefname && !strcmp(data->oldrefname, existingrefname)) 669return0; 670if(names_conflict(data->refname, existingrefname)) { 671 data->conflicting_refname = existingrefname; 672return1; 673} 674return0; 675} 676 677/* 678 * Return true iff a reference named refname could be created without 679 * conflicting with the name of an existing reference in array. If 680 * oldrefname is non-NULL, ignore potential conflicts with oldrefname 681 * (e.g., because oldrefname is scheduled for deletion in the same 682 * operation). 683 */ 684static intis_refname_available(const char*refname,const char*oldrefname, 685struct ref_dir *dir) 686{ 687struct name_conflict_cb data; 688 data.refname = refname; 689 data.oldrefname = oldrefname; 690 data.conflicting_refname = NULL; 691 692sort_ref_dir(dir); 693if(do_for_each_ref_in_dir(dir,0,"", name_conflict_fn, 6940, DO_FOR_EACH_INCLUDE_BROKEN, 695&data)) { 696error("'%s' exists; cannot create '%s'", 697 data.conflicting_refname, refname); 698return0; 699} 700return1; 701} 702 703/* 704 * Future: need to be in "struct repository" 705 * when doing a full libification. 706 */ 707static struct ref_cache { 708struct ref_cache *next; 709struct ref_entry *loose; 710struct ref_entry *packed; 711/* The submodule name, or "" for the main repo. */ 712char name[FLEX_ARRAY]; 713} *ref_cache; 714 715static voidclear_packed_ref_cache(struct ref_cache *refs) 716{ 717if(refs->packed) { 718free_ref_entry(refs->packed); 719 refs->packed = NULL; 720} 721} 722 723static voidclear_loose_ref_cache(struct ref_cache *refs) 724{ 725if(refs->loose) { 726free_ref_entry(refs->loose); 727 refs->loose = NULL; 728} 729} 730 731static struct ref_cache *create_ref_cache(const char*submodule) 732{ 733int len; 734struct ref_cache *refs; 735if(!submodule) 736 submodule =""; 737 len =strlen(submodule) +1; 738 refs =xcalloc(1,sizeof(struct ref_cache) + len); 739memcpy(refs->name, submodule, len); 740return refs; 741} 742 743/* 744 * Return a pointer to a ref_cache for the specified submodule. For 745 * the main repository, use submodule==NULL. The returned structure 746 * will be allocated and initialized but not necessarily populated; it 747 * should not be freed. 748 */ 749static struct ref_cache *get_ref_cache(const char*submodule) 750{ 751struct ref_cache *refs = ref_cache; 752if(!submodule) 753 submodule =""; 754while(refs) { 755if(!strcmp(submodule, refs->name)) 756return refs; 757 refs = refs->next; 758} 759 760 refs =create_ref_cache(submodule); 761 refs->next = ref_cache; 762 ref_cache = refs; 763return refs; 764} 765 766voidinvalidate_ref_cache(const char*submodule) 767{ 768struct ref_cache *refs =get_ref_cache(submodule); 769clear_packed_ref_cache(refs); 770clear_loose_ref_cache(refs); 771} 772 773/* 774 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 775 * Return a pointer to the refname within the line (null-terminated), 776 * or NULL if there was a problem. 777 */ 778static const char*parse_ref_line(char*line,unsigned char*sha1) 779{ 780/* 781 * 42: the answer to everything. 782 * 783 * In this case, it happens to be the answer to 784 * 40 (length of sha1 hex representation) 785 * +1 (space in between hex and name) 786 * +1 (newline at the end of the line) 787 */ 788int len =strlen(line) -42; 789 790if(len <=0) 791return NULL; 792if(get_sha1_hex(line, sha1) <0) 793return NULL; 794if(!isspace(line[40])) 795return NULL; 796 line +=41; 797if(isspace(*line)) 798return NULL; 799if(line[len] !='\n') 800return NULL; 801 line[len] =0; 802 803return line; 804} 805 806/* 807 * Read f, which is a packed-refs file, into dir. 808 * 809 * A comment line of the form "# pack-refs with: " may contain zero or 810 * more traits. We interpret the traits as follows: 811 * 812 * No traits: 813 * 814 * Probably no references are peeled. But if the file contains a 815 * peeled value for a reference, we will use it. 816 * 817 * peeled: 818 * 819 * References under "refs/tags/", if they *can* be peeled, *are* 820 * peeled in this file. References outside of "refs/tags/" are 821 * probably not peeled even if they could have been, but if we find 822 * a peeled value for such a reference we will use it. 823 * 824 * fully-peeled: 825 * 826 * All references in the file that can be peeled are peeled. 827 * Inversely (and this is more important), any references in the 828 * file for which no peeled value is recorded is not peelable. This 829 * trait should typically be written alongside "peeled" for 830 * compatibility with older clients, but we do not require it 831 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 832 */ 833static voidread_packed_refs(FILE*f,struct ref_dir *dir) 834{ 835struct ref_entry *last = NULL; 836char refline[PATH_MAX]; 837enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 838 839while(fgets(refline,sizeof(refline), f)) { 840unsigned char sha1[20]; 841const char*refname; 842static const char header[] ="# pack-refs with:"; 843 844if(!strncmp(refline, header,sizeof(header)-1)) { 845const char*traits = refline +sizeof(header) -1; 846if(strstr(traits," fully-peeled ")) 847 peeled = PEELED_FULLY; 848else if(strstr(traits," peeled ")) 849 peeled = PEELED_TAGS; 850/* perhaps other traits later as well */ 851continue; 852} 853 854 refname =parse_ref_line(refline, sha1); 855if(refname) { 856 last =create_ref_entry(refname, sha1, REF_ISPACKED,1); 857if(peeled == PEELED_FULLY || 858(peeled == PEELED_TAGS && !prefixcmp(refname,"refs/tags/"))) 859 last->flag |= REF_KNOWS_PEELED; 860add_ref(dir, last); 861continue; 862} 863if(last && 864 refline[0] =='^'&& 865strlen(refline) ==42&& 866 refline[41] =='\n'&& 867!get_sha1_hex(refline +1, sha1)) { 868hashcpy(last->u.value.peeled, sha1); 869/* 870 * Regardless of what the file header said, 871 * we definitely know the value of *this* 872 * reference: 873 */ 874 last->flag |= REF_KNOWS_PEELED; 875} 876} 877} 878 879static struct ref_dir *get_packed_refs(struct ref_cache *refs) 880{ 881if(!refs->packed) { 882const char*packed_refs_file; 883FILE*f; 884 885 refs->packed =create_dir_entry(refs,"",0,0); 886if(*refs->name) 887 packed_refs_file =git_path_submodule(refs->name,"packed-refs"); 888else 889 packed_refs_file =git_path("packed-refs"); 890 f =fopen(packed_refs_file,"r"); 891if(f) { 892read_packed_refs(f,get_ref_dir(refs->packed)); 893fclose(f); 894} 895} 896returnget_ref_dir(refs->packed); 897} 898 899voidadd_packed_ref(const char*refname,const unsigned char*sha1) 900{ 901add_ref(get_packed_refs(get_ref_cache(NULL)), 902create_ref_entry(refname, sha1, REF_ISPACKED,1)); 903} 904 905/* 906 * Read the loose references from the namespace dirname into dir 907 * (without recursing). dirname must end with '/'. dir must be the 908 * directory entry corresponding to dirname. 909 */ 910static voidread_loose_refs(const char*dirname,struct ref_dir *dir) 911{ 912struct ref_cache *refs = dir->ref_cache; 913DIR*d; 914const char*path; 915struct dirent *de; 916int dirnamelen =strlen(dirname); 917struct strbuf refname; 918 919if(*refs->name) 920 path =git_path_submodule(refs->name,"%s", dirname); 921else 922 path =git_path("%s", dirname); 923 924 d =opendir(path); 925if(!d) 926return; 927 928strbuf_init(&refname, dirnamelen +257); 929strbuf_add(&refname, dirname, dirnamelen); 930 931while((de =readdir(d)) != NULL) { 932unsigned char sha1[20]; 933struct stat st; 934int flag; 935const char*refdir; 936 937if(de->d_name[0] =='.') 938continue; 939if(has_extension(de->d_name,".lock")) 940continue; 941strbuf_addstr(&refname, de->d_name); 942 refdir = *refs->name 943?git_path_submodule(refs->name,"%s", refname.buf) 944:git_path("%s", refname.buf); 945if(stat(refdir, &st) <0) { 946;/* silently ignore */ 947}else if(S_ISDIR(st.st_mode)) { 948strbuf_addch(&refname,'/'); 949add_entry_to_dir(dir, 950create_dir_entry(refs, refname.buf, 951 refname.len,1)); 952}else{ 953if(*refs->name) { 954hashclr(sha1); 955 flag =0; 956if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) { 957hashclr(sha1); 958 flag |= REF_ISBROKEN; 959} 960}else if(read_ref_full(refname.buf, sha1,1, &flag)) { 961hashclr(sha1); 962 flag |= REF_ISBROKEN; 963} 964add_entry_to_dir(dir, 965create_ref_entry(refname.buf, sha1, flag,1)); 966} 967strbuf_setlen(&refname, dirnamelen); 968} 969strbuf_release(&refname); 970closedir(d); 971} 972 973static struct ref_dir *get_loose_refs(struct ref_cache *refs) 974{ 975if(!refs->loose) { 976/* 977 * Mark the top-level directory complete because we 978 * are about to read the only subdirectory that can 979 * hold references: 980 */ 981 refs->loose =create_dir_entry(refs,"",0,0); 982/* 983 * Create an incomplete entry for "refs/": 984 */ 985add_entry_to_dir(get_ref_dir(refs->loose), 986create_dir_entry(refs,"refs/",5,1)); 987} 988returnget_ref_dir(refs->loose); 989} 990 991/* We allow "recursive" symbolic refs. Only within reason, though */ 992#define MAXDEPTH 5 993#define MAXREFLEN (1024) 994 995/* 996 * Called by resolve_gitlink_ref_recursive() after it failed to read 997 * from the loose refs in ref_cache refs. Find <refname> in the 998 * packed-refs file for the submodule. 999 */1000static intresolve_gitlink_packed_ref(struct ref_cache *refs,1001const char*refname,unsigned char*sha1)1002{1003struct ref_entry *ref;1004struct ref_dir *dir =get_packed_refs(refs);10051006 ref =find_ref(dir, refname);1007if(ref == NULL)1008return-1;10091010memcpy(sha1, ref->u.value.sha1,20);1011return0;1012}10131014static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1015const char*refname,unsigned char*sha1,1016int recursion)1017{1018int fd, len;1019char buffer[128], *p;1020char*path;10211022if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1023return-1;1024 path = *refs->name1025?git_path_submodule(refs->name,"%s", refname)1026:git_path("%s", refname);1027 fd =open(path, O_RDONLY);1028if(fd <0)1029returnresolve_gitlink_packed_ref(refs, refname, sha1);10301031 len =read(fd, buffer,sizeof(buffer)-1);1032close(fd);1033if(len <0)1034return-1;1035while(len &&isspace(buffer[len-1]))1036 len--;1037 buffer[len] =0;10381039/* Was it a detached head or an old-fashioned symlink? */1040if(!get_sha1_hex(buffer, sha1))1041return0;10421043/* Symref? */1044if(strncmp(buffer,"ref:",4))1045return-1;1046 p = buffer +4;1047while(isspace(*p))1048 p++;10491050returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1051}10521053intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1054{1055int len =strlen(path), retval;1056char*submodule;1057struct ref_cache *refs;10581059while(len && path[len-1] =='/')1060 len--;1061if(!len)1062return-1;1063 submodule =xstrndup(path, len);1064 refs =get_ref_cache(submodule);1065free(submodule);10661067 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1068return retval;1069}10701071/*1072 * Try to read ref from the packed references. On success, set sha11073 * and return 0; otherwise, return -1.1074 */1075static intget_packed_ref(const char*refname,unsigned char*sha1)1076{1077struct ref_dir *packed =get_packed_refs(get_ref_cache(NULL));1078struct ref_entry *entry =find_ref(packed, refname);1079if(entry) {1080hashcpy(sha1, entry->u.value.sha1);1081return0;1082}1083return-1;1084}10851086const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1087{1088int depth = MAXDEPTH;1089 ssize_t len;1090char buffer[256];1091static char refname_buffer[256];10921093if(flag)1094*flag =0;10951096if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))1097return NULL;10981099for(;;) {1100char path[PATH_MAX];1101struct stat st;1102char*buf;1103int fd;11041105if(--depth <0)1106return NULL;11071108git_snpath(path,sizeof(path),"%s", refname);11091110if(lstat(path, &st) <0) {1111if(errno != ENOENT)1112return NULL;1113/*1114 * The loose reference file does not exist;1115 * check for a packed reference.1116 */1117if(!get_packed_ref(refname, sha1)) {1118if(flag)1119*flag |= REF_ISPACKED;1120return refname;1121}1122/* The reference is not a packed reference, either. */1123if(reading) {1124return NULL;1125}else{1126hashclr(sha1);1127return refname;1128}1129}11301131/* Follow "normalized" - ie "refs/.." symlinks by hand */1132if(S_ISLNK(st.st_mode)) {1133 len =readlink(path, buffer,sizeof(buffer)-1);1134if(len <0)1135return NULL;1136 buffer[len] =0;1137if(!prefixcmp(buffer,"refs/") &&1138!check_refname_format(buffer,0)) {1139strcpy(refname_buffer, buffer);1140 refname = refname_buffer;1141if(flag)1142*flag |= REF_ISSYMREF;1143continue;1144}1145}11461147/* Is it a directory? */1148if(S_ISDIR(st.st_mode)) {1149 errno = EISDIR;1150return NULL;1151}11521153/*1154 * Anything else, just open it and try to use it as1155 * a ref1156 */1157 fd =open(path, O_RDONLY);1158if(fd <0)1159return NULL;1160 len =read_in_full(fd, buffer,sizeof(buffer)-1);1161close(fd);1162if(len <0)1163return NULL;1164while(len &&isspace(buffer[len-1]))1165 len--;1166 buffer[len] ='\0';11671168/*1169 * Is it a symbolic ref?1170 */1171if(prefixcmp(buffer,"ref:"))1172break;1173if(flag)1174*flag |= REF_ISSYMREF;1175 buf = buffer +4;1176while(isspace(*buf))1177 buf++;1178if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1179if(flag)1180*flag |= REF_ISBROKEN;1181return NULL;1182}1183 refname =strcpy(refname_buffer, buf);1184}1185/* Please note that FETCH_HEAD has a second line containing other data. */1186if(get_sha1_hex(buffer, sha1) || (buffer[40] !='\0'&& !isspace(buffer[40]))) {1187if(flag)1188*flag |= REF_ISBROKEN;1189return NULL;1190}1191return refname;1192}11931194char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1195{1196const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1197return ret ?xstrdup(ret) : NULL;1198}11991200/* The argument to filter_refs */1201struct ref_filter {1202const char*pattern;1203 each_ref_fn *fn;1204void*cb_data;1205};12061207intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1208{1209if(resolve_ref_unsafe(refname, sha1, reading, flags))1210return0;1211return-1;1212}12131214intread_ref(const char*refname,unsigned char*sha1)1215{1216returnread_ref_full(refname, sha1,1, NULL);1217}12181219intref_exists(const char*refname)1220{1221unsigned char sha1[20];1222return!!resolve_ref_unsafe(refname, sha1,1, NULL);1223}12241225static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1226void*data)1227{1228struct ref_filter *filter = (struct ref_filter *)data;1229if(fnmatch(filter->pattern, refname,0))1230return0;1231return filter->fn(refname, sha1, flags, filter->cb_data);1232}12331234intpeel_ref(const char*refname,unsigned char*sha1)1235{1236int flag;1237unsigned char base[20];1238struct object *o;12391240if(current_ref && (current_ref->name == refname1241|| !strcmp(current_ref->name, refname))) {1242if(current_ref->flag & REF_KNOWS_PEELED) {1243if(is_null_sha1(current_ref->u.value.peeled))1244return-1;1245hashcpy(sha1, current_ref->u.value.peeled);1246return0;1247}1248hashcpy(base, current_ref->u.value.sha1);1249goto fallback;1250}12511252if(read_ref_full(refname, base,1, &flag))1253return-1;12541255if((flag & REF_ISPACKED)) {1256struct ref_dir *dir =get_packed_refs(get_ref_cache(NULL));1257struct ref_entry *r =find_ref(dir, refname);12581259if(r != NULL && r->flag & REF_KNOWS_PEELED) {1260hashcpy(sha1, r->u.value.peeled);1261return0;1262}1263}12641265fallback:1266 o =lookup_unknown_object(base);1267if(o->type == OBJ_NONE) {1268int type =sha1_object_info(base, NULL);1269if(type <0)1270return-1;1271 o->type = type;1272}12731274if(o->type == OBJ_TAG) {1275 o =deref_tag_noverify(o);1276if(o) {1277hashcpy(sha1, o->sha1);1278return0;1279}1280}1281return-1;1282}12831284struct warn_if_dangling_data {1285FILE*fp;1286const char*refname;1287const char*msg_fmt;1288};12891290static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1291int flags,void*cb_data)1292{1293struct warn_if_dangling_data *d = cb_data;1294const char*resolves_to;1295unsigned char junk[20];12961297if(!(flags & REF_ISSYMREF))1298return0;12991300 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1301if(!resolves_to ||strcmp(resolves_to, d->refname))1302return0;13031304fprintf(d->fp, d->msg_fmt, refname);1305fputc('\n', d->fp);1306return0;1307}13081309voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1310{1311struct warn_if_dangling_data data;13121313 data.fp = fp;1314 data.refname = refname;1315 data.msg_fmt = msg_fmt;1316for_each_rawref(warn_if_dangling_symref, &data);1317}13181319static intdo_for_each_ref(const char*submodule,const char*base, each_ref_fn fn,1320int trim,int flags,void*cb_data)1321{1322struct ref_cache *refs =get_ref_cache(submodule);1323struct ref_dir *packed_dir =get_packed_refs(refs);1324struct ref_dir *loose_dir =get_loose_refs(refs);1325int retval =0;13261327if(base && *base) {1328 packed_dir =find_containing_dir(packed_dir, base,0);1329 loose_dir =find_containing_dir(loose_dir, base,0);1330}13311332if(packed_dir && loose_dir) {1333sort_ref_dir(packed_dir);1334sort_ref_dir(loose_dir);1335 retval =do_for_each_ref_in_dirs(1336 packed_dir, loose_dir,1337 base, fn, trim, flags, cb_data);1338}else if(packed_dir) {1339sort_ref_dir(packed_dir);1340 retval =do_for_each_ref_in_dir(1341 packed_dir,0,1342 base, fn, trim, flags, cb_data);1343}else if(loose_dir) {1344sort_ref_dir(loose_dir);1345 retval =do_for_each_ref_in_dir(1346 loose_dir,0,1347 base, fn, trim, flags, cb_data);1348}13491350return retval;1351}13521353static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1354{1355unsigned char sha1[20];1356int flag;13571358if(submodule) {1359if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1360returnfn("HEAD", sha1,0, cb_data);13611362return0;1363}13641365if(!read_ref_full("HEAD", sha1,1, &flag))1366returnfn("HEAD", sha1, flag, cb_data);13671368return0;1369}13701371inthead_ref(each_ref_fn fn,void*cb_data)1372{1373returndo_head_ref(NULL, fn, cb_data);1374}13751376inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1377{1378returndo_head_ref(submodule, fn, cb_data);1379}13801381intfor_each_ref(each_ref_fn fn,void*cb_data)1382{1383returndo_for_each_ref(NULL,"", fn,0,0, cb_data);1384}13851386intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1387{1388returndo_for_each_ref(submodule,"", fn,0,0, cb_data);1389}13901391intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1392{1393returndo_for_each_ref(NULL, prefix, fn,strlen(prefix),0, cb_data);1394}13951396intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1397 each_ref_fn fn,void*cb_data)1398{1399returndo_for_each_ref(submodule, prefix, fn,strlen(prefix),0, cb_data);1400}14011402intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1403{1404returnfor_each_ref_in("refs/tags/", fn, cb_data);1405}14061407intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1408{1409returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1410}14111412intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1413{1414returnfor_each_ref_in("refs/heads/", fn, cb_data);1415}14161417intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1418{1419returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1420}14211422intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1423{1424returnfor_each_ref_in("refs/remotes/", fn, cb_data);1425}14261427intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1428{1429returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1430}14311432intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1433{1434returndo_for_each_ref(NULL,"refs/replace/", fn,13,0, cb_data);1435}14361437inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1438{1439struct strbuf buf = STRBUF_INIT;1440int ret =0;1441unsigned char sha1[20];1442int flag;14431444strbuf_addf(&buf,"%sHEAD",get_git_namespace());1445if(!read_ref_full(buf.buf, sha1,1, &flag))1446 ret =fn(buf.buf, sha1, flag, cb_data);1447strbuf_release(&buf);14481449return ret;1450}14511452intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1453{1454struct strbuf buf = STRBUF_INIT;1455int ret;1456strbuf_addf(&buf,"%srefs/",get_git_namespace());1457 ret =do_for_each_ref(NULL, buf.buf, fn,0,0, cb_data);1458strbuf_release(&buf);1459return ret;1460}14611462intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1463const char*prefix,void*cb_data)1464{1465struct strbuf real_pattern = STRBUF_INIT;1466struct ref_filter filter;1467int ret;14681469if(!prefix &&prefixcmp(pattern,"refs/"))1470strbuf_addstr(&real_pattern,"refs/");1471else if(prefix)1472strbuf_addstr(&real_pattern, prefix);1473strbuf_addstr(&real_pattern, pattern);14741475if(!has_glob_specials(pattern)) {1476/* Append implied '/' '*' if not present. */1477if(real_pattern.buf[real_pattern.len -1] !='/')1478strbuf_addch(&real_pattern,'/');1479/* No need to check for '*', there is none. */1480strbuf_addch(&real_pattern,'*');1481}14821483 filter.pattern = real_pattern.buf;1484 filter.fn = fn;1485 filter.cb_data = cb_data;1486 ret =for_each_ref(filter_refs, &filter);14871488strbuf_release(&real_pattern);1489return ret;1490}14911492intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1493{1494returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1495}14961497intfor_each_rawref(each_ref_fn fn,void*cb_data)1498{1499returndo_for_each_ref(NULL,"", fn,0,1500 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1501}15021503const char*prettify_refname(const char*name)1504{1505return name + (1506!prefixcmp(name,"refs/heads/") ?11:1507!prefixcmp(name,"refs/tags/") ?10:1508!prefixcmp(name,"refs/remotes/") ?13:15090);1510}15111512const char*ref_rev_parse_rules[] = {1513"%.*s",1514"refs/%.*s",1515"refs/tags/%.*s",1516"refs/heads/%.*s",1517"refs/remotes/%.*s",1518"refs/remotes/%.*s/HEAD",1519 NULL1520};15211522intrefname_match(const char*abbrev_name,const char*full_name,const char**rules)1523{1524const char**p;1525const int abbrev_name_len =strlen(abbrev_name);15261527for(p = rules; *p; p++) {1528if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {1529return1;1530}1531}15321533return0;1534}15351536static struct ref_lock *verify_lock(struct ref_lock *lock,1537const unsigned char*old_sha1,int mustexist)1538{1539if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {1540error("Can't verify ref%s", lock->ref_name);1541unlock_ref(lock);1542return NULL;1543}1544if(hashcmp(lock->old_sha1, old_sha1)) {1545error("Ref%sis at%sbut expected%s", lock->ref_name,1546sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));1547unlock_ref(lock);1548return NULL;1549}1550return lock;1551}15521553static intremove_empty_directories(const char*file)1554{1555/* we want to create a file but there is a directory there;1556 * if that is an empty directory (or a directory that contains1557 * only empty directories), remove them.1558 */1559struct strbuf path;1560int result;15611562strbuf_init(&path,20);1563strbuf_addstr(&path, file);15641565 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);15661567strbuf_release(&path);15681569return result;1570}15711572/*1573 * *string and *len will only be substituted, and *string returned (for1574 * later free()ing) if the string passed in is a magic short-hand form1575 * to name a branch.1576 */1577static char*substitute_branch_name(const char**string,int*len)1578{1579struct strbuf buf = STRBUF_INIT;1580int ret =interpret_branch_name(*string, &buf);15811582if(ret == *len) {1583size_t size;1584*string =strbuf_detach(&buf, &size);1585*len = size;1586return(char*)*string;1587}15881589return NULL;1590}15911592intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)1593{1594char*last_branch =substitute_branch_name(&str, &len);1595const char**p, *r;1596int refs_found =0;15971598*ref = NULL;1599for(p = ref_rev_parse_rules; *p; p++) {1600char fullref[PATH_MAX];1601unsigned char sha1_from_ref[20];1602unsigned char*this_result;1603int flag;16041605 this_result = refs_found ? sha1_from_ref : sha1;1606mksnpath(fullref,sizeof(fullref), *p, len, str);1607 r =resolve_ref_unsafe(fullref, this_result,1, &flag);1608if(r) {1609if(!refs_found++)1610*ref =xstrdup(r);1611if(!warn_ambiguous_refs)1612break;1613}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {1614warning("ignoring dangling symref%s.", fullref);1615}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {1616warning("ignoring broken ref%s.", fullref);1617}1618}1619free(last_branch);1620return refs_found;1621}16221623intdwim_log(const char*str,int len,unsigned char*sha1,char**log)1624{1625char*last_branch =substitute_branch_name(&str, &len);1626const char**p;1627int logs_found =0;16281629*log = NULL;1630for(p = ref_rev_parse_rules; *p; p++) {1631struct stat st;1632unsigned char hash[20];1633char path[PATH_MAX];1634const char*ref, *it;16351636mksnpath(path,sizeof(path), *p, len, str);1637 ref =resolve_ref_unsafe(path, hash,1, NULL);1638if(!ref)1639continue;1640if(!stat(git_path("logs/%s", path), &st) &&1641S_ISREG(st.st_mode))1642 it = path;1643else if(strcmp(ref, path) &&1644!stat(git_path("logs/%s", ref), &st) &&1645S_ISREG(st.st_mode))1646 it = ref;1647else1648continue;1649if(!logs_found++) {1650*log =xstrdup(it);1651hashcpy(sha1, hash);1652}1653if(!warn_ambiguous_refs)1654break;1655}1656free(last_branch);1657return logs_found;1658}16591660static struct ref_lock *lock_ref_sha1_basic(const char*refname,1661const unsigned char*old_sha1,1662int flags,int*type_p)1663{1664char*ref_file;1665const char*orig_refname = refname;1666struct ref_lock *lock;1667int last_errno =0;1668int type, lflags;1669int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1670int missing =0;16711672 lock =xcalloc(1,sizeof(struct ref_lock));1673 lock->lock_fd = -1;16741675 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);1676if(!refname && errno == EISDIR) {1677/* we are trying to lock foo but we used to1678 * have foo/bar which now does not exist;1679 * it is normal for the empty directory 'foo'1680 * to remain.1681 */1682 ref_file =git_path("%s", orig_refname);1683if(remove_empty_directories(ref_file)) {1684 last_errno = errno;1685error("there are still refs under '%s'", orig_refname);1686goto error_return;1687}1688 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);1689}1690if(type_p)1691*type_p = type;1692if(!refname) {1693 last_errno = errno;1694error("unable to resolve reference%s:%s",1695 orig_refname,strerror(errno));1696goto error_return;1697}1698 missing =is_null_sha1(lock->old_sha1);1699/* When the ref did not exist and we are creating it,1700 * make sure there is no existing ref that is packed1701 * whose name begins with our refname, nor a ref whose1702 * name is a proper prefix of our refname.1703 */1704if(missing &&1705!is_refname_available(refname, NULL,get_packed_refs(get_ref_cache(NULL)))) {1706 last_errno = ENOTDIR;1707goto error_return;1708}17091710 lock->lk =xcalloc(1,sizeof(struct lock_file));17111712 lflags = LOCK_DIE_ON_ERROR;1713if(flags & REF_NODEREF) {1714 refname = orig_refname;1715 lflags |= LOCK_NODEREF;1716}1717 lock->ref_name =xstrdup(refname);1718 lock->orig_ref_name =xstrdup(orig_refname);1719 ref_file =git_path("%s", refname);1720if(missing)1721 lock->force_write =1;1722if((flags & REF_NODEREF) && (type & REF_ISSYMREF))1723 lock->force_write =1;17241725if(safe_create_leading_directories(ref_file)) {1726 last_errno = errno;1727error("unable to create directory for%s", ref_file);1728goto error_return;1729}17301731 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);1732return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;17331734 error_return:1735unlock_ref(lock);1736 errno = last_errno;1737return NULL;1738}17391740struct ref_lock *lock_ref_sha1(const char*refname,const unsigned char*old_sha1)1741{1742char refpath[PATH_MAX];1743if(check_refname_format(refname,0))1744return NULL;1745strcpy(refpath,mkpath("refs/%s", refname));1746returnlock_ref_sha1_basic(refpath, old_sha1,0, NULL);1747}17481749struct ref_lock *lock_any_ref_for_update(const char*refname,1750const unsigned char*old_sha1,int flags)1751{1752if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))1753return NULL;1754returnlock_ref_sha1_basic(refname, old_sha1, flags, NULL);1755}17561757struct repack_without_ref_sb {1758const char*refname;1759int fd;1760};17611762static intrepack_without_ref_fn(const char*refname,const unsigned char*sha1,1763int flags,void*cb_data)1764{1765struct repack_without_ref_sb *data = cb_data;1766char line[PATH_MAX +100];1767int len;17681769if(!strcmp(data->refname, refname))1770return0;1771 len =snprintf(line,sizeof(line),"%s %s\n",1772sha1_to_hex(sha1), refname);1773/* this should not happen but just being defensive */1774if(len >sizeof(line))1775die("too long a refname '%s'", refname);1776write_or_die(data->fd, line, len);1777return0;1778}17791780static struct lock_file packlock;17811782static intrepack_without_ref(const char*refname)1783{1784struct repack_without_ref_sb data;1785struct ref_cache *refs =get_ref_cache(NULL);1786struct ref_dir *packed =get_packed_refs(refs);1787if(find_ref(packed, refname) == NULL)1788return0;1789 data.refname = refname;1790 data.fd =hold_lock_file_for_update(&packlock,git_path("packed-refs"),0);1791if(data.fd <0) {1792unable_to_lock_error(git_path("packed-refs"), errno);1793returnerror("cannot delete '%s' from packed refs", refname);1794}1795clear_packed_ref_cache(refs);1796 packed =get_packed_refs(refs);1797do_for_each_ref_in_dir(packed,0,"", repack_without_ref_fn,0,0, &data);1798returncommit_lock_file(&packlock);1799}18001801intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)1802{1803struct ref_lock *lock;1804int err, i =0, ret =0, flag =0;18051806 lock =lock_ref_sha1_basic(refname, sha1, delopt, &flag);1807if(!lock)1808return1;1809if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {1810/* loose */1811 i =strlen(lock->lk->filename) -5;/* .lock */1812 lock->lk->filename[i] =0;1813 err =unlink_or_warn(lock->lk->filename);1814if(err && errno != ENOENT)1815 ret =1;18161817 lock->lk->filename[i] ='.';1818}1819/* removing the loose one could have resurrected an earlier1820 * packed one. Also, if it was not loose we need to repack1821 * without it.1822 */1823 ret |=repack_without_ref(lock->ref_name);18241825unlink_or_warn(git_path("logs/%s", lock->ref_name));1826invalidate_ref_cache(NULL);1827unlock_ref(lock);1828return ret;1829}18301831/*1832 * People using contrib's git-new-workdir have .git/logs/refs ->1833 * /some/other/path/.git/logs/refs, and that may live on another device.1834 *1835 * IOW, to avoid cross device rename errors, the temporary renamed log must1836 * live into logs/refs.1837 */1838#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"18391840intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)1841{1842unsigned char sha1[20], orig_sha1[20];1843int flag =0, logmoved =0;1844struct ref_lock *lock;1845struct stat loginfo;1846int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);1847const char*symref = NULL;1848struct ref_cache *refs =get_ref_cache(NULL);18491850if(log &&S_ISLNK(loginfo.st_mode))1851returnerror("reflog for%sis a symlink", oldrefname);18521853 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);1854if(flag & REF_ISSYMREF)1855returnerror("refname%sis a symbolic ref, renaming it is not supported",1856 oldrefname);1857if(!symref)1858returnerror("refname%snot found", oldrefname);18591860if(!is_refname_available(newrefname, oldrefname,get_packed_refs(refs)))1861return1;18621863if(!is_refname_available(newrefname, oldrefname,get_loose_refs(refs)))1864return1;18651866if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))1867returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",1868 oldrefname,strerror(errno));18691870if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {1871error("unable to delete old%s", oldrefname);1872goto rollback;1873}18741875if(!read_ref_full(newrefname, sha1,1, &flag) &&1876delete_ref(newrefname, sha1, REF_NODEREF)) {1877if(errno==EISDIR) {1878if(remove_empty_directories(git_path("%s", newrefname))) {1879error("Directory not empty:%s", newrefname);1880goto rollback;1881}1882}else{1883error("unable to delete existing%s", newrefname);1884goto rollback;1885}1886}18871888if(log &&safe_create_leading_directories(git_path("logs/%s", newrefname))) {1889error("unable to create directory for%s", newrefname);1890goto rollback;1891}18921893 retry:1894if(log &&rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {1895if(errno==EISDIR || errno==ENOTDIR) {1896/*1897 * rename(a, b) when b is an existing1898 * directory ought to result in ISDIR, but1899 * Solaris 5.8 gives ENOTDIR. Sheesh.1900 */1901if(remove_empty_directories(git_path("logs/%s", newrefname))) {1902error("Directory not empty: logs/%s", newrefname);1903goto rollback;1904}1905goto retry;1906}else{1907error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",1908 newrefname,strerror(errno));1909goto rollback;1910}1911}1912 logmoved = log;19131914 lock =lock_ref_sha1_basic(newrefname, NULL,0, NULL);1915if(!lock) {1916error("unable to lock%sfor update", newrefname);1917goto rollback;1918}1919 lock->force_write =1;1920hashcpy(lock->old_sha1, orig_sha1);1921if(write_ref_sha1(lock, orig_sha1, logmsg)) {1922error("unable to write current sha1 into%s", newrefname);1923goto rollback;1924}19251926return0;19271928 rollback:1929 lock =lock_ref_sha1_basic(oldrefname, NULL,0, NULL);1930if(!lock) {1931error("unable to lock%sfor rollback", oldrefname);1932goto rollbacklog;1933}19341935 lock->force_write =1;1936 flag = log_all_ref_updates;1937 log_all_ref_updates =0;1938if(write_ref_sha1(lock, orig_sha1, NULL))1939error("unable to write current sha1 into%s", oldrefname);1940 log_all_ref_updates = flag;19411942 rollbacklog:1943if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))1944error("unable to restore logfile%sfrom%s:%s",1945 oldrefname, newrefname,strerror(errno));1946if(!logmoved && log &&1947rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))1948error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",1949 oldrefname,strerror(errno));19501951return1;1952}19531954intclose_ref(struct ref_lock *lock)1955{1956if(close_lock_file(lock->lk))1957return-1;1958 lock->lock_fd = -1;1959return0;1960}19611962intcommit_ref(struct ref_lock *lock)1963{1964if(commit_lock_file(lock->lk))1965return-1;1966 lock->lock_fd = -1;1967return0;1968}19691970voidunlock_ref(struct ref_lock *lock)1971{1972/* Do not free lock->lk -- atexit() still looks at them */1973if(lock->lk)1974rollback_lock_file(lock->lk);1975free(lock->ref_name);1976free(lock->orig_ref_name);1977free(lock);1978}19791980/*1981 * copy the reflog message msg to buf, which has been allocated sufficiently1982 * large, while cleaning up the whitespaces. Especially, convert LF to space,1983 * because reflog file is one line per entry.1984 */1985static intcopy_msg(char*buf,const char*msg)1986{1987char*cp = buf;1988char c;1989int wasspace =1;19901991*cp++ ='\t';1992while((c = *msg++)) {1993if(wasspace &&isspace(c))1994continue;1995 wasspace =isspace(c);1996if(wasspace)1997 c =' ';1998*cp++ = c;1999}2000while(buf < cp &&isspace(cp[-1]))2001 cp--;2002*cp++ ='\n';2003return cp - buf;2004}20052006intlog_ref_setup(const char*refname,char*logfile,int bufsize)2007{2008int logfd, oflags = O_APPEND | O_WRONLY;20092010git_snpath(logfile, bufsize,"logs/%s", refname);2011if(log_all_ref_updates &&2012(!prefixcmp(refname,"refs/heads/") ||2013!prefixcmp(refname,"refs/remotes/") ||2014!prefixcmp(refname,"refs/notes/") ||2015!strcmp(refname,"HEAD"))) {2016if(safe_create_leading_directories(logfile) <0)2017returnerror("unable to create directory for%s",2018 logfile);2019 oflags |= O_CREAT;2020}20212022 logfd =open(logfile, oflags,0666);2023if(logfd <0) {2024if(!(oflags & O_CREAT) && errno == ENOENT)2025return0;20262027if((oflags & O_CREAT) && errno == EISDIR) {2028if(remove_empty_directories(logfile)) {2029returnerror("There are still logs under '%s'",2030 logfile);2031}2032 logfd =open(logfile, oflags,0666);2033}20342035if(logfd <0)2036returnerror("Unable to append to%s:%s",2037 logfile,strerror(errno));2038}20392040adjust_shared_perm(logfile);2041close(logfd);2042return0;2043}20442045static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2046const unsigned char*new_sha1,const char*msg)2047{2048int logfd, result, written, oflags = O_APPEND | O_WRONLY;2049unsigned maxlen, len;2050int msglen;2051char log_file[PATH_MAX];2052char*logrec;2053const char*committer;20542055if(log_all_ref_updates <0)2056 log_all_ref_updates = !is_bare_repository();20572058 result =log_ref_setup(refname, log_file,sizeof(log_file));2059if(result)2060return result;20612062 logfd =open(log_file, oflags);2063if(logfd <0)2064return0;2065 msglen = msg ?strlen(msg) :0;2066 committer =git_committer_info(0);2067 maxlen =strlen(committer) + msglen +100;2068 logrec =xmalloc(maxlen);2069 len =sprintf(logrec,"%s %s %s\n",2070sha1_to_hex(old_sha1),2071sha1_to_hex(new_sha1),2072 committer);2073if(msglen)2074 len +=copy_msg(logrec + len -1, msg) -1;2075 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2076free(logrec);2077if(close(logfd) !=0|| written != len)2078returnerror("Unable to append to%s", log_file);2079return0;2080}20812082static intis_branch(const char*refname)2083{2084return!strcmp(refname,"HEAD") || !prefixcmp(refname,"refs/heads/");2085}20862087intwrite_ref_sha1(struct ref_lock *lock,2088const unsigned char*sha1,const char*logmsg)2089{2090static char term ='\n';2091struct object *o;20922093if(!lock)2094return-1;2095if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2096unlock_ref(lock);2097return0;2098}2099 o =parse_object(sha1);2100if(!o) {2101error("Trying to write ref%swith nonexistent object%s",2102 lock->ref_name,sha1_to_hex(sha1));2103unlock_ref(lock);2104return-1;2105}2106if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2107error("Trying to write non-commit object%sto branch%s",2108sha1_to_hex(sha1), lock->ref_name);2109unlock_ref(lock);2110return-1;2111}2112if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||2113write_in_full(lock->lock_fd, &term,1) !=12114||close_ref(lock) <0) {2115error("Couldn't write%s", lock->lk->filename);2116unlock_ref(lock);2117return-1;2118}2119clear_loose_ref_cache(get_ref_cache(NULL));2120if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||2121(strcmp(lock->ref_name, lock->orig_ref_name) &&2122log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {2123unlock_ref(lock);2124return-1;2125}2126if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2127/*2128 * Special hack: If a branch is updated directly and HEAD2129 * points to it (may happen on the remote side of a push2130 * for example) then logically the HEAD reflog should be2131 * updated too.2132 * A generic solution implies reverse symref information,2133 * but finding all symrefs pointing to the given branch2134 * would be rather costly for this rare event (the direct2135 * update of a branch) to be worth it. So let's cheat and2136 * check with HEAD only which should cover 99% of all usage2137 * scenarios (even 100% of the default ones).2138 */2139unsigned char head_sha1[20];2140int head_flag;2141const char*head_ref;2142 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);2143if(head_ref && (head_flag & REF_ISSYMREF) &&2144!strcmp(head_ref, lock->ref_name))2145log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);2146}2147if(commit_ref(lock)) {2148error("Couldn't set%s", lock->ref_name);2149unlock_ref(lock);2150return-1;2151}2152unlock_ref(lock);2153return0;2154}21552156intcreate_symref(const char*ref_target,const char*refs_heads_master,2157const char*logmsg)2158{2159const char*lockpath;2160char ref[1000];2161int fd, len, written;2162char*git_HEAD =git_pathdup("%s", ref_target);2163unsigned char old_sha1[20], new_sha1[20];21642165if(logmsg &&read_ref(ref_target, old_sha1))2166hashclr(old_sha1);21672168if(safe_create_leading_directories(git_HEAD) <0)2169returnerror("unable to create directory for%s", git_HEAD);21702171#ifndef NO_SYMLINK_HEAD2172if(prefer_symlink_refs) {2173unlink(git_HEAD);2174if(!symlink(refs_heads_master, git_HEAD))2175goto done;2176fprintf(stderr,"no symlink - falling back to symbolic ref\n");2177}2178#endif21792180 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);2181if(sizeof(ref) <= len) {2182error("refname too long:%s", refs_heads_master);2183goto error_free_return;2184}2185 lockpath =mkpath("%s.lock", git_HEAD);2186 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);2187if(fd <0) {2188error("Unable to open%sfor writing", lockpath);2189goto error_free_return;2190}2191 written =write_in_full(fd, ref, len);2192if(close(fd) !=0|| written != len) {2193error("Unable to write to%s", lockpath);2194goto error_unlink_return;2195}2196if(rename(lockpath, git_HEAD) <0) {2197error("Unable to create%s", git_HEAD);2198goto error_unlink_return;2199}2200if(adjust_shared_perm(git_HEAD)) {2201error("Unable to fix permissions on%s", lockpath);2202 error_unlink_return:2203unlink_or_warn(lockpath);2204 error_free_return:2205free(git_HEAD);2206return-1;2207}22082209#ifndef NO_SYMLINK_HEAD2210 done:2211#endif2212if(logmsg && !read_ref(refs_heads_master, new_sha1))2213log_ref_write(ref_target, old_sha1, new_sha1, logmsg);22142215free(git_HEAD);2216return0;2217}22182219static char*ref_msg(const char*line,const char*endp)2220{2221const char*ep;2222 line +=82;2223 ep =memchr(line,'\n', endp - line);2224if(!ep)2225 ep = endp;2226returnxmemdupz(line, ep - line);2227}22282229intread_ref_at(const char*refname,unsigned long at_time,int cnt,2230unsigned char*sha1,char**msg,2231unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)2232{2233const char*logfile, *logdata, *logend, *rec, *lastgt, *lastrec;2234char*tz_c;2235int logfd, tz, reccnt =0;2236struct stat st;2237unsigned long date;2238unsigned char logged_sha1[20];2239void*log_mapped;2240size_t mapsz;22412242 logfile =git_path("logs/%s", refname);2243 logfd =open(logfile, O_RDONLY,0);2244if(logfd <0)2245die_errno("Unable to read log '%s'", logfile);2246fstat(logfd, &st);2247if(!st.st_size)2248die("Log%sis empty.", logfile);2249 mapsz =xsize_t(st.st_size);2250 log_mapped =xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd,0);2251 logdata = log_mapped;2252close(logfd);22532254 lastrec = NULL;2255 rec = logend = logdata + st.st_size;2256while(logdata < rec) {2257 reccnt++;2258if(logdata < rec && *(rec-1) =='\n')2259 rec--;2260 lastgt = NULL;2261while(logdata < rec && *(rec-1) !='\n') {2262 rec--;2263if(*rec =='>')2264 lastgt = rec;2265}2266if(!lastgt)2267die("Log%sis corrupt.", logfile);2268 date =strtoul(lastgt +1, &tz_c,10);2269if(date <= at_time || cnt ==0) {2270 tz =strtoul(tz_c, NULL,10);2271if(msg)2272*msg =ref_msg(rec, logend);2273if(cutoff_time)2274*cutoff_time = date;2275if(cutoff_tz)2276*cutoff_tz = tz;2277if(cutoff_cnt)2278*cutoff_cnt = reccnt -1;2279if(lastrec) {2280if(get_sha1_hex(lastrec, logged_sha1))2281die("Log%sis corrupt.", logfile);2282if(get_sha1_hex(rec +41, sha1))2283die("Log%sis corrupt.", logfile);2284if(hashcmp(logged_sha1, sha1)) {2285warning("Log%shas gap after%s.",2286 logfile,show_date(date, tz, DATE_RFC2822));2287}2288}2289else if(date == at_time) {2290if(get_sha1_hex(rec +41, sha1))2291die("Log%sis corrupt.", logfile);2292}2293else{2294if(get_sha1_hex(rec +41, logged_sha1))2295die("Log%sis corrupt.", logfile);2296if(hashcmp(logged_sha1, sha1)) {2297warning("Log%sunexpectedly ended on%s.",2298 logfile,show_date(date, tz, DATE_RFC2822));2299}2300}2301munmap(log_mapped, mapsz);2302return0;2303}2304 lastrec = rec;2305if(cnt >0)2306 cnt--;2307}23082309 rec = logdata;2310while(rec < logend && *rec !='>'&& *rec !='\n')2311 rec++;2312if(rec == logend || *rec =='\n')2313die("Log%sis corrupt.", logfile);2314 date =strtoul(rec +1, &tz_c,10);2315 tz =strtoul(tz_c, NULL,10);2316if(get_sha1_hex(logdata, sha1))2317die("Log%sis corrupt.", logfile);2318if(is_null_sha1(sha1)) {2319if(get_sha1_hex(logdata +41, sha1))2320die("Log%sis corrupt.", logfile);2321}2322if(msg)2323*msg =ref_msg(logdata, logend);2324munmap(log_mapped, mapsz);23252326if(cutoff_time)2327*cutoff_time = date;2328if(cutoff_tz)2329*cutoff_tz = tz;2330if(cutoff_cnt)2331*cutoff_cnt = reccnt;2332return1;2333}23342335static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2336{2337unsigned char osha1[20], nsha1[20];2338char*email_end, *message;2339unsigned long timestamp;2340int tz;23412342/* old SP new SP name <email> SP time TAB msg LF */2343if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2344get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2345get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2346!(email_end =strchr(sb->buf +82,'>')) ||2347 email_end[1] !=' '||2348!(timestamp =strtoul(email_end +2, &message,10)) ||2349!message || message[0] !=' '||2350(message[1] !='+'&& message[1] !='-') ||2351!isdigit(message[2]) || !isdigit(message[3]) ||2352!isdigit(message[4]) || !isdigit(message[5]))2353return0;/* corrupt? */2354 email_end[1] ='\0';2355 tz =strtol(message +1, NULL,10);2356if(message[6] !='\t')2357 message +=6;2358else2359 message +=7;2360returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2361}23622363static char*find_beginning_of_line(char*bob,char*scan)2364{2365while(bob < scan && *(--scan) !='\n')2366;/* keep scanning backwards */2367/*2368 * Return either beginning of the buffer, or LF at the end of2369 * the previous line.2370 */2371return scan;2372}23732374intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2375{2376struct strbuf sb = STRBUF_INIT;2377FILE*logfp;2378long pos;2379int ret =0, at_tail =1;23802381 logfp =fopen(git_path("logs/%s", refname),"r");2382if(!logfp)2383return-1;23842385/* Jump to the end */2386if(fseek(logfp,0, SEEK_END) <0)2387returnerror("cannot seek back reflog for%s:%s",2388 refname,strerror(errno));2389 pos =ftell(logfp);2390while(!ret &&0< pos) {2391int cnt;2392size_t nread;2393char buf[BUFSIZ];2394char*endp, *scanp;23952396/* Fill next block from the end */2397 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2398if(fseek(logfp, pos - cnt, SEEK_SET))2399returnerror("cannot seek back reflog for%s:%s",2400 refname,strerror(errno));2401 nread =fread(buf, cnt,1, logfp);2402if(nread !=1)2403returnerror("cannot read%dbytes from reflog for%s:%s",2404 cnt, refname,strerror(errno));2405 pos -= cnt;24062407 scanp = endp = buf + cnt;2408if(at_tail && scanp[-1] =='\n')2409/* Looking at the final LF at the end of the file */2410 scanp--;2411 at_tail =0;24122413while(buf < scanp) {2414/*2415 * terminating LF of the previous line, or the beginning2416 * of the buffer.2417 */2418char*bp;24192420 bp =find_beginning_of_line(buf, scanp);24212422if(*bp !='\n') {2423strbuf_splice(&sb,0,0, buf, endp - buf);2424if(pos)2425break;/* need to fill another block */2426 scanp = buf -1;/* leave loop */2427}else{2428/*2429 * (bp + 1) thru endp is the beginning of the2430 * current line we have in sb2431 */2432strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2433 scanp = bp;2434 endp = bp +1;2435}2436 ret =show_one_reflog_ent(&sb, fn, cb_data);2437strbuf_reset(&sb);2438if(ret)2439break;2440}24412442}2443if(!ret && sb.len)2444 ret =show_one_reflog_ent(&sb, fn, cb_data);24452446fclose(logfp);2447strbuf_release(&sb);2448return ret;2449}24502451intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2452{2453FILE*logfp;2454struct strbuf sb = STRBUF_INIT;2455int ret =0;24562457 logfp =fopen(git_path("logs/%s", refname),"r");2458if(!logfp)2459return-1;24602461while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2462 ret =show_one_reflog_ent(&sb, fn, cb_data);2463fclose(logfp);2464strbuf_release(&sb);2465return ret;2466}2467/*2468 * Call fn for each reflog in the namespace indicated by name. name2469 * must be empty or end with '/'. Name will be used as a scratch2470 * space, but its contents will be restored before return.2471 */2472static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)2473{2474DIR*d =opendir(git_path("logs/%s", name->buf));2475int retval =0;2476struct dirent *de;2477int oldlen = name->len;24782479if(!d)2480return name->len ? errno :0;24812482while((de =readdir(d)) != NULL) {2483struct stat st;24842485if(de->d_name[0] =='.')2486continue;2487if(has_extension(de->d_name,".lock"))2488continue;2489strbuf_addstr(name, de->d_name);2490if(stat(git_path("logs/%s", name->buf), &st) <0) {2491;/* silently ignore */2492}else{2493if(S_ISDIR(st.st_mode)) {2494strbuf_addch(name,'/');2495 retval =do_for_each_reflog(name, fn, cb_data);2496}else{2497unsigned char sha1[20];2498if(read_ref_full(name->buf, sha1,0, NULL))2499 retval =error("bad ref for%s", name->buf);2500else2501 retval =fn(name->buf, sha1,0, cb_data);2502}2503if(retval)2504break;2505}2506strbuf_setlen(name, oldlen);2507}2508closedir(d);2509return retval;2510}25112512intfor_each_reflog(each_ref_fn fn,void*cb_data)2513{2514int retval;2515struct strbuf name;2516strbuf_init(&name, PATH_MAX);2517 retval =do_for_each_reflog(&name, fn, cb_data);2518strbuf_release(&name);2519return retval;2520}25212522intupdate_ref(const char*action,const char*refname,2523const unsigned char*sha1,const unsigned char*oldval,2524int flags,enum action_on_err onerr)2525{2526static struct ref_lock *lock;2527 lock =lock_any_ref_for_update(refname, oldval, flags);2528if(!lock) {2529const char*str ="Cannot lock the ref '%s'.";2530switch(onerr) {2531case MSG_ON_ERR:error(str, refname);break;2532case DIE_ON_ERR:die(str, refname);break;2533case QUIET_ON_ERR:break;2534}2535return1;2536}2537if(write_ref_sha1(lock, sha1, action) <0) {2538const char*str ="Cannot update the ref '%s'.";2539switch(onerr) {2540case MSG_ON_ERR:error(str, refname);break;2541case DIE_ON_ERR:die(str, refname);break;2542case QUIET_ON_ERR:break;2543}2544return1;2545}2546return0;2547}25482549struct ref *find_ref_by_name(const struct ref *list,const char*name)2550{2551for( ; list; list = list->next)2552if(!strcmp(list->name, name))2553return(struct ref *)list;2554return NULL;2555}25562557/*2558 * generate a format suitable for scanf from a ref_rev_parse_rules2559 * rule, that is replace the "%.*s" spec with a "%s" spec2560 */2561static voidgen_scanf_fmt(char*scanf_fmt,const char*rule)2562{2563char*spec;25642565 spec =strstr(rule,"%.*s");2566if(!spec ||strstr(spec +4,"%.*s"))2567die("invalid rule in ref_rev_parse_rules:%s", rule);25682569/* copy all until spec */2570strncpy(scanf_fmt, rule, spec - rule);2571 scanf_fmt[spec - rule] ='\0';2572/* copy new spec */2573strcat(scanf_fmt,"%s");2574/* copy remaining rule */2575strcat(scanf_fmt, spec +4);25762577return;2578}25792580char*shorten_unambiguous_ref(const char*refname,int strict)2581{2582int i;2583static char**scanf_fmts;2584static int nr_rules;2585char*short_name;25862587/* pre generate scanf formats from ref_rev_parse_rules[] */2588if(!nr_rules) {2589size_t total_len =0;25902591/* the rule list is NULL terminated, count them first */2592for(; ref_rev_parse_rules[nr_rules]; nr_rules++)2593/* no +1 because strlen("%s") < strlen("%.*s") */2594 total_len +=strlen(ref_rev_parse_rules[nr_rules]);25952596 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);25972598 total_len =0;2599for(i =0; i < nr_rules; i++) {2600 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules]2601+ total_len;2602gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);2603 total_len +=strlen(ref_rev_parse_rules[i]);2604}2605}26062607/* bail out if there are no rules */2608if(!nr_rules)2609returnxstrdup(refname);26102611/* buffer for scanf result, at most refname must fit */2612 short_name =xstrdup(refname);26132614/* skip first rule, it will always match */2615for(i = nr_rules -1; i >0; --i) {2616int j;2617int rules_to_fail = i;2618int short_name_len;26192620if(1!=sscanf(refname, scanf_fmts[i], short_name))2621continue;26222623 short_name_len =strlen(short_name);26242625/*2626 * in strict mode, all (except the matched one) rules2627 * must fail to resolve to a valid non-ambiguous ref2628 */2629if(strict)2630 rules_to_fail = nr_rules;26312632/*2633 * check if the short name resolves to a valid ref,2634 * but use only rules prior to the matched one2635 */2636for(j =0; j < rules_to_fail; j++) {2637const char*rule = ref_rev_parse_rules[j];2638char refname[PATH_MAX];26392640/* skip matched rule */2641if(i == j)2642continue;26432644/*2645 * the short name is ambiguous, if it resolves2646 * (with this previous rule) to a valid ref2647 * read_ref() returns 0 on success2648 */2649mksnpath(refname,sizeof(refname),2650 rule, short_name_len, short_name);2651if(ref_exists(refname))2652break;2653}26542655/*2656 * short name is non-ambiguous if all previous rules2657 * haven't resolved to a valid ref2658 */2659if(j == rules_to_fail)2660return short_name;2661}26622663free(short_name);2664returnxstrdup(refname);2665}26662667static struct string_list *hide_refs;26682669intparse_hide_refs_config(const char*var,const char*value,const char*section)2670{2671if(!strcmp("transfer.hiderefs", var) ||2672/* NEEDSWORK: use parse_config_key() once both are merged */2673(!prefixcmp(var, section) && var[strlen(section)] =='.'&&2674!strcmp(var +strlen(section),".hiderefs"))) {2675char*ref;2676int len;26772678if(!value)2679returnconfig_error_nonbool(var);2680 ref =xstrdup(value);2681 len =strlen(ref);2682while(len && ref[len -1] =='/')2683 ref[--len] ='\0';2684if(!hide_refs) {2685 hide_refs =xcalloc(1,sizeof(*hide_refs));2686 hide_refs->strdup_strings =1;2687}2688string_list_append(hide_refs, ref);2689}2690return0;2691}26922693intref_is_hidden(const char*refname)2694{2695struct string_list_item *item;26962697if(!hide_refs)2698return0;2699for_each_string_list_item(item, hide_refs) {2700int len;2701if(prefixcmp(refname, item->string))2702continue;2703 len =strlen(item->string);2704if(!refname[len] || refname[len] =='/')2705return1;2706}2707return0;2708}