1#include "cache.h" 2#include "lockfile.h" 3#include "refs.h" 4#include "object.h" 5#include "tag.h" 6#include "dir.h" 7#include "string-list.h" 8 9struct ref_lock { 10 char *ref_name; 11 char *orig_ref_name; 12 struct lock_file *lk; 13 struct object_id old_oid; 14}; 15 16/* 17 * How to handle various characters in refnames: 18 * 0: An acceptable character for refs 19 * 1: End-of-component 20 * 2: ., look for a preceding . to reject .. in refs 21 * 3: {, look for a preceding @ to reject @{ in refs 22 * 4: A bad character: ASCII control characters, and 23 * ":", "?", "[", "\", "^", "~", SP, or TAB 24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 25 */ 26static unsigned char refname_disposition[256] = { 27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1, 30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0, 33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag in ref_update::flags when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Used as a flag in ref_update::flags when the reference should be 51 * updated to new_sha1. 52 */ 53#define REF_HAVE_NEW 0x08 54 55/* 56 * Used as a flag in ref_update::flags when old_sha1 should be 57 * checked. 58 */ 59#define REF_HAVE_OLD 0x10 60 61/* 62 * Used as a flag in ref_update::flags when the lockfile needs to be 63 * committed. 64 */ 65#define REF_NEEDS_COMMIT 0x20 66 67/* 68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a 69 * value to ref_update::flags 70 */ 71 72/* 73 * Try to read one refname component from the front of refname. 74 * Return the length of the component found, or -1 if the component is 75 * not legal. It is legal if it is something reasonable to have under 76 * ".git/refs/"; We do not like it if: 77 * 78 * - any path component of it begins with ".", or 79 * - it has double dots "..", or 80 * - it has ASCII control characters, or 81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 83 * - it ends with a "/", or 84 * - it ends with ".lock", or 85 * - it contains a "@{" portion 86 */ 87static int check_refname_component(const char *refname, int *flags) 88{ 89 const char *cp; 90 char last = '\0'; 91 92 for (cp = refname; ; cp++) { 93 int ch = *cp & 255; 94 unsigned char disp = refname_disposition[ch]; 95 switch (disp) { 96 case 1: 97 goto out; 98 case 2: 99 if (last == '.') 100 return -1; /* Refname contains "..". */ 101 break; 102 case 3: 103 if (last == '@') 104 return -1; /* Refname contains "@{". */ 105 break; 106 case 4: 107 return -1; 108 case 5: 109 if (!(*flags & REFNAME_REFSPEC_PATTERN)) 110 return -1; /* refspec can't be a pattern */ 111 112 /* 113 * Unset the pattern flag so that we only accept 114 * a single asterisk for one side of refspec. 115 */ 116 *flags &= ~ REFNAME_REFSPEC_PATTERN; 117 break; 118 } 119 last = ch; 120 } 121out: 122 if (cp == refname) 123 return 0; /* Component has zero length. */ 124 if (refname[0] == '.') 125 return -1; /* Component starts with '.'. */ 126 if (cp - refname >= LOCK_SUFFIX_LEN && 127 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 128 return -1; /* Refname ends with ".lock". */ 129 return cp - refname; 130} 131 132int check_refname_format(const char *refname, int flags) 133{ 134 int component_len, component_count = 0; 135 136 if (!strcmp(refname, "@")) 137 /* Refname is a single character '@'. */ 138 return -1; 139 140 while (1) { 141 /* We are at the start of a path component. */ 142 component_len = check_refname_component(refname, &flags); 143 if (component_len <= 0) 144 return -1; 145 146 component_count++; 147 if (refname[component_len] == '\0') 148 break; 149 /* Skip to next component. */ 150 refname += component_len + 1; 151 } 152 153 if (refname[component_len - 1] == '.') 154 return -1; /* Refname ends with '.'. */ 155 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2) 156 return -1; /* Refname has only one component. */ 157 return 0; 158} 159 160struct ref_entry; 161 162/* 163 * Information used (along with the information in ref_entry) to 164 * describe a single cached reference. This data structure only 165 * occurs embedded in a union in struct ref_entry, and only when 166 * (ref_entry->flag & REF_DIR) is zero. 167 */ 168struct ref_value { 169 /* 170 * The name of the object to which this reference resolves 171 * (which may be a tag object). If REF_ISBROKEN, this is 172 * null. If REF_ISSYMREF, then this is the name of the object 173 * referred to by the last reference in the symlink chain. 174 */ 175 struct object_id oid; 176 177 /* 178 * If REF_KNOWS_PEELED, then this field holds the peeled value 179 * of this reference, or null if the reference is known not to 180 * be peelable. See the documentation for peel_ref() for an 181 * exact definition of "peelable". 182 */ 183 struct object_id peeled; 184}; 185 186struct ref_cache; 187 188/* 189 * Information used (along with the information in ref_entry) to 190 * describe a level in the hierarchy of references. This data 191 * structure only occurs embedded in a union in struct ref_entry, and 192 * only when (ref_entry.flag & REF_DIR) is set. In that case, 193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 194 * in the directory have already been read: 195 * 196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 197 * or packed references, already read. 198 * 199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 200 * references that hasn't been read yet (nor has any of its 201 * subdirectories). 202 * 203 * Entries within a directory are stored within a growable array of 204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 205 * sorted are sorted by their component name in strcmp() order and the 206 * remaining entries are unsorted. 207 * 208 * Loose references are read lazily, one directory at a time. When a 209 * directory of loose references is read, then all of the references 210 * in that directory are stored, and REF_INCOMPLETE stubs are created 211 * for any subdirectories, but the subdirectories themselves are not 212 * read. The reading is triggered by get_ref_dir(). 213 */ 214struct ref_dir { 215 int nr, alloc; 216 217 /* 218 * Entries with index 0 <= i < sorted are sorted by name. New 219 * entries are appended to the list unsorted, and are sorted 220 * only when required; thus we avoid the need to sort the list 221 * after the addition of every reference. 222 */ 223 int sorted; 224 225 /* A pointer to the ref_cache that contains this ref_dir. */ 226 struct ref_cache *ref_cache; 227 228 struct ref_entry **entries; 229}; 230 231/* 232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 234 * public values; see refs.h. 235 */ 236 237/* 238 * The field ref_entry->u.value.peeled of this value entry contains 239 * the correct peeled value for the reference, which might be 240 * null_sha1 if the reference is not a tag or if it is broken. 241 */ 242#define REF_KNOWS_PEELED 0x10 243 244/* ref_entry represents a directory of references */ 245#define REF_DIR 0x20 246 247/* 248 * Entry has not yet been read from disk (used only for REF_DIR 249 * entries representing loose references) 250 */ 251#define REF_INCOMPLETE 0x40 252 253/* 254 * A ref_entry represents either a reference or a "subdirectory" of 255 * references. 256 * 257 * Each directory in the reference namespace is represented by a 258 * ref_entry with (flags & REF_DIR) set and containing a subdir member 259 * that holds the entries in that directory that have been read so 260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 262 * used for loose reference directories. 263 * 264 * References are represented by a ref_entry with (flags & REF_DIR) 265 * unset and a value member that describes the reference's value. The 266 * flag member is at the ref_entry level, but it is also needed to 267 * interpret the contents of the value field (in other words, a 268 * ref_value object is not very much use without the enclosing 269 * ref_entry). 270 * 271 * Reference names cannot end with slash and directories' names are 272 * always stored with a trailing slash (except for the top-level 273 * directory, which is always denoted by ""). This has two nice 274 * consequences: (1) when the entries in each subdir are sorted 275 * lexicographically by name (as they usually are), the references in 276 * a whole tree can be generated in lexicographic order by traversing 277 * the tree in left-to-right, depth-first order; (2) the names of 278 * references and subdirectories cannot conflict, and therefore the 279 * presence of an empty subdirectory does not block the creation of a 280 * similarly-named reference. (The fact that reference names with the 281 * same leading components can conflict *with each other* is a 282 * separate issue that is regulated by verify_refname_available().) 283 * 284 * Please note that the name field contains the fully-qualified 285 * reference (or subdirectory) name. Space could be saved by only 286 * storing the relative names. But that would require the full names 287 * to be generated on the fly when iterating in do_for_each_ref(), and 288 * would break callback functions, who have always been able to assume 289 * that the name strings that they are passed will not be freed during 290 * the iteration. 291 */ 292struct ref_entry { 293 unsigned char flag; /* ISSYMREF? ISPACKED? */ 294 union { 295 struct ref_value value; /* if not (flags&REF_DIR) */ 296 struct ref_dir subdir; /* if (flags&REF_DIR) */ 297 } u; 298 /* 299 * The full name of the reference (e.g., "refs/heads/master") 300 * or the full name of the directory with a trailing slash 301 * (e.g., "refs/heads/"): 302 */ 303 char name[FLEX_ARRAY]; 304}; 305 306static void read_loose_refs(const char *dirname, struct ref_dir *dir); 307static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len); 308static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 309 const char *dirname, size_t len, 310 int incomplete); 311static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry); 312 313static struct ref_dir *get_ref_dir(struct ref_entry *entry) 314{ 315 struct ref_dir *dir; 316 assert(entry->flag & REF_DIR); 317 dir = &entry->u.subdir; 318 if (entry->flag & REF_INCOMPLETE) { 319 read_loose_refs(entry->name, dir); 320 321 /* 322 * Manually add refs/bisect, which, being 323 * per-worktree, might not appear in the directory 324 * listing for refs/ in the main repo. 325 */ 326 if (!strcmp(entry->name, "refs/")) { 327 int pos = search_ref_dir(dir, "refs/bisect/", 12); 328 if (pos < 0) { 329 struct ref_entry *child_entry; 330 child_entry = create_dir_entry(dir->ref_cache, 331 "refs/bisect/", 332 12, 1); 333 add_entry_to_dir(dir, child_entry); 334 read_loose_refs("refs/bisect", 335 &child_entry->u.subdir); 336 } 337 } 338 entry->flag &= ~REF_INCOMPLETE; 339 } 340 return dir; 341} 342 343/* 344 * Check if a refname is safe. 345 * For refs that start with "refs/" we consider it safe as long they do 346 * not try to resolve to outside of refs/. 347 * 348 * For all other refs we only consider them safe iff they only contain 349 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 350 * "config"). 351 */ 352static int refname_is_safe(const char *refname) 353{ 354 if (starts_with(refname, "refs/")) { 355 char *buf; 356 int result; 357 358 buf = xmalloc(strlen(refname) + 1); 359 /* 360 * Does the refname try to escape refs/? 361 * For example: refs/foo/../bar is safe but refs/foo/../../bar 362 * is not. 363 */ 364 result = !normalize_path_copy(buf, refname + strlen("refs/")); 365 free(buf); 366 return result; 367 } 368 while (*refname) { 369 if (!isupper(*refname) && *refname != '_') 370 return 0; 371 refname++; 372 } 373 return 1; 374} 375 376static struct ref_entry *create_ref_entry(const char *refname, 377 const unsigned char *sha1, int flag, 378 int check_name) 379{ 380 int len; 381 struct ref_entry *ref; 382 383 if (check_name && 384 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 385 die("Reference has invalid format: '%s'", refname); 386 len = strlen(refname) + 1; 387 ref = xmalloc(sizeof(struct ref_entry) + len); 388 hashcpy(ref->u.value.oid.hash, sha1); 389 oidclr(&ref->u.value.peeled); 390 memcpy(ref->name, refname, len); 391 ref->flag = flag; 392 return ref; 393} 394 395static void clear_ref_dir(struct ref_dir *dir); 396 397static void free_ref_entry(struct ref_entry *entry) 398{ 399 if (entry->flag & REF_DIR) { 400 /* 401 * Do not use get_ref_dir() here, as that might 402 * trigger the reading of loose refs. 403 */ 404 clear_ref_dir(&entry->u.subdir); 405 } 406 free(entry); 407} 408 409/* 410 * Add a ref_entry to the end of dir (unsorted). Entry is always 411 * stored directly in dir; no recursion into subdirectories is 412 * done. 413 */ 414static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry) 415{ 416 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc); 417 dir->entries[dir->nr++] = entry; 418 /* optimize for the case that entries are added in order */ 419 if (dir->nr == 1 || 420 (dir->nr == dir->sorted + 1 && 421 strcmp(dir->entries[dir->nr - 2]->name, 422 dir->entries[dir->nr - 1]->name) < 0)) 423 dir->sorted = dir->nr; 424} 425 426/* 427 * Clear and free all entries in dir, recursively. 428 */ 429static void clear_ref_dir(struct ref_dir *dir) 430{ 431 int i; 432 for (i = 0; i < dir->nr; i++) 433 free_ref_entry(dir->entries[i]); 434 free(dir->entries); 435 dir->sorted = dir->nr = dir->alloc = 0; 436 dir->entries = NULL; 437} 438 439/* 440 * Create a struct ref_entry object for the specified dirname. 441 * dirname is the name of the directory with a trailing slash (e.g., 442 * "refs/heads/") or "" for the top-level directory. 443 */ 444static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 445 const char *dirname, size_t len, 446 int incomplete) 447{ 448 struct ref_entry *direntry; 449 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1); 450 memcpy(direntry->name, dirname, len); 451 direntry->name[len] = '\0'; 452 direntry->u.subdir.ref_cache = ref_cache; 453 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0); 454 return direntry; 455} 456 457static int ref_entry_cmp(const void *a, const void *b) 458{ 459 struct ref_entry *one = *(struct ref_entry **)a; 460 struct ref_entry *two = *(struct ref_entry **)b; 461 return strcmp(one->name, two->name); 462} 463 464static void sort_ref_dir(struct ref_dir *dir); 465 466struct string_slice { 467 size_t len; 468 const char *str; 469}; 470 471static int ref_entry_cmp_sslice(const void *key_, const void *ent_) 472{ 473 const struct string_slice *key = key_; 474 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_; 475 int cmp = strncmp(key->str, ent->name, key->len); 476 if (cmp) 477 return cmp; 478 return '\0' - (unsigned char)ent->name[key->len]; 479} 480 481/* 482 * Return the index of the entry with the given refname from the 483 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 484 * no such entry is found. dir must already be complete. 485 */ 486static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len) 487{ 488 struct ref_entry **r; 489 struct string_slice key; 490 491 if (refname == NULL || !dir->nr) 492 return -1; 493 494 sort_ref_dir(dir); 495 key.len = len; 496 key.str = refname; 497 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries), 498 ref_entry_cmp_sslice); 499 500 if (r == NULL) 501 return -1; 502 503 return r - dir->entries; 504} 505 506/* 507 * Search for a directory entry directly within dir (without 508 * recursing). Sort dir if necessary. subdirname must be a directory 509 * name (i.e., end in '/'). If mkdir is set, then create the 510 * directory if it is missing; otherwise, return NULL if the desired 511 * directory cannot be found. dir must already be complete. 512 */ 513static struct ref_dir *search_for_subdir(struct ref_dir *dir, 514 const char *subdirname, size_t len, 515 int mkdir) 516{ 517 int entry_index = search_ref_dir(dir, subdirname, len); 518 struct ref_entry *entry; 519 if (entry_index == -1) { 520 if (!mkdir) 521 return NULL; 522 /* 523 * Since dir is complete, the absence of a subdir 524 * means that the subdir really doesn't exist; 525 * therefore, create an empty record for it but mark 526 * the record complete. 527 */ 528 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0); 529 add_entry_to_dir(dir, entry); 530 } else { 531 entry = dir->entries[entry_index]; 532 } 533 return get_ref_dir(entry); 534} 535 536/* 537 * If refname is a reference name, find the ref_dir within the dir 538 * tree that should hold refname. If refname is a directory name 539 * (i.e., ends in '/'), then return that ref_dir itself. dir must 540 * represent the top-level directory and must already be complete. 541 * Sort ref_dirs and recurse into subdirectories as necessary. If 542 * mkdir is set, then create any missing directories; otherwise, 543 * return NULL if the desired directory cannot be found. 544 */ 545static struct ref_dir *find_containing_dir(struct ref_dir *dir, 546 const char *refname, int mkdir) 547{ 548 const char *slash; 549 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 550 size_t dirnamelen = slash - refname + 1; 551 struct ref_dir *subdir; 552 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir); 553 if (!subdir) { 554 dir = NULL; 555 break; 556 } 557 dir = subdir; 558 } 559 560 return dir; 561} 562 563/* 564 * Find the value entry with the given name in dir, sorting ref_dirs 565 * and recursing into subdirectories as necessary. If the name is not 566 * found or it corresponds to a directory entry, return NULL. 567 */ 568static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname) 569{ 570 int entry_index; 571 struct ref_entry *entry; 572 dir = find_containing_dir(dir, refname, 0); 573 if (!dir) 574 return NULL; 575 entry_index = search_ref_dir(dir, refname, strlen(refname)); 576 if (entry_index == -1) 577 return NULL; 578 entry = dir->entries[entry_index]; 579 return (entry->flag & REF_DIR) ? NULL : entry; 580} 581 582/* 583 * Remove the entry with the given name from dir, recursing into 584 * subdirectories as necessary. If refname is the name of a directory 585 * (i.e., ends with '/'), then remove the directory and its contents. 586 * If the removal was successful, return the number of entries 587 * remaining in the directory entry that contained the deleted entry. 588 * If the name was not found, return -1. Please note that this 589 * function only deletes the entry from the cache; it does not delete 590 * it from the filesystem or ensure that other cache entries (which 591 * might be symbolic references to the removed entry) are updated. 592 * Nor does it remove any containing dir entries that might be made 593 * empty by the removal. dir must represent the top-level directory 594 * and must already be complete. 595 */ 596static int remove_entry(struct ref_dir *dir, const char *refname) 597{ 598 int refname_len = strlen(refname); 599 int entry_index; 600 struct ref_entry *entry; 601 int is_dir = refname[refname_len - 1] == '/'; 602 if (is_dir) { 603 /* 604 * refname represents a reference directory. Remove 605 * the trailing slash; otherwise we will get the 606 * directory *representing* refname rather than the 607 * one *containing* it. 608 */ 609 char *dirname = xmemdupz(refname, refname_len - 1); 610 dir = find_containing_dir(dir, dirname, 0); 611 free(dirname); 612 } else { 613 dir = find_containing_dir(dir, refname, 0); 614 } 615 if (!dir) 616 return -1; 617 entry_index = search_ref_dir(dir, refname, refname_len); 618 if (entry_index == -1) 619 return -1; 620 entry = dir->entries[entry_index]; 621 622 memmove(&dir->entries[entry_index], 623 &dir->entries[entry_index + 1], 624 (dir->nr - entry_index - 1) * sizeof(*dir->entries) 625 ); 626 dir->nr--; 627 if (dir->sorted > entry_index) 628 dir->sorted--; 629 free_ref_entry(entry); 630 return dir->nr; 631} 632 633/* 634 * Add a ref_entry to the ref_dir (unsorted), recursing into 635 * subdirectories as necessary. dir must represent the top-level 636 * directory. Return 0 on success. 637 */ 638static int add_ref(struct ref_dir *dir, struct ref_entry *ref) 639{ 640 dir = find_containing_dir(dir, ref->name, 1); 641 if (!dir) 642 return -1; 643 add_entry_to_dir(dir, ref); 644 return 0; 645} 646 647/* 648 * Emit a warning and return true iff ref1 and ref2 have the same name 649 * and the same sha1. Die if they have the same name but different 650 * sha1s. 651 */ 652static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2) 653{ 654 if (strcmp(ref1->name, ref2->name)) 655 return 0; 656 657 /* Duplicate name; make sure that they don't conflict: */ 658 659 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 660 /* This is impossible by construction */ 661 die("Reference directory conflict: %s", ref1->name); 662 663 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 664 die("Duplicated ref, and SHA1s don't match: %s", ref1->name); 665 666 warning("Duplicated ref: %s", ref1->name); 667 return 1; 668} 669 670/* 671 * Sort the entries in dir non-recursively (if they are not already 672 * sorted) and remove any duplicate entries. 673 */ 674static void sort_ref_dir(struct ref_dir *dir) 675{ 676 int i, j; 677 struct ref_entry *last = NULL; 678 679 /* 680 * This check also prevents passing a zero-length array to qsort(), 681 * which is a problem on some platforms. 682 */ 683 if (dir->sorted == dir->nr) 684 return; 685 686 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp); 687 688 /* Remove any duplicates: */ 689 for (i = 0, j = 0; j < dir->nr; j++) { 690 struct ref_entry *entry = dir->entries[j]; 691 if (last && is_dup_ref(last, entry)) 692 free_ref_entry(entry); 693 else 694 last = dir->entries[i++] = entry; 695 } 696 dir->sorted = dir->nr = i; 697} 698 699/* Include broken references in a do_for_each_ref*() iteration: */ 700#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 701 702/* 703 * Return true iff the reference described by entry can be resolved to 704 * an object in the database. Emit a warning if the referred-to 705 * object does not exist. 706 */ 707static int ref_resolves_to_object(struct ref_entry *entry) 708{ 709 if (entry->flag & REF_ISBROKEN) 710 return 0; 711 if (!has_sha1_file(entry->u.value.oid.hash)) { 712 error("%s does not point to a valid object!", entry->name); 713 return 0; 714 } 715 return 1; 716} 717 718/* 719 * current_ref is a performance hack: when iterating over references 720 * using the for_each_ref*() functions, current_ref is set to the 721 * current reference's entry before calling the callback function. If 722 * the callback function calls peel_ref(), then peel_ref() first 723 * checks whether the reference to be peeled is the current reference 724 * (it usually is) and if so, returns that reference's peeled version 725 * if it is available. This avoids a refname lookup in a common case. 726 */ 727static struct ref_entry *current_ref; 728 729typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data); 730 731struct ref_entry_cb { 732 const char *base; 733 int trim; 734 int flags; 735 each_ref_fn *fn; 736 void *cb_data; 737}; 738 739/* 740 * Handle one reference in a do_for_each_ref*()-style iteration, 741 * calling an each_ref_fn for each entry. 742 */ 743static int do_one_ref(struct ref_entry *entry, void *cb_data) 744{ 745 struct ref_entry_cb *data = cb_data; 746 struct ref_entry *old_current_ref; 747 int retval; 748 749 if (!starts_with(entry->name, data->base)) 750 return 0; 751 752 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 753 !ref_resolves_to_object(entry)) 754 return 0; 755 756 /* Store the old value, in case this is a recursive call: */ 757 old_current_ref = current_ref; 758 current_ref = entry; 759 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 760 entry->flag, data->cb_data); 761 current_ref = old_current_ref; 762 return retval; 763} 764 765/* 766 * Call fn for each reference in dir that has index in the range 767 * offset <= index < dir->nr. Recurse into subdirectories that are in 768 * that index range, sorting them before iterating. This function 769 * does not sort dir itself; it should be sorted beforehand. fn is 770 * called for all references, including broken ones. 771 */ 772static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset, 773 each_ref_entry_fn fn, void *cb_data) 774{ 775 int i; 776 assert(dir->sorted == dir->nr); 777 for (i = offset; i < dir->nr; i++) { 778 struct ref_entry *entry = dir->entries[i]; 779 int retval; 780 if (entry->flag & REF_DIR) { 781 struct ref_dir *subdir = get_ref_dir(entry); 782 sort_ref_dir(subdir); 783 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data); 784 } else { 785 retval = fn(entry, cb_data); 786 } 787 if (retval) 788 return retval; 789 } 790 return 0; 791} 792 793/* 794 * Call fn for each reference in the union of dir1 and dir2, in order 795 * by refname. Recurse into subdirectories. If a value entry appears 796 * in both dir1 and dir2, then only process the version that is in 797 * dir2. The input dirs must already be sorted, but subdirs will be 798 * sorted as needed. fn is called for all references, including 799 * broken ones. 800 */ 801static int do_for_each_entry_in_dirs(struct ref_dir *dir1, 802 struct ref_dir *dir2, 803 each_ref_entry_fn fn, void *cb_data) 804{ 805 int retval; 806 int i1 = 0, i2 = 0; 807 808 assert(dir1->sorted == dir1->nr); 809 assert(dir2->sorted == dir2->nr); 810 while (1) { 811 struct ref_entry *e1, *e2; 812 int cmp; 813 if (i1 == dir1->nr) { 814 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data); 815 } 816 if (i2 == dir2->nr) { 817 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data); 818 } 819 e1 = dir1->entries[i1]; 820 e2 = dir2->entries[i2]; 821 cmp = strcmp(e1->name, e2->name); 822 if (cmp == 0) { 823 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 824 /* Both are directories; descend them in parallel. */ 825 struct ref_dir *subdir1 = get_ref_dir(e1); 826 struct ref_dir *subdir2 = get_ref_dir(e2); 827 sort_ref_dir(subdir1); 828 sort_ref_dir(subdir2); 829 retval = do_for_each_entry_in_dirs( 830 subdir1, subdir2, fn, cb_data); 831 i1++; 832 i2++; 833 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 834 /* Both are references; ignore the one from dir1. */ 835 retval = fn(e2, cb_data); 836 i1++; 837 i2++; 838 } else { 839 die("conflict between reference and directory: %s", 840 e1->name); 841 } 842 } else { 843 struct ref_entry *e; 844 if (cmp < 0) { 845 e = e1; 846 i1++; 847 } else { 848 e = e2; 849 i2++; 850 } 851 if (e->flag & REF_DIR) { 852 struct ref_dir *subdir = get_ref_dir(e); 853 sort_ref_dir(subdir); 854 retval = do_for_each_entry_in_dir( 855 subdir, 0, fn, cb_data); 856 } else { 857 retval = fn(e, cb_data); 858 } 859 } 860 if (retval) 861 return retval; 862 } 863} 864 865/* 866 * Load all of the refs from the dir into our in-memory cache. The hard work 867 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 868 * through all of the sub-directories. We do not even need to care about 869 * sorting, as traversal order does not matter to us. 870 */ 871static void prime_ref_dir(struct ref_dir *dir) 872{ 873 int i; 874 for (i = 0; i < dir->nr; i++) { 875 struct ref_entry *entry = dir->entries[i]; 876 if (entry->flag & REF_DIR) 877 prime_ref_dir(get_ref_dir(entry)); 878 } 879} 880 881struct nonmatching_ref_data { 882 const struct string_list *skip; 883 const char *conflicting_refname; 884}; 885 886static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata) 887{ 888 struct nonmatching_ref_data *data = vdata; 889 890 if (data->skip && string_list_has_string(data->skip, entry->name)) 891 return 0; 892 893 data->conflicting_refname = entry->name; 894 return 1; 895} 896 897/* 898 * Return 0 if a reference named refname could be created without 899 * conflicting with the name of an existing reference in dir. 900 * See verify_refname_available for more information. 901 */ 902static int verify_refname_available_dir(const char *refname, 903 const struct string_list *extras, 904 const struct string_list *skip, 905 struct ref_dir *dir, 906 struct strbuf *err) 907{ 908 const char *slash; 909 int pos; 910 struct strbuf dirname = STRBUF_INIT; 911 int ret = -1; 912 913 /* 914 * For the sake of comments in this function, suppose that 915 * refname is "refs/foo/bar". 916 */ 917 918 assert(err); 919 920 strbuf_grow(&dirname, strlen(refname) + 1); 921 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 922 /* Expand dirname to the new prefix, not including the trailing slash: */ 923 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 924 925 /* 926 * We are still at a leading dir of the refname (e.g., 927 * "refs/foo"; if there is a reference with that name, 928 * it is a conflict, *unless* it is in skip. 929 */ 930 if (dir) { 931 pos = search_ref_dir(dir, dirname.buf, dirname.len); 932 if (pos >= 0 && 933 (!skip || !string_list_has_string(skip, dirname.buf))) { 934 /* 935 * We found a reference whose name is 936 * a proper prefix of refname; e.g., 937 * "refs/foo", and is not in skip. 938 */ 939 strbuf_addf(err, "'%s' exists; cannot create '%s'", 940 dirname.buf, refname); 941 goto cleanup; 942 } 943 } 944 945 if (extras && string_list_has_string(extras, dirname.buf) && 946 (!skip || !string_list_has_string(skip, dirname.buf))) { 947 strbuf_addf(err, "cannot process '%s' and '%s' at the same time", 948 refname, dirname.buf); 949 goto cleanup; 950 } 951 952 /* 953 * Otherwise, we can try to continue our search with 954 * the next component. So try to look up the 955 * directory, e.g., "refs/foo/". If we come up empty, 956 * we know there is nothing under this whole prefix, 957 * but even in that case we still have to continue the 958 * search for conflicts with extras. 959 */ 960 strbuf_addch(&dirname, '/'); 961 if (dir) { 962 pos = search_ref_dir(dir, dirname.buf, dirname.len); 963 if (pos < 0) { 964 /* 965 * There was no directory "refs/foo/", 966 * so there is nothing under this 967 * whole prefix. So there is no need 968 * to continue looking for conflicting 969 * references. But we need to continue 970 * looking for conflicting extras. 971 */ 972 dir = NULL; 973 } else { 974 dir = get_ref_dir(dir->entries[pos]); 975 } 976 } 977 } 978 979 /* 980 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 981 * There is no point in searching for a reference with that 982 * name, because a refname isn't considered to conflict with 983 * itself. But we still need to check for references whose 984 * names are in the "refs/foo/bar/" namespace, because they 985 * *do* conflict. 986 */ 987 strbuf_addstr(&dirname, refname + dirname.len); 988 strbuf_addch(&dirname, '/'); 989 990 if (dir) { 991 pos = search_ref_dir(dir, dirname.buf, dirname.len); 992 993 if (pos >= 0) { 994 /* 995 * We found a directory named "$refname/" 996 * (e.g., "refs/foo/bar/"). It is a problem 997 * iff it contains any ref that is not in 998 * "skip". 999 */1000 struct nonmatching_ref_data data;10011002 data.skip = skip;1003 data.conflicting_refname = NULL;1004 dir = get_ref_dir(dir->entries[pos]);1005 sort_ref_dir(dir);1006 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {1007 strbuf_addf(err, "'%s' exists; cannot create '%s'",1008 data.conflicting_refname, refname);1009 goto cleanup;1010 }1011 }1012 }10131014 if (extras) {1015 /*1016 * Check for entries in extras that start with1017 * "$refname/". We do that by looking for the place1018 * where "$refname/" would be inserted in extras. If1019 * there is an entry at that position that starts with1020 * "$refname/" and is not in skip, then we have a1021 * conflict.1022 */1023 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);1024 pos < extras->nr; pos++) {1025 const char *extra_refname = extras->items[pos].string;10261027 if (!starts_with(extra_refname, dirname.buf))1028 break;10291030 if (!skip || !string_list_has_string(skip, extra_refname)) {1031 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",1032 refname, extra_refname);1033 goto cleanup;1034 }1035 }1036 }10371038 /* No conflicts were found */1039 ret = 0;10401041cleanup:1042 strbuf_release(&dirname);1043 return ret;1044}10451046struct packed_ref_cache {1047 struct ref_entry *root;10481049 /*1050 * Count of references to the data structure in this instance,1051 * including the pointer from ref_cache::packed if any. The1052 * data will not be freed as long as the reference count is1053 * nonzero.1054 */1055 unsigned int referrers;10561057 /*1058 * Iff the packed-refs file associated with this instance is1059 * currently locked for writing, this points at the associated1060 * lock (which is owned by somebody else). The referrer count1061 * is also incremented when the file is locked and decremented1062 * when it is unlocked.1063 */1064 struct lock_file *lock;10651066 /* The metadata from when this packed-refs cache was read */1067 struct stat_validity validity;1068};10691070/*1071 * Future: need to be in "struct repository"1072 * when doing a full libification.1073 */1074static struct ref_cache {1075 struct ref_cache *next;1076 struct ref_entry *loose;1077 struct packed_ref_cache *packed;1078 /*1079 * The submodule name, or "" for the main repo. We allocate1080 * length 1 rather than FLEX_ARRAY so that the main ref_cache1081 * is initialized correctly.1082 */1083 char name[1];1084} ref_cache, *submodule_ref_caches;10851086/* Lock used for the main packed-refs file: */1087static struct lock_file packlock;10881089/*1090 * Increment the reference count of *packed_refs.1091 */1092static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1093{1094 packed_refs->referrers++;1095}10961097/*1098 * Decrease the reference count of *packed_refs. If it goes to zero,1099 * free *packed_refs and return true; otherwise return false.1100 */1101static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)1102{1103 if (!--packed_refs->referrers) {1104 free_ref_entry(packed_refs->root);1105 stat_validity_clear(&packed_refs->validity);1106 free(packed_refs);1107 return 1;1108 } else {1109 return 0;1110 }1111}11121113static void clear_packed_ref_cache(struct ref_cache *refs)1114{1115 if (refs->packed) {1116 struct packed_ref_cache *packed_refs = refs->packed;11171118 if (packed_refs->lock)1119 die("internal error: packed-ref cache cleared while locked");1120 refs->packed = NULL;1121 release_packed_ref_cache(packed_refs);1122 }1123}11241125static void clear_loose_ref_cache(struct ref_cache *refs)1126{1127 if (refs->loose) {1128 free_ref_entry(refs->loose);1129 refs->loose = NULL;1130 }1131}11321133static struct ref_cache *create_ref_cache(const char *submodule)1134{1135 int len;1136 struct ref_cache *refs;1137 if (!submodule)1138 submodule = "";1139 len = strlen(submodule) + 1;1140 refs = xcalloc(1, sizeof(struct ref_cache) + len);1141 memcpy(refs->name, submodule, len);1142 return refs;1143}11441145/*1146 * Return a pointer to a ref_cache for the specified submodule. For1147 * the main repository, use submodule==NULL. The returned structure1148 * will be allocated and initialized but not necessarily populated; it1149 * should not be freed.1150 */1151static struct ref_cache *get_ref_cache(const char *submodule)1152{1153 struct ref_cache *refs;11541155 if (!submodule || !*submodule)1156 return &ref_cache;11571158 for (refs = submodule_ref_caches; refs; refs = refs->next)1159 if (!strcmp(submodule, refs->name))1160 return refs;11611162 refs = create_ref_cache(submodule);1163 refs->next = submodule_ref_caches;1164 submodule_ref_caches = refs;1165 return refs;1166}11671168/* The length of a peeled reference line in packed-refs, including EOL: */1169#define PEELED_LINE_LENGTH 4211701171/*1172 * The packed-refs header line that we write out. Perhaps other1173 * traits will be added later. The trailing space is required.1174 */1175static const char PACKED_REFS_HEADER[] =1176 "# pack-refs with: peeled fully-peeled \n";11771178/*1179 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1180 * Return a pointer to the refname within the line (null-terminated),1181 * or NULL if there was a problem.1182 */1183static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)1184{1185 const char *ref;11861187 /*1188 * 42: the answer to everything.1189 *1190 * In this case, it happens to be the answer to1191 * 40 (length of sha1 hex representation)1192 * +1 (space in between hex and name)1193 * +1 (newline at the end of the line)1194 */1195 if (line->len <= 42)1196 return NULL;11971198 if (get_sha1_hex(line->buf, sha1) < 0)1199 return NULL;1200 if (!isspace(line->buf[40]))1201 return NULL;12021203 ref = line->buf + 41;1204 if (isspace(*ref))1205 return NULL;12061207 if (line->buf[line->len - 1] != '\n')1208 return NULL;1209 line->buf[--line->len] = 0;12101211 return ref;1212}12131214/*1215 * Read f, which is a packed-refs file, into dir.1216 *1217 * A comment line of the form "# pack-refs with: " may contain zero or1218 * more traits. We interpret the traits as follows:1219 *1220 * No traits:1221 *1222 * Probably no references are peeled. But if the file contains a1223 * peeled value for a reference, we will use it.1224 *1225 * peeled:1226 *1227 * References under "refs/tags/", if they *can* be peeled, *are*1228 * peeled in this file. References outside of "refs/tags/" are1229 * probably not peeled even if they could have been, but if we find1230 * a peeled value for such a reference we will use it.1231 *1232 * fully-peeled:1233 *1234 * All references in the file that can be peeled are peeled.1235 * Inversely (and this is more important), any references in the1236 * file for which no peeled value is recorded is not peelable. This1237 * trait should typically be written alongside "peeled" for1238 * compatibility with older clients, but we do not require it1239 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1240 */1241static void read_packed_refs(FILE *f, struct ref_dir *dir)1242{1243 struct ref_entry *last = NULL;1244 struct strbuf line = STRBUF_INIT;1245 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12461247 while (strbuf_getwholeline(&line, f, '\n') != EOF) {1248 unsigned char sha1[20];1249 const char *refname;1250 const char *traits;12511252 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {1253 if (strstr(traits, " fully-peeled "))1254 peeled = PEELED_FULLY;1255 else if (strstr(traits, " peeled "))1256 peeled = PEELED_TAGS;1257 /* perhaps other traits later as well */1258 continue;1259 }12601261 refname = parse_ref_line(&line, sha1);1262 if (refname) {1263 int flag = REF_ISPACKED;12641265 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1266 if (!refname_is_safe(refname))1267 die("packed refname is dangerous: %s", refname);1268 hashclr(sha1);1269 flag |= REF_BAD_NAME | REF_ISBROKEN;1270 }1271 last = create_ref_entry(refname, sha1, flag, 0);1272 if (peeled == PEELED_FULLY ||1273 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))1274 last->flag |= REF_KNOWS_PEELED;1275 add_ref(dir, last);1276 continue;1277 }1278 if (last &&1279 line.buf[0] == '^' &&1280 line.len == PEELED_LINE_LENGTH &&1281 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&1282 !get_sha1_hex(line.buf + 1, sha1)) {1283 hashcpy(last->u.value.peeled.hash, sha1);1284 /*1285 * Regardless of what the file header said,1286 * we definitely know the value of *this*1287 * reference:1288 */1289 last->flag |= REF_KNOWS_PEELED;1290 }1291 }12921293 strbuf_release(&line);1294}12951296/*1297 * Get the packed_ref_cache for the specified ref_cache, creating it1298 * if necessary.1299 */1300static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1301{1302 char *packed_refs_file;13031304 if (*refs->name)1305 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");1306 else1307 packed_refs_file = git_pathdup("packed-refs");13081309 if (refs->packed &&1310 !stat_validity_check(&refs->packed->validity, packed_refs_file))1311 clear_packed_ref_cache(refs);13121313 if (!refs->packed) {1314 FILE *f;13151316 refs->packed = xcalloc(1, sizeof(*refs->packed));1317 acquire_packed_ref_cache(refs->packed);1318 refs->packed->root = create_dir_entry(refs, "", 0, 0);1319 f = fopen(packed_refs_file, "r");1320 if (f) {1321 stat_validity_update(&refs->packed->validity, fileno(f));1322 read_packed_refs(f, get_ref_dir(refs->packed->root));1323 fclose(f);1324 }1325 }1326 free(packed_refs_file);1327 return refs->packed;1328}13291330static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1331{1332 return get_ref_dir(packed_ref_cache->root);1333}13341335static struct ref_dir *get_packed_refs(struct ref_cache *refs)1336{1337 return get_packed_ref_dir(get_packed_ref_cache(refs));1338}13391340/*1341 * Add a reference to the in-memory packed reference cache. This may1342 * only be called while the packed-refs file is locked (see1343 * lock_packed_refs()). To actually write the packed-refs file, call1344 * commit_packed_refs().1345 */1346static void add_packed_ref(const char *refname, const unsigned char *sha1)1347{1348 struct packed_ref_cache *packed_ref_cache =1349 get_packed_ref_cache(&ref_cache);13501351 if (!packed_ref_cache->lock)1352 die("internal error: packed refs not locked");1353 add_ref(get_packed_ref_dir(packed_ref_cache),1354 create_ref_entry(refname, sha1, REF_ISPACKED, 1));1355}13561357/*1358 * Read the loose references from the namespace dirname into dir1359 * (without recursing). dirname must end with '/'. dir must be the1360 * directory entry corresponding to dirname.1361 */1362static void read_loose_refs(const char *dirname, struct ref_dir *dir)1363{1364 struct ref_cache *refs = dir->ref_cache;1365 DIR *d;1366 struct dirent *de;1367 int dirnamelen = strlen(dirname);1368 struct strbuf refname;1369 struct strbuf path = STRBUF_INIT;1370 size_t path_baselen;13711372 if (*refs->name)1373 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);1374 else1375 strbuf_git_path(&path, "%s", dirname);1376 path_baselen = path.len;13771378 d = opendir(path.buf);1379 if (!d) {1380 strbuf_release(&path);1381 return;1382 }13831384 strbuf_init(&refname, dirnamelen + 257);1385 strbuf_add(&refname, dirname, dirnamelen);13861387 while ((de = readdir(d)) != NULL) {1388 unsigned char sha1[20];1389 struct stat st;1390 int flag;13911392 if (de->d_name[0] == '.')1393 continue;1394 if (ends_with(de->d_name, ".lock"))1395 continue;1396 strbuf_addstr(&refname, de->d_name);1397 strbuf_addstr(&path, de->d_name);1398 if (stat(path.buf, &st) < 0) {1399 ; /* silently ignore */1400 } else if (S_ISDIR(st.st_mode)) {1401 strbuf_addch(&refname, '/');1402 add_entry_to_dir(dir,1403 create_dir_entry(refs, refname.buf,1404 refname.len, 1));1405 } else {1406 int read_ok;14071408 if (*refs->name) {1409 hashclr(sha1);1410 flag = 0;1411 read_ok = !resolve_gitlink_ref(refs->name,1412 refname.buf, sha1);1413 } else {1414 read_ok = !read_ref_full(refname.buf,1415 RESOLVE_REF_READING,1416 sha1, &flag);1417 }14181419 if (!read_ok) {1420 hashclr(sha1);1421 flag |= REF_ISBROKEN;1422 } else if (is_null_sha1(sha1)) {1423 /*1424 * It is so astronomically unlikely1425 * that NULL_SHA1 is the SHA-1 of an1426 * actual object that we consider its1427 * appearance in a loose reference1428 * file to be repo corruption1429 * (probably due to a software bug).1430 */1431 flag |= REF_ISBROKEN;1432 }14331434 if (check_refname_format(refname.buf,1435 REFNAME_ALLOW_ONELEVEL)) {1436 if (!refname_is_safe(refname.buf))1437 die("loose refname is dangerous: %s", refname.buf);1438 hashclr(sha1);1439 flag |= REF_BAD_NAME | REF_ISBROKEN;1440 }1441 add_entry_to_dir(dir,1442 create_ref_entry(refname.buf, sha1, flag, 0));1443 }1444 strbuf_setlen(&refname, dirnamelen);1445 strbuf_setlen(&path, path_baselen);1446 }1447 strbuf_release(&refname);1448 strbuf_release(&path);1449 closedir(d);1450}14511452static struct ref_dir *get_loose_refs(struct ref_cache *refs)1453{1454 if (!refs->loose) {1455 /*1456 * Mark the top-level directory complete because we1457 * are about to read the only subdirectory that can1458 * hold references:1459 */1460 refs->loose = create_dir_entry(refs, "", 0, 0);1461 /*1462 * Create an incomplete entry for "refs/":1463 */1464 add_entry_to_dir(get_ref_dir(refs->loose),1465 create_dir_entry(refs, "refs/", 5, 1));1466 }1467 return get_ref_dir(refs->loose);1468}14691470/* We allow "recursive" symbolic refs. Only within reason, though */1471#define MAXDEPTH 51472#define MAXREFLEN (1024)14731474/*1475 * Called by resolve_gitlink_ref_recursive() after it failed to read1476 * from the loose refs in ref_cache refs. Find <refname> in the1477 * packed-refs file for the submodule.1478 */1479static int resolve_gitlink_packed_ref(struct ref_cache *refs,1480 const char *refname, unsigned char *sha1)1481{1482 struct ref_entry *ref;1483 struct ref_dir *dir = get_packed_refs(refs);14841485 ref = find_ref(dir, refname);1486 if (ref == NULL)1487 return -1;14881489 hashcpy(sha1, ref->u.value.oid.hash);1490 return 0;1491}14921493static int resolve_gitlink_ref_recursive(struct ref_cache *refs,1494 const char *refname, unsigned char *sha1,1495 int recursion)1496{1497 int fd, len;1498 char buffer[128], *p;1499 char *path;15001501 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)1502 return -1;1503 path = *refs->name1504 ? git_pathdup_submodule(refs->name, "%s", refname)1505 : git_pathdup("%s", refname);1506 fd = open(path, O_RDONLY);1507 free(path);1508 if (fd < 0)1509 return resolve_gitlink_packed_ref(refs, refname, sha1);15101511 len = read(fd, buffer, sizeof(buffer)-1);1512 close(fd);1513 if (len < 0)1514 return -1;1515 while (len && isspace(buffer[len-1]))1516 len--;1517 buffer[len] = 0;15181519 /* Was it a detached head or an old-fashioned symlink? */1520 if (!get_sha1_hex(buffer, sha1))1521 return 0;15221523 /* Symref? */1524 if (strncmp(buffer, "ref:", 4))1525 return -1;1526 p = buffer + 4;1527 while (isspace(*p))1528 p++;15291530 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1531}15321533int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)1534{1535 int len = strlen(path), retval;1536 char *submodule;1537 struct ref_cache *refs;15381539 while (len && path[len-1] == '/')1540 len--;1541 if (!len)1542 return -1;1543 submodule = xstrndup(path, len);1544 refs = get_ref_cache(submodule);1545 free(submodule);15461547 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);1548 return retval;1549}15501551/*1552 * Return the ref_entry for the given refname from the packed1553 * references. If it does not exist, return NULL.1554 */1555static struct ref_entry *get_packed_ref(const char *refname)1556{1557 return find_ref(get_packed_refs(&ref_cache), refname);1558}15591560/*1561 * A loose ref file doesn't exist; check for a packed ref. The1562 * options are forwarded from resolve_safe_unsafe().1563 */1564static int resolve_missing_loose_ref(const char *refname,1565 int resolve_flags,1566 unsigned char *sha1,1567 int *flags)1568{1569 struct ref_entry *entry;15701571 /*1572 * The loose reference file does not exist; check for a packed1573 * reference.1574 */1575 entry = get_packed_ref(refname);1576 if (entry) {1577 hashcpy(sha1, entry->u.value.oid.hash);1578 if (flags)1579 *flags |= REF_ISPACKED;1580 return 0;1581 }1582 /* The reference is not a packed reference, either. */1583 if (resolve_flags & RESOLVE_REF_READING) {1584 errno = ENOENT;1585 return -1;1586 } else {1587 hashclr(sha1);1588 return 0;1589 }1590}15911592/* This function needs to return a meaningful errno on failure */1593static const char *resolve_ref_1(const char *refname,1594 int resolve_flags,1595 unsigned char *sha1,1596 int *flags,1597 struct strbuf *sb_refname,1598 struct strbuf *sb_path,1599 struct strbuf *sb_contents)1600{1601 int depth = MAXDEPTH;1602 int bad_name = 0;16031604 if (flags)1605 *flags = 0;16061607 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1608 if (flags)1609 *flags |= REF_BAD_NAME;16101611 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1612 !refname_is_safe(refname)) {1613 errno = EINVAL;1614 return NULL;1615 }1616 /*1617 * dwim_ref() uses REF_ISBROKEN to distinguish between1618 * missing refs and refs that were present but invalid,1619 * to complain about the latter to stderr.1620 *1621 * We don't know whether the ref exists, so don't set1622 * REF_ISBROKEN yet.1623 */1624 bad_name = 1;1625 }1626 for (;;) {1627 const char *path;1628 struct stat st;1629 char *buf;1630 int fd;16311632 if (--depth < 0) {1633 errno = ELOOP;1634 return NULL;1635 }16361637 strbuf_reset(sb_path);1638 strbuf_git_path(sb_path, "%s", refname);1639 path = sb_path->buf;16401641 /*1642 * We might have to loop back here to avoid a race1643 * condition: first we lstat() the file, then we try1644 * to read it as a link or as a file. But if somebody1645 * changes the type of the file (file <-> directory1646 * <-> symlink) between the lstat() and reading, then1647 * we don't want to report that as an error but rather1648 * try again starting with the lstat().1649 */1650 stat_ref:1651 if (lstat(path, &st) < 0) {1652 if (errno != ENOENT)1653 return NULL;1654 if (resolve_missing_loose_ref(refname, resolve_flags,1655 sha1, flags))1656 return NULL;1657 if (bad_name) {1658 hashclr(sha1);1659 if (flags)1660 *flags |= REF_ISBROKEN;1661 }1662 return refname;1663 }16641665 /* Follow "normalized" - ie "refs/.." symlinks by hand */1666 if (S_ISLNK(st.st_mode)) {1667 strbuf_reset(sb_contents);1668 if (strbuf_readlink(sb_contents, path, 0) < 0) {1669 if (errno == ENOENT || errno == EINVAL)1670 /* inconsistent with lstat; retry */1671 goto stat_ref;1672 else1673 return NULL;1674 }1675 if (starts_with(sb_contents->buf, "refs/") &&1676 !check_refname_format(sb_contents->buf, 0)) {1677 strbuf_swap(sb_refname, sb_contents);1678 refname = sb_refname->buf;1679 if (flags)1680 *flags |= REF_ISSYMREF;1681 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1682 hashclr(sha1);1683 return refname;1684 }1685 continue;1686 }1687 }16881689 /* Is it a directory? */1690 if (S_ISDIR(st.st_mode)) {1691 errno = EISDIR;1692 return NULL;1693 }16941695 /*1696 * Anything else, just open it and try to use it as1697 * a ref1698 */1699 fd = open(path, O_RDONLY);1700 if (fd < 0) {1701 if (errno == ENOENT)1702 /* inconsistent with lstat; retry */1703 goto stat_ref;1704 else1705 return NULL;1706 }1707 strbuf_reset(sb_contents);1708 if (strbuf_read(sb_contents, fd, 256) < 0) {1709 int save_errno = errno;1710 close(fd);1711 errno = save_errno;1712 return NULL;1713 }1714 close(fd);1715 strbuf_rtrim(sb_contents);17161717 /*1718 * Is it a symbolic ref?1719 */1720 if (!starts_with(sb_contents->buf, "ref:")) {1721 /*1722 * Please note that FETCH_HEAD has a second1723 * line containing other data.1724 */1725 if (get_sha1_hex(sb_contents->buf, sha1) ||1726 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {1727 if (flags)1728 *flags |= REF_ISBROKEN;1729 errno = EINVAL;1730 return NULL;1731 }1732 if (bad_name) {1733 hashclr(sha1);1734 if (flags)1735 *flags |= REF_ISBROKEN;1736 }1737 return refname;1738 }1739 if (flags)1740 *flags |= REF_ISSYMREF;1741 buf = sb_contents->buf + 4;1742 while (isspace(*buf))1743 buf++;1744 strbuf_reset(sb_refname);1745 strbuf_addstr(sb_refname, buf);1746 refname = sb_refname->buf;1747 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1748 hashclr(sha1);1749 return refname;1750 }1751 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1752 if (flags)1753 *flags |= REF_ISBROKEN;17541755 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1756 !refname_is_safe(buf)) {1757 errno = EINVAL;1758 return NULL;1759 }1760 bad_name = 1;1761 }1762 }1763}17641765const char *resolve_ref_unsafe(const char *refname, int resolve_flags,1766 unsigned char *sha1, int *flags)1767{1768 static struct strbuf sb_refname = STRBUF_INIT;1769 struct strbuf sb_contents = STRBUF_INIT;1770 struct strbuf sb_path = STRBUF_INIT;1771 const char *ret;17721773 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,1774 &sb_refname, &sb_path, &sb_contents);1775 strbuf_release(&sb_path);1776 strbuf_release(&sb_contents);1777 return ret;1778}17791780char *resolve_refdup(const char *refname, int resolve_flags,1781 unsigned char *sha1, int *flags)1782{1783 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1784 sha1, flags));1785}17861787/* The argument to filter_refs */1788struct ref_filter {1789 const char *pattern;1790 each_ref_fn *fn;1791 void *cb_data;1792};17931794int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)1795{1796 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1797 return 0;1798 return -1;1799}18001801int read_ref(const char *refname, unsigned char *sha1)1802{1803 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1804}18051806int ref_exists(const char *refname)1807{1808 unsigned char sha1[20];1809 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1810}18111812static int filter_refs(const char *refname, const struct object_id *oid,1813 int flags, void *data)1814{1815 struct ref_filter *filter = (struct ref_filter *)data;18161817 if (wildmatch(filter->pattern, refname, 0, NULL))1818 return 0;1819 return filter->fn(refname, oid, flags, filter->cb_data);1820}18211822enum peel_status {1823 /* object was peeled successfully: */1824 PEEL_PEELED = 0,18251826 /*1827 * object cannot be peeled because the named object (or an1828 * object referred to by a tag in the peel chain), does not1829 * exist.1830 */1831 PEEL_INVALID = -1,18321833 /* object cannot be peeled because it is not a tag: */1834 PEEL_NON_TAG = -2,18351836 /* ref_entry contains no peeled value because it is a symref: */1837 PEEL_IS_SYMREF = -3,18381839 /*1840 * ref_entry cannot be peeled because it is broken (i.e., the1841 * symbolic reference cannot even be resolved to an object1842 * name):1843 */1844 PEEL_BROKEN = -41845};18461847/*1848 * Peel the named object; i.e., if the object is a tag, resolve the1849 * tag recursively until a non-tag is found. If successful, store the1850 * result to sha1 and return PEEL_PEELED. If the object is not a tag1851 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1852 * and leave sha1 unchanged.1853 */1854static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)1855{1856 struct object *o = lookup_unknown_object(name);18571858 if (o->type == OBJ_NONE) {1859 int type = sha1_object_info(name, NULL);1860 if (type < 0 || !object_as_type(o, type, 0))1861 return PEEL_INVALID;1862 }18631864 if (o->type != OBJ_TAG)1865 return PEEL_NON_TAG;18661867 o = deref_tag_noverify(o);1868 if (!o)1869 return PEEL_INVALID;18701871 hashcpy(sha1, o->sha1);1872 return PEEL_PEELED;1873}18741875/*1876 * Peel the entry (if possible) and return its new peel_status. If1877 * repeel is true, re-peel the entry even if there is an old peeled1878 * value that is already stored in it.1879 *1880 * It is OK to call this function with a packed reference entry that1881 * might be stale and might even refer to an object that has since1882 * been garbage-collected. In such a case, if the entry has1883 * REF_KNOWS_PEELED then leave the status unchanged and return1884 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1885 */1886static enum peel_status peel_entry(struct ref_entry *entry, int repeel)1887{1888 enum peel_status status;18891890 if (entry->flag & REF_KNOWS_PEELED) {1891 if (repeel) {1892 entry->flag &= ~REF_KNOWS_PEELED;1893 oidclr(&entry->u.value.peeled);1894 } else {1895 return is_null_oid(&entry->u.value.peeled) ?1896 PEEL_NON_TAG : PEEL_PEELED;1897 }1898 }1899 if (entry->flag & REF_ISBROKEN)1900 return PEEL_BROKEN;1901 if (entry->flag & REF_ISSYMREF)1902 return PEEL_IS_SYMREF;19031904 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1905 if (status == PEEL_PEELED || status == PEEL_NON_TAG)1906 entry->flag |= REF_KNOWS_PEELED;1907 return status;1908}19091910int peel_ref(const char *refname, unsigned char *sha1)1911{1912 int flag;1913 unsigned char base[20];19141915 if (current_ref && (current_ref->name == refname1916 || !strcmp(current_ref->name, refname))) {1917 if (peel_entry(current_ref, 0))1918 return -1;1919 hashcpy(sha1, current_ref->u.value.peeled.hash);1920 return 0;1921 }19221923 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1924 return -1;19251926 /*1927 * If the reference is packed, read its ref_entry from the1928 * cache in the hope that we already know its peeled value.1929 * We only try this optimization on packed references because1930 * (a) forcing the filling of the loose reference cache could1931 * be expensive and (b) loose references anyway usually do not1932 * have REF_KNOWS_PEELED.1933 */1934 if (flag & REF_ISPACKED) {1935 struct ref_entry *r = get_packed_ref(refname);1936 if (r) {1937 if (peel_entry(r, 0))1938 return -1;1939 hashcpy(sha1, r->u.value.peeled.hash);1940 return 0;1941 }1942 }19431944 return peel_object(base, sha1);1945}19461947struct warn_if_dangling_data {1948 FILE *fp;1949 const char *refname;1950 const struct string_list *refnames;1951 const char *msg_fmt;1952};19531954static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,1955 int flags, void *cb_data)1956{1957 struct warn_if_dangling_data *d = cb_data;1958 const char *resolves_to;1959 struct object_id junk;19601961 if (!(flags & REF_ISSYMREF))1962 return 0;19631964 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);1965 if (!resolves_to1966 || (d->refname1967 ? strcmp(resolves_to, d->refname)1968 : !string_list_has_string(d->refnames, resolves_to))) {1969 return 0;1970 }19711972 fprintf(d->fp, d->msg_fmt, refname);1973 fputc('\n', d->fp);1974 return 0;1975}19761977void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)1978{1979 struct warn_if_dangling_data data;19801981 data.fp = fp;1982 data.refname = refname;1983 data.refnames = NULL;1984 data.msg_fmt = msg_fmt;1985 for_each_rawref(warn_if_dangling_symref, &data);1986}19871988void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)1989{1990 struct warn_if_dangling_data data;19911992 data.fp = fp;1993 data.refname = NULL;1994 data.refnames = refnames;1995 data.msg_fmt = msg_fmt;1996 for_each_rawref(warn_if_dangling_symref, &data);1997}19981999/*2000 * Call fn for each reference in the specified ref_cache, omitting2001 * references not in the containing_dir of base. fn is called for all2002 * references, including broken ones. If fn ever returns a non-zero2003 * value, stop the iteration and return that value; otherwise, return2004 * 0.2005 */2006static int do_for_each_entry(struct ref_cache *refs, const char *base,2007 each_ref_entry_fn fn, void *cb_data)2008{2009 struct packed_ref_cache *packed_ref_cache;2010 struct ref_dir *loose_dir;2011 struct ref_dir *packed_dir;2012 int retval = 0;20132014 /*2015 * We must make sure that all loose refs are read before accessing the2016 * packed-refs file; this avoids a race condition in which loose refs2017 * are migrated to the packed-refs file by a simultaneous process, but2018 * our in-memory view is from before the migration. get_packed_ref_cache()2019 * takes care of making sure our view is up to date with what is on2020 * disk.2021 */2022 loose_dir = get_loose_refs(refs);2023 if (base && *base) {2024 loose_dir = find_containing_dir(loose_dir, base, 0);2025 }2026 if (loose_dir)2027 prime_ref_dir(loose_dir);20282029 packed_ref_cache = get_packed_ref_cache(refs);2030 acquire_packed_ref_cache(packed_ref_cache);2031 packed_dir = get_packed_ref_dir(packed_ref_cache);2032 if (base && *base) {2033 packed_dir = find_containing_dir(packed_dir, base, 0);2034 }20352036 if (packed_dir && loose_dir) {2037 sort_ref_dir(packed_dir);2038 sort_ref_dir(loose_dir);2039 retval = do_for_each_entry_in_dirs(2040 packed_dir, loose_dir, fn, cb_data);2041 } else if (packed_dir) {2042 sort_ref_dir(packed_dir);2043 retval = do_for_each_entry_in_dir(2044 packed_dir, 0, fn, cb_data);2045 } else if (loose_dir) {2046 sort_ref_dir(loose_dir);2047 retval = do_for_each_entry_in_dir(2048 loose_dir, 0, fn, cb_data);2049 }20502051 release_packed_ref_cache(packed_ref_cache);2052 return retval;2053}20542055/*2056 * Call fn for each reference in the specified ref_cache for which the2057 * refname begins with base. If trim is non-zero, then trim that many2058 * characters off the beginning of each refname before passing the2059 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2060 * broken references in the iteration. If fn ever returns a non-zero2061 * value, stop the iteration and return that value; otherwise, return2062 * 0.2063 */2064static int do_for_each_ref(struct ref_cache *refs, const char *base,2065 each_ref_fn fn, int trim, int flags, void *cb_data)2066{2067 struct ref_entry_cb data;2068 data.base = base;2069 data.trim = trim;2070 data.flags = flags;2071 data.fn = fn;2072 data.cb_data = cb_data;20732074 if (ref_paranoia < 0)2075 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);2076 if (ref_paranoia)2077 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20782079 return do_for_each_entry(refs, base, do_one_ref, &data);2080}20812082static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)2083{2084 struct object_id oid;2085 int flag;20862087 if (submodule) {2088 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)2089 return fn("HEAD", &oid, 0, cb_data);20902091 return 0;2092 }20932094 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2095 return fn("HEAD", &oid, flag, cb_data);20962097 return 0;2098}20992100int head_ref(each_ref_fn fn, void *cb_data)2101{2102 return do_head_ref(NULL, fn, cb_data);2103}21042105int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2106{2107 return do_head_ref(submodule, fn, cb_data);2108}21092110int for_each_ref(each_ref_fn fn, void *cb_data)2111{2112 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);2113}21142115int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2116{2117 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);2118}21192120int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)2121{2122 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);2123}21242125int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)2126{2127 unsigned int flag = 0;21282129 if (broken)2130 flag = DO_FOR_EACH_INCLUDE_BROKEN;2131 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);2132}21332134int for_each_ref_in_submodule(const char *submodule, const char *prefix,2135 each_ref_fn fn, void *cb_data)2136{2137 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);2138}21392140int for_each_tag_ref(each_ref_fn fn, void *cb_data)2141{2142 return for_each_ref_in("refs/tags/", fn, cb_data);2143}21442145int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2146{2147 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);2148}21492150int for_each_branch_ref(each_ref_fn fn, void *cb_data)2151{2152 return for_each_ref_in("refs/heads/", fn, cb_data);2153}21542155int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2156{2157 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);2158}21592160int for_each_remote_ref(each_ref_fn fn, void *cb_data)2161{2162 return for_each_ref_in("refs/remotes/", fn, cb_data);2163}21642165int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)2166{2167 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);2168}21692170int for_each_replace_ref(each_ref_fn fn, void *cb_data)2171{2172 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,2173 strlen(git_replace_ref_base), 0, cb_data);2174}21752176int head_ref_namespaced(each_ref_fn fn, void *cb_data)2177{2178 struct strbuf buf = STRBUF_INIT;2179 int ret = 0;2180 struct object_id oid;2181 int flag;21822183 strbuf_addf(&buf, "%sHEAD", get_git_namespace());2184 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2185 ret = fn(buf.buf, &oid, flag, cb_data);2186 strbuf_release(&buf);21872188 return ret;2189}21902191int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)2192{2193 struct strbuf buf = STRBUF_INIT;2194 int ret;2195 strbuf_addf(&buf, "%srefs/", get_git_namespace());2196 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);2197 strbuf_release(&buf);2198 return ret;2199}22002201int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,2202 const char *prefix, void *cb_data)2203{2204 struct strbuf real_pattern = STRBUF_INIT;2205 struct ref_filter filter;2206 int ret;22072208 if (!prefix && !starts_with(pattern, "refs/"))2209 strbuf_addstr(&real_pattern, "refs/");2210 else if (prefix)2211 strbuf_addstr(&real_pattern, prefix);2212 strbuf_addstr(&real_pattern, pattern);22132214 if (!has_glob_specials(pattern)) {2215 /* Append implied '/' '*' if not present. */2216 strbuf_complete(&real_pattern, '/');2217 /* No need to check for '*', there is none. */2218 strbuf_addch(&real_pattern, '*');2219 }22202221 filter.pattern = real_pattern.buf;2222 filter.fn = fn;2223 filter.cb_data = cb_data;2224 ret = for_each_ref(filter_refs, &filter);22252226 strbuf_release(&real_pattern);2227 return ret;2228}22292230int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)2231{2232 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);2233}22342235int for_each_rawref(each_ref_fn fn, void *cb_data)2236{2237 return do_for_each_ref(&ref_cache, "", fn, 0,2238 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2239}22402241const char *prettify_refname(const char *name)2242{2243 return name + (2244 starts_with(name, "refs/heads/") ? 11 :2245 starts_with(name, "refs/tags/") ? 10 :2246 starts_with(name, "refs/remotes/") ? 13 :2247 0);2248}22492250static const char *ref_rev_parse_rules[] = {2251 "%.*s",2252 "refs/%.*s",2253 "refs/tags/%.*s",2254 "refs/heads/%.*s",2255 "refs/remotes/%.*s",2256 "refs/remotes/%.*s/HEAD",2257 NULL2258};22592260int refname_match(const char *abbrev_name, const char *full_name)2261{2262 const char **p;2263 const int abbrev_name_len = strlen(abbrev_name);22642265 for (p = ref_rev_parse_rules; *p; p++) {2266 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {2267 return 1;2268 }2269 }22702271 return 0;2272}22732274static void unlock_ref(struct ref_lock *lock)2275{2276 /* Do not free lock->lk -- atexit() still looks at them */2277 if (lock->lk)2278 rollback_lock_file(lock->lk);2279 free(lock->ref_name);2280 free(lock->orig_ref_name);2281 free(lock);2282}22832284/*2285 * Verify that the reference locked by lock has the value old_sha1.2286 * Fail if the reference doesn't exist and mustexist is set. Return 02287 * on success. On error, write an error message to err, set errno, and2288 * return a negative value.2289 */2290static int verify_lock(struct ref_lock *lock,2291 const unsigned char *old_sha1, int mustexist,2292 struct strbuf *err)2293{2294 assert(err);22952296 if (read_ref_full(lock->ref_name,2297 mustexist ? RESOLVE_REF_READING : 0,2298 lock->old_oid.hash, NULL)) {2299 int save_errno = errno;2300 strbuf_addf(err, "can't verify ref %s", lock->ref_name);2301 errno = save_errno;2302 return -1;2303 }2304 if (hashcmp(lock->old_oid.hash, old_sha1)) {2305 strbuf_addf(err, "ref %s is at %s but expected %s",2306 lock->ref_name,2307 sha1_to_hex(lock->old_oid.hash),2308 sha1_to_hex(old_sha1));2309 errno = EBUSY;2310 return -1;2311 }2312 return 0;2313}23142315static int remove_empty_directories(struct strbuf *path)2316{2317 /*2318 * we want to create a file but there is a directory there;2319 * if that is an empty directory (or a directory that contains2320 * only empty directories), remove them.2321 */2322 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2323}23242325/*2326 * *string and *len will only be substituted, and *string returned (for2327 * later free()ing) if the string passed in is a magic short-hand form2328 * to name a branch.2329 */2330static char *substitute_branch_name(const char **string, int *len)2331{2332 struct strbuf buf = STRBUF_INIT;2333 int ret = interpret_branch_name(*string, *len, &buf);23342335 if (ret == *len) {2336 size_t size;2337 *string = strbuf_detach(&buf, &size);2338 *len = size;2339 return (char *)*string;2340 }23412342 return NULL;2343}23442345int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)2346{2347 char *last_branch = substitute_branch_name(&str, &len);2348 const char **p, *r;2349 int refs_found = 0;23502351 *ref = NULL;2352 for (p = ref_rev_parse_rules; *p; p++) {2353 char fullref[PATH_MAX];2354 unsigned char sha1_from_ref[20];2355 unsigned char *this_result;2356 int flag;23572358 this_result = refs_found ? sha1_from_ref : sha1;2359 mksnpath(fullref, sizeof(fullref), *p, len, str);2360 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2361 this_result, &flag);2362 if (r) {2363 if (!refs_found++)2364 *ref = xstrdup(r);2365 if (!warn_ambiguous_refs)2366 break;2367 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {2368 warning("ignoring dangling symref %s.", fullref);2369 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {2370 warning("ignoring broken ref %s.", fullref);2371 }2372 }2373 free(last_branch);2374 return refs_found;2375}23762377int dwim_log(const char *str, int len, unsigned char *sha1, char **log)2378{2379 char *last_branch = substitute_branch_name(&str, &len);2380 const char **p;2381 int logs_found = 0;23822383 *log = NULL;2384 for (p = ref_rev_parse_rules; *p; p++) {2385 unsigned char hash[20];2386 char path[PATH_MAX];2387 const char *ref, *it;23882389 mksnpath(path, sizeof(path), *p, len, str);2390 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,2391 hash, NULL);2392 if (!ref)2393 continue;2394 if (reflog_exists(path))2395 it = path;2396 else if (strcmp(ref, path) && reflog_exists(ref))2397 it = ref;2398 else2399 continue;2400 if (!logs_found++) {2401 *log = xstrdup(it);2402 hashcpy(sha1, hash);2403 }2404 if (!warn_ambiguous_refs)2405 break;2406 }2407 free(last_branch);2408 return logs_found;2409}24102411/*2412 * Locks a ref returning the lock on success and NULL on failure.2413 * On failure errno is set to something meaningful.2414 */2415static struct ref_lock *lock_ref_sha1_basic(const char *refname,2416 const unsigned char *old_sha1,2417 const struct string_list *extras,2418 const struct string_list *skip,2419 unsigned int flags, int *type_p,2420 struct strbuf *err)2421{2422 struct strbuf ref_file = STRBUF_INIT;2423 struct strbuf orig_ref_file = STRBUF_INIT;2424 const char *orig_refname = refname;2425 struct ref_lock *lock;2426 int last_errno = 0;2427 int type, lflags;2428 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2429 int resolve_flags = 0;2430 int attempts_remaining = 3;24312432 assert(err);24332434 lock = xcalloc(1, sizeof(struct ref_lock));24352436 if (mustexist)2437 resolve_flags |= RESOLVE_REF_READING;2438 if (flags & REF_DELETING) {2439 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2440 if (flags & REF_NODEREF)2441 resolve_flags |= RESOLVE_REF_NO_RECURSE;2442 }24432444 refname = resolve_ref_unsafe(refname, resolve_flags,2445 lock->old_oid.hash, &type);2446 if (!refname && errno == EISDIR) {2447 /*2448 * we are trying to lock foo but we used to2449 * have foo/bar which now does not exist;2450 * it is normal for the empty directory 'foo'2451 * to remain.2452 */2453 strbuf_git_path(&orig_ref_file, "%s", orig_refname);2454 if (remove_empty_directories(&orig_ref_file)) {2455 last_errno = errno;2456 if (!verify_refname_available_dir(orig_refname, extras, skip,2457 get_loose_refs(&ref_cache), err))2458 strbuf_addf(err, "there are still refs under '%s'",2459 orig_refname);2460 goto error_return;2461 }2462 refname = resolve_ref_unsafe(orig_refname, resolve_flags,2463 lock->old_oid.hash, &type);2464 }2465 if (type_p)2466 *type_p = type;2467 if (!refname) {2468 last_errno = errno;2469 if (last_errno != ENOTDIR ||2470 !verify_refname_available_dir(orig_refname, extras, skip,2471 get_loose_refs(&ref_cache), err))2472 strbuf_addf(err, "unable to resolve reference %s: %s",2473 orig_refname, strerror(last_errno));24742475 goto error_return;2476 }2477 /*2478 * If the ref did not exist and we are creating it, make sure2479 * there is no existing packed ref whose name begins with our2480 * refname, nor a packed ref whose name is a proper prefix of2481 * our refname.2482 */2483 if (is_null_oid(&lock->old_oid) &&2484 verify_refname_available_dir(refname, extras, skip,2485 get_packed_refs(&ref_cache), err)) {2486 last_errno = ENOTDIR;2487 goto error_return;2488 }24892490 lock->lk = xcalloc(1, sizeof(struct lock_file));24912492 lflags = 0;2493 if (flags & REF_NODEREF) {2494 refname = orig_refname;2495 lflags |= LOCK_NO_DEREF;2496 }2497 lock->ref_name = xstrdup(refname);2498 lock->orig_ref_name = xstrdup(orig_refname);2499 strbuf_git_path(&ref_file, "%s", refname);25002501 retry:2502 switch (safe_create_leading_directories_const(ref_file.buf)) {2503 case SCLD_OK:2504 break; /* success */2505 case SCLD_VANISHED:2506 if (--attempts_remaining > 0)2507 goto retry;2508 /* fall through */2509 default:2510 last_errno = errno;2511 strbuf_addf(err, "unable to create directory for %s",2512 ref_file.buf);2513 goto error_return;2514 }25152516 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {2517 last_errno = errno;2518 if (errno == ENOENT && --attempts_remaining > 0)2519 /*2520 * Maybe somebody just deleted one of the2521 * directories leading to ref_file. Try2522 * again:2523 */2524 goto retry;2525 else {2526 unable_to_lock_message(ref_file.buf, errno, err);2527 goto error_return;2528 }2529 }2530 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {2531 last_errno = errno;2532 goto error_return;2533 }2534 goto out;25352536 error_return:2537 unlock_ref(lock);2538 lock = NULL;25392540 out:2541 strbuf_release(&ref_file);2542 strbuf_release(&orig_ref_file);2543 errno = last_errno;2544 return lock;2545}25462547/*2548 * Write an entry to the packed-refs file for the specified refname.2549 * If peeled is non-NULL, write it as the entry's peeled value.2550 */2551static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,2552 unsigned char *peeled)2553{2554 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);2555 if (peeled)2556 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));2557}25582559/*2560 * An each_ref_entry_fn that writes the entry to a packed-refs file.2561 */2562static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)2563{2564 enum peel_status peel_status = peel_entry(entry, 0);25652566 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2567 error("internal error: %s is not a valid packed reference!",2568 entry->name);2569 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2570 peel_status == PEEL_PEELED ?2571 entry->u.value.peeled.hash : NULL);2572 return 0;2573}25742575/*2576 * Lock the packed-refs file for writing. Flags is passed to2577 * hold_lock_file_for_update(). Return 0 on success. On errors, set2578 * errno appropriately and return a nonzero value.2579 */2580static int lock_packed_refs(int flags)2581{2582 static int timeout_configured = 0;2583 static int timeout_value = 1000;25842585 struct packed_ref_cache *packed_ref_cache;25862587 if (!timeout_configured) {2588 git_config_get_int("core.packedrefstimeout", &timeout_value);2589 timeout_configured = 1;2590 }25912592 if (hold_lock_file_for_update_timeout(2593 &packlock, git_path("packed-refs"),2594 flags, timeout_value) < 0)2595 return -1;2596 /*2597 * Get the current packed-refs while holding the lock. If the2598 * packed-refs file has been modified since we last read it,2599 * this will automatically invalidate the cache and re-read2600 * the packed-refs file.2601 */2602 packed_ref_cache = get_packed_ref_cache(&ref_cache);2603 packed_ref_cache->lock = &packlock;2604 /* Increment the reference count to prevent it from being freed: */2605 acquire_packed_ref_cache(packed_ref_cache);2606 return 0;2607}26082609/*2610 * Write the current version of the packed refs cache from memory to2611 * disk. The packed-refs file must already be locked for writing (see2612 * lock_packed_refs()). Return zero on success. On errors, set errno2613 * and return a nonzero value2614 */2615static int commit_packed_refs(void)2616{2617 struct packed_ref_cache *packed_ref_cache =2618 get_packed_ref_cache(&ref_cache);2619 int error = 0;2620 int save_errno = 0;2621 FILE *out;26222623 if (!packed_ref_cache->lock)2624 die("internal error: packed-refs not locked");26252626 out = fdopen_lock_file(packed_ref_cache->lock, "w");2627 if (!out)2628 die_errno("unable to fdopen packed-refs descriptor");26292630 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);2631 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),2632 0, write_packed_entry_fn, out);26332634 if (commit_lock_file(packed_ref_cache->lock)) {2635 save_errno = errno;2636 error = -1;2637 }2638 packed_ref_cache->lock = NULL;2639 release_packed_ref_cache(packed_ref_cache);2640 errno = save_errno;2641 return error;2642}26432644/*2645 * Rollback the lockfile for the packed-refs file, and discard the2646 * in-memory packed reference cache. (The packed-refs file will be2647 * read anew if it is needed again after this function is called.)2648 */2649static void rollback_packed_refs(void)2650{2651 struct packed_ref_cache *packed_ref_cache =2652 get_packed_ref_cache(&ref_cache);26532654 if (!packed_ref_cache->lock)2655 die("internal error: packed-refs not locked");2656 rollback_lock_file(packed_ref_cache->lock);2657 packed_ref_cache->lock = NULL;2658 release_packed_ref_cache(packed_ref_cache);2659 clear_packed_ref_cache(&ref_cache);2660}26612662struct ref_to_prune {2663 struct ref_to_prune *next;2664 unsigned char sha1[20];2665 char name[FLEX_ARRAY];2666};26672668struct pack_refs_cb_data {2669 unsigned int flags;2670 struct ref_dir *packed_refs;2671 struct ref_to_prune *ref_to_prune;2672};26732674/*2675 * An each_ref_entry_fn that is run over loose references only. If2676 * the loose reference can be packed, add an entry in the packed ref2677 * cache. If the reference should be pruned, also add it to2678 * ref_to_prune in the pack_refs_cb_data.2679 */2680static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)2681{2682 struct pack_refs_cb_data *cb = cb_data;2683 enum peel_status peel_status;2684 struct ref_entry *packed_entry;2685 int is_tag_ref = starts_with(entry->name, "refs/tags/");26862687 /* Do not pack per-worktree refs: */2688 if (ref_type(entry->name) != REF_TYPE_NORMAL)2689 return 0;26902691 /* ALWAYS pack tags */2692 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2693 return 0;26942695 /* Do not pack symbolic or broken refs: */2696 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2697 return 0;26982699 /* Add a packed ref cache entry equivalent to the loose entry. */2700 peel_status = peel_entry(entry, 1);2701 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2702 die("internal error peeling reference %s (%s)",2703 entry->name, oid_to_hex(&entry->u.value.oid));2704 packed_entry = find_ref(cb->packed_refs, entry->name);2705 if (packed_entry) {2706 /* Overwrite existing packed entry with info from loose entry */2707 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2708 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2709 } else {2710 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,2711 REF_ISPACKED | REF_KNOWS_PEELED, 0);2712 add_ref(cb->packed_refs, packed_entry);2713 }2714 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);27152716 /* Schedule the loose reference for pruning if requested. */2717 if ((cb->flags & PACK_REFS_PRUNE)) {2718 int namelen = strlen(entry->name) + 1;2719 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);2720 hashcpy(n->sha1, entry->u.value.oid.hash);2721 memcpy(n->name, entry->name, namelen); /* includes NUL */2722 n->next = cb->ref_to_prune;2723 cb->ref_to_prune = n;2724 }2725 return 0;2726}27272728/*2729 * Remove empty parents, but spare refs/ and immediate subdirs.2730 * Note: munges *name.2731 */2732static void try_remove_empty_parents(char *name)2733{2734 char *p, *q;2735 int i;2736 p = name;2737 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */2738 while (*p && *p != '/')2739 p++;2740 /* tolerate duplicate slashes; see check_refname_format() */2741 while (*p == '/')2742 p++;2743 }2744 for (q = p; *q; q++)2745 ;2746 while (1) {2747 while (q > p && *q != '/')2748 q--;2749 while (q > p && *(q-1) == '/')2750 q--;2751 if (q == p)2752 break;2753 *q = '\0';2754 if (rmdir(git_path("%s", name)))2755 break;2756 }2757}27582759/* make sure nobody touched the ref, and unlink */2760static void prune_ref(struct ref_to_prune *r)2761{2762 struct ref_transaction *transaction;2763 struct strbuf err = STRBUF_INIT;27642765 if (check_refname_format(r->name, 0))2766 return;27672768 transaction = ref_transaction_begin(&err);2769 if (!transaction ||2770 ref_transaction_delete(transaction, r->name, r->sha1,2771 REF_ISPRUNING, NULL, &err) ||2772 ref_transaction_commit(transaction, &err)) {2773 ref_transaction_free(transaction);2774 error("%s", err.buf);2775 strbuf_release(&err);2776 return;2777 }2778 ref_transaction_free(transaction);2779 strbuf_release(&err);2780 try_remove_empty_parents(r->name);2781}27822783static void prune_refs(struct ref_to_prune *r)2784{2785 while (r) {2786 prune_ref(r);2787 r = r->next;2788 }2789}27902791int pack_refs(unsigned int flags)2792{2793 struct pack_refs_cb_data cbdata;27942795 memset(&cbdata, 0, sizeof(cbdata));2796 cbdata.flags = flags;27972798 lock_packed_refs(LOCK_DIE_ON_ERROR);2799 cbdata.packed_refs = get_packed_refs(&ref_cache);28002801 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,2802 pack_if_possible_fn, &cbdata);28032804 if (commit_packed_refs())2805 die_errno("unable to overwrite old ref-pack file");28062807 prune_refs(cbdata.ref_to_prune);2808 return 0;2809}28102811/*2812 * Rewrite the packed-refs file, omitting any refs listed in2813 * 'refnames'. On error, leave packed-refs unchanged, write an error2814 * message to 'err', and return a nonzero value.2815 *2816 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2817 */2818static int repack_without_refs(struct string_list *refnames, struct strbuf *err)2819{2820 struct ref_dir *packed;2821 struct string_list_item *refname;2822 int ret, needs_repacking = 0, removed = 0;28232824 assert(err);28252826 /* Look for a packed ref */2827 for_each_string_list_item(refname, refnames) {2828 if (get_packed_ref(refname->string)) {2829 needs_repacking = 1;2830 break;2831 }2832 }28332834 /* Avoid locking if we have nothing to do */2835 if (!needs_repacking)2836 return 0; /* no refname exists in packed refs */28372838 if (lock_packed_refs(0)) {2839 unable_to_lock_message(git_path("packed-refs"), errno, err);2840 return -1;2841 }2842 packed = get_packed_refs(&ref_cache);28432844 /* Remove refnames from the cache */2845 for_each_string_list_item(refname, refnames)2846 if (remove_entry(packed, refname->string) != -1)2847 removed = 1;2848 if (!removed) {2849 /*2850 * All packed entries disappeared while we were2851 * acquiring the lock.2852 */2853 rollback_packed_refs();2854 return 0;2855 }28562857 /* Write what remains */2858 ret = commit_packed_refs();2859 if (ret)2860 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",2861 strerror(errno));2862 return ret;2863}28642865static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)2866{2867 assert(err);28682869 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2870 /*2871 * loose. The loose file name is the same as the2872 * lockfile name, minus ".lock":2873 */2874 char *loose_filename = get_locked_file_path(lock->lk);2875 int res = unlink_or_msg(loose_filename, err);2876 free(loose_filename);2877 if (res)2878 return 1;2879 }2880 return 0;2881}28822883static int is_per_worktree_ref(const char *refname)2884{2885 return !strcmp(refname, "HEAD") ||2886 starts_with(refname, "refs/bisect/");2887}28882889static int is_pseudoref_syntax(const char *refname)2890{2891 const char *c;28922893 for (c = refname; *c; c++) {2894 if (!isupper(*c) && *c != '-' && *c != '_')2895 return 0;2896 }28972898 return 1;2899}29002901enum ref_type ref_type(const char *refname)2902{2903 if (is_per_worktree_ref(refname))2904 return REF_TYPE_PER_WORKTREE;2905 if (is_pseudoref_syntax(refname))2906 return REF_TYPE_PSEUDOREF;2907 return REF_TYPE_NORMAL;2908}29092910static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,2911 const unsigned char *old_sha1, struct strbuf *err)2912{2913 const char *filename;2914 int fd;2915 static struct lock_file lock;2916 struct strbuf buf = STRBUF_INIT;2917 int ret = -1;29182919 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));29202921 filename = git_path("%s", pseudoref);2922 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2923 if (fd < 0) {2924 strbuf_addf(err, "Could not open '%s' for writing: %s",2925 filename, strerror(errno));2926 return -1;2927 }29282929 if (old_sha1) {2930 unsigned char actual_old_sha1[20];29312932 if (read_ref(pseudoref, actual_old_sha1))2933 die("could not read ref '%s'", pseudoref);2934 if (hashcmp(actual_old_sha1, old_sha1)) {2935 strbuf_addf(err, "Unexpected sha1 when writing %s", pseudoref);2936 rollback_lock_file(&lock);2937 goto done;2938 }2939 }29402941 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {2942 strbuf_addf(err, "Could not write to '%s'", filename);2943 rollback_lock_file(&lock);2944 goto done;2945 }29462947 commit_lock_file(&lock);2948 ret = 0;2949done:2950 strbuf_release(&buf);2951 return ret;2952}29532954static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)2955{2956 static struct lock_file lock;2957 const char *filename;29582959 filename = git_path("%s", pseudoref);29602961 if (old_sha1 && !is_null_sha1(old_sha1)) {2962 int fd;2963 unsigned char actual_old_sha1[20];29642965 fd = hold_lock_file_for_update(&lock, filename,2966 LOCK_DIE_ON_ERROR);2967 if (fd < 0)2968 die_errno(_("Could not open '%s' for writing"), filename);2969 if (read_ref(pseudoref, actual_old_sha1))2970 die("could not read ref '%s'", pseudoref);2971 if (hashcmp(actual_old_sha1, old_sha1)) {2972 warning("Unexpected sha1 when deleting %s", pseudoref);2973 rollback_lock_file(&lock);2974 return -1;2975 }29762977 unlink(filename);2978 rollback_lock_file(&lock);2979 } else {2980 unlink(filename);2981 }29822983 return 0;2984}29852986int delete_ref(const char *refname, const unsigned char *old_sha1,2987 unsigned int flags)2988{2989 struct ref_transaction *transaction;2990 struct strbuf err = STRBUF_INIT;29912992 if (ref_type(refname) == REF_TYPE_PSEUDOREF)2993 return delete_pseudoref(refname, old_sha1);29942995 transaction = ref_transaction_begin(&err);2996 if (!transaction ||2997 ref_transaction_delete(transaction, refname, old_sha1,2998 flags, NULL, &err) ||2999 ref_transaction_commit(transaction, &err)) {3000 error("%s", err.buf);3001 ref_transaction_free(transaction);3002 strbuf_release(&err);3003 return 1;3004 }3005 ref_transaction_free(transaction);3006 strbuf_release(&err);3007 return 0;3008}30093010int delete_refs(struct string_list *refnames)3011{3012 struct strbuf err = STRBUF_INIT;3013 int i, result = 0;30143015 if (!refnames->nr)3016 return 0;30173018 result = repack_without_refs(refnames, &err);3019 if (result) {3020 /*3021 * If we failed to rewrite the packed-refs file, then3022 * it is unsafe to try to remove loose refs, because3023 * doing so might expose an obsolete packed value for3024 * a reference that might even point at an object that3025 * has been garbage collected.3026 */3027 if (refnames->nr == 1)3028 error(_("could not delete reference %s: %s"),3029 refnames->items[0].string, err.buf);3030 else3031 error(_("could not delete references: %s"), err.buf);30323033 goto out;3034 }30353036 for (i = 0; i < refnames->nr; i++) {3037 const char *refname = refnames->items[i].string;30383039 if (delete_ref(refname, NULL, 0))3040 result |= error(_("could not remove reference %s"), refname);3041 }30423043out:3044 strbuf_release(&err);3045 return result;3046}30473048/*3049 * People using contrib's git-new-workdir have .git/logs/refs ->3050 * /some/other/path/.git/logs/refs, and that may live on another device.3051 *3052 * IOW, to avoid cross device rename errors, the temporary renamed log must3053 * live into logs/refs.3054 */3055#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"30563057static int rename_tmp_log(const char *newrefname)3058{3059 int attempts_remaining = 4;3060 struct strbuf path = STRBUF_INIT;3061 int ret = -1;30623063 retry:3064 strbuf_reset(&path);3065 strbuf_git_path(&path, "logs/%s", newrefname);3066 switch (safe_create_leading_directories_const(path.buf)) {3067 case SCLD_OK:3068 break; /* success */3069 case SCLD_VANISHED:3070 if (--attempts_remaining > 0)3071 goto retry;3072 /* fall through */3073 default:3074 error("unable to create directory for %s", newrefname);3075 goto out;3076 }30773078 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {3079 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {3080 /*3081 * rename(a, b) when b is an existing3082 * directory ought to result in ISDIR, but3083 * Solaris 5.8 gives ENOTDIR. Sheesh.3084 */3085 if (remove_empty_directories(&path)) {3086 error("Directory not empty: logs/%s", newrefname);3087 goto out;3088 }3089 goto retry;3090 } else if (errno == ENOENT && --attempts_remaining > 0) {3091 /*3092 * Maybe another process just deleted one of3093 * the directories in the path to newrefname.3094 * Try again from the beginning.3095 */3096 goto retry;3097 } else {3098 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",3099 newrefname, strerror(errno));3100 goto out;3101 }3102 }3103 ret = 0;3104out:3105 strbuf_release(&path);3106 return ret;3107}31083109/*3110 * Return 0 if a reference named refname could be created without3111 * conflicting with the name of an existing reference. Otherwise,3112 * return a negative value and write an explanation to err. If extras3113 * is non-NULL, it is a list of additional refnames with which refname3114 * is not allowed to conflict. If skip is non-NULL, ignore potential3115 * conflicts with refs in skip (e.g., because they are scheduled for3116 * deletion in the same operation). Behavior is undefined if the same3117 * name is listed in both extras and skip.3118 *3119 * Two reference names conflict if one of them exactly matches the3120 * leading components of the other; e.g., "foo/bar" conflicts with3121 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or3122 * "foo/barbados".3123 *3124 * extras and skip must be sorted.3125 */3126static int verify_refname_available(const char *newname,3127 struct string_list *extras,3128 struct string_list *skip,3129 struct strbuf *err)3130{3131 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);3132 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);31333134 if (verify_refname_available_dir(newname, extras, skip,3135 packed_refs, err) ||3136 verify_refname_available_dir(newname, extras, skip,3137 loose_refs, err))3138 return -1;31393140 return 0;3141}31423143static int rename_ref_available(const char *oldname, const char *newname)3144{3145 struct string_list skip = STRING_LIST_INIT_NODUP;3146 struct strbuf err = STRBUF_INIT;3147 int ret;31483149 string_list_insert(&skip, oldname);3150 ret = !verify_refname_available(newname, NULL, &skip, &err);3151 if (!ret)3152 error("%s", err.buf);31533154 string_list_clear(&skip, 0);3155 strbuf_release(&err);3156 return ret;3157}31583159static int write_ref_to_lockfile(struct ref_lock *lock,3160 const unsigned char *sha1, struct strbuf *err);3161static int commit_ref_update(struct ref_lock *lock,3162 const unsigned char *sha1, const char *logmsg,3163 int flags, struct strbuf *err);31643165int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)3166{3167 unsigned char sha1[20], orig_sha1[20];3168 int flag = 0, logmoved = 0;3169 struct ref_lock *lock;3170 struct stat loginfo;3171 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3172 const char *symref = NULL;3173 struct strbuf err = STRBUF_INIT;31743175 if (log && S_ISLNK(loginfo.st_mode))3176 return error("reflog for %s is a symlink", oldrefname);31773178 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3179 orig_sha1, &flag);3180 if (flag & REF_ISSYMREF)3181 return error("refname %s is a symbolic ref, renaming it is not supported",3182 oldrefname);3183 if (!symref)3184 return error("refname %s not found", oldrefname);31853186 if (!rename_ref_available(oldrefname, newrefname))3187 return 1;31883189 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))3190 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",3191 oldrefname, strerror(errno));31923193 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3194 error("unable to delete old %s", oldrefname);3195 goto rollback;3196 }31973198 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3199 delete_ref(newrefname, sha1, REF_NODEREF)) {3200 if (errno==EISDIR) {3201 struct strbuf path = STRBUF_INIT;3202 int result;32033204 strbuf_git_path(&path, "%s", newrefname);3205 result = remove_empty_directories(&path);3206 strbuf_release(&path);32073208 if (result) {3209 error("Directory not empty: %s", newrefname);3210 goto rollback;3211 }3212 } else {3213 error("unable to delete existing %s", newrefname);3214 goto rollback;3215 }3216 }32173218 if (log && rename_tmp_log(newrefname))3219 goto rollback;32203221 logmoved = log;32223223 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);3224 if (!lock) {3225 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);3226 strbuf_release(&err);3227 goto rollback;3228 }3229 hashcpy(lock->old_oid.hash, orig_sha1);32303231 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||3232 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {3233 error("unable to write current sha1 into %s: %s", newrefname, err.buf);3234 strbuf_release(&err);3235 goto rollback;3236 }32373238 return 0;32393240 rollback:3241 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);3242 if (!lock) {3243 error("unable to lock %s for rollback: %s", oldrefname, err.buf);3244 strbuf_release(&err);3245 goto rollbacklog;3246 }32473248 flag = log_all_ref_updates;3249 log_all_ref_updates = 0;3250 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||3251 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {3252 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);3253 strbuf_release(&err);3254 }3255 log_all_ref_updates = flag;32563257 rollbacklog:3258 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))3259 error("unable to restore logfile %s from %s: %s",3260 oldrefname, newrefname, strerror(errno));3261 if (!logmoved && log &&3262 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))3263 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",3264 oldrefname, strerror(errno));32653266 return 1;3267}32683269static int close_ref(struct ref_lock *lock)3270{3271 if (close_lock_file(lock->lk))3272 return -1;3273 return 0;3274}32753276static int commit_ref(struct ref_lock *lock)3277{3278 if (commit_lock_file(lock->lk))3279 return -1;3280 return 0;3281}32823283/*3284 * copy the reflog message msg to buf, which has been allocated sufficiently3285 * large, while cleaning up the whitespaces. Especially, convert LF to space,3286 * because reflog file is one line per entry.3287 */3288static int copy_reflog_msg(char *buf, const char *msg)3289{3290 char *cp = buf;3291 char c;3292 int wasspace = 1;32933294 *cp++ = '\t';3295 while ((c = *msg++)) {3296 if (wasspace && isspace(c))3297 continue;3298 wasspace = isspace(c);3299 if (wasspace)3300 c = ' ';3301 *cp++ = c;3302 }3303 while (buf < cp && isspace(cp[-1]))3304 cp--;3305 *cp++ = '\n';3306 return cp - buf;3307}33083309static int should_autocreate_reflog(const char *refname)3310{3311 if (!log_all_ref_updates)3312 return 0;3313 return starts_with(refname, "refs/heads/") ||3314 starts_with(refname, "refs/remotes/") ||3315 starts_with(refname, "refs/notes/") ||3316 !strcmp(refname, "HEAD");3317}33183319/*3320 * Create a reflog for a ref. If force_create = 0, the reflog will3321 * only be created for certain refs (those for which3322 * should_autocreate_reflog returns non-zero. Otherwise, create it3323 * regardless of the ref name. Fill in *err and return -1 on failure.3324 */3325static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)3326{3327 int logfd, oflags = O_APPEND | O_WRONLY;33283329 strbuf_git_path(logfile, "logs/%s", refname);3330 if (force_create || should_autocreate_reflog(refname)) {3331 if (safe_create_leading_directories(logfile->buf) < 0) {3332 strbuf_addf(err, "unable to create directory for %s: "3333 "%s", logfile->buf, strerror(errno));3334 return -1;3335 }3336 oflags |= O_CREAT;3337 }33383339 logfd = open(logfile->buf, oflags, 0666);3340 if (logfd < 0) {3341 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3342 return 0;33433344 if (errno == EISDIR) {3345 if (remove_empty_directories(logfile)) {3346 strbuf_addf(err, "There are still logs under "3347 "'%s'", logfile->buf);3348 return -1;3349 }3350 logfd = open(logfile->buf, oflags, 0666);3351 }33523353 if (logfd < 0) {3354 strbuf_addf(err, "unable to append to %s: %s",3355 logfile->buf, strerror(errno));3356 return -1;3357 }3358 }33593360 adjust_shared_perm(logfile->buf);3361 close(logfd);3362 return 0;3363}336433653366int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)3367{3368 int ret;3369 struct strbuf sb = STRBUF_INIT;33703371 ret = log_ref_setup(refname, &sb, err, force_create);3372 strbuf_release(&sb);3373 return ret;3374}33753376static int log_ref_write_fd(int fd, const unsigned char *old_sha1,3377 const unsigned char *new_sha1,3378 const char *committer, const char *msg)3379{3380 int msglen, written;3381 unsigned maxlen, len;3382 char *logrec;33833384 msglen = msg ? strlen(msg) : 0;3385 maxlen = strlen(committer) + msglen + 100;3386 logrec = xmalloc(maxlen);3387 len = xsnprintf(logrec, maxlen, "%s %s %s\n",3388 sha1_to_hex(old_sha1),3389 sha1_to_hex(new_sha1),3390 committer);3391 if (msglen)3392 len += copy_reflog_msg(logrec + len - 1, msg) - 1;33933394 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;3395 free(logrec);3396 if (written != len)3397 return -1;33983399 return 0;3400}34013402static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,3403 const unsigned char *new_sha1, const char *msg,3404 struct strbuf *logfile, int flags,3405 struct strbuf *err)3406{3407 int logfd, result, oflags = O_APPEND | O_WRONLY;34083409 if (log_all_ref_updates < 0)3410 log_all_ref_updates = !is_bare_repository();34113412 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);34133414 if (result)3415 return result;34163417 logfd = open(logfile->buf, oflags);3418 if (logfd < 0)3419 return 0;3420 result = log_ref_write_fd(logfd, old_sha1, new_sha1,3421 git_committer_info(0), msg);3422 if (result) {3423 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,3424 strerror(errno));3425 close(logfd);3426 return -1;3427 }3428 if (close(logfd)) {3429 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,3430 strerror(errno));3431 return -1;3432 }3433 return 0;3434}34353436static int log_ref_write(const char *refname, const unsigned char *old_sha1,3437 const unsigned char *new_sha1, const char *msg,3438 int flags, struct strbuf *err)3439{3440 struct strbuf sb = STRBUF_INIT;3441 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3442 err);3443 strbuf_release(&sb);3444 return ret;3445}34463447int is_branch(const char *refname)3448{3449 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");3450}34513452/*3453 * Write sha1 into the open lockfile, then close the lockfile. On3454 * errors, rollback the lockfile, fill in *err and3455 * return -1.3456 */3457static int write_ref_to_lockfile(struct ref_lock *lock,3458 const unsigned char *sha1, struct strbuf *err)3459{3460 static char term = '\n';3461 struct object *o;3462 int fd;34633464 o = parse_object(sha1);3465 if (!o) {3466 strbuf_addf(err,3467 "Trying to write ref %s with nonexistent object %s",3468 lock->ref_name, sha1_to_hex(sha1));3469 unlock_ref(lock);3470 return -1;3471 }3472 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {3473 strbuf_addf(err,3474 "Trying to write non-commit object %s to branch %s",3475 sha1_to_hex(sha1), lock->ref_name);3476 unlock_ref(lock);3477 return -1;3478 }3479 fd = get_lock_file_fd(lock->lk);3480 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||3481 write_in_full(fd, &term, 1) != 1 ||3482 close_ref(lock) < 0) {3483 strbuf_addf(err,3484 "Couldn't write %s", get_lock_file_path(lock->lk));3485 unlock_ref(lock);3486 return -1;3487 }3488 return 0;3489}34903491/*3492 * Commit a change to a loose reference that has already been written3493 * to the loose reference lockfile. Also update the reflogs if3494 * necessary, using the specified lockmsg (which can be NULL).3495 */3496static int commit_ref_update(struct ref_lock *lock,3497 const unsigned char *sha1, const char *logmsg,3498 int flags, struct strbuf *err)3499{3500 clear_loose_ref_cache(&ref_cache);3501 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||3502 (strcmp(lock->ref_name, lock->orig_ref_name) &&3503 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {3504 char *old_msg = strbuf_detach(err, NULL);3505 strbuf_addf(err, "Cannot update the ref '%s': %s",3506 lock->ref_name, old_msg);3507 free(old_msg);3508 unlock_ref(lock);3509 return -1;3510 }3511 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {3512 /*3513 * Special hack: If a branch is updated directly and HEAD3514 * points to it (may happen on the remote side of a push3515 * for example) then logically the HEAD reflog should be3516 * updated too.3517 * A generic solution implies reverse symref information,3518 * but finding all symrefs pointing to the given branch3519 * would be rather costly for this rare event (the direct3520 * update of a branch) to be worth it. So let's cheat and3521 * check with HEAD only which should cover 99% of all usage3522 * scenarios (even 100% of the default ones).3523 */3524 unsigned char head_sha1[20];3525 int head_flag;3526 const char *head_ref;3527 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3528 head_sha1, &head_flag);3529 if (head_ref && (head_flag & REF_ISSYMREF) &&3530 !strcmp(head_ref, lock->ref_name)) {3531 struct strbuf log_err = STRBUF_INIT;3532 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,3533 logmsg, 0, &log_err)) {3534 error("%s", log_err.buf);3535 strbuf_release(&log_err);3536 }3537 }3538 }3539 if (commit_ref(lock)) {3540 error("Couldn't set %s", lock->ref_name);3541 unlock_ref(lock);3542 return -1;3543 }35443545 unlock_ref(lock);3546 return 0;3547}35483549int create_symref(const char *ref_target, const char *refs_heads_master,3550 const char *logmsg)3551{3552 char *lockpath = NULL;3553 char ref[1000];3554 int fd, len, written;3555 char *git_HEAD = git_pathdup("%s", ref_target);3556 unsigned char old_sha1[20], new_sha1[20];3557 struct strbuf err = STRBUF_INIT;35583559 if (logmsg && read_ref(ref_target, old_sha1))3560 hashclr(old_sha1);35613562 if (safe_create_leading_directories(git_HEAD) < 0)3563 return error("unable to create directory for %s", git_HEAD);35643565#ifndef NO_SYMLINK_HEAD3566 if (prefer_symlink_refs) {3567 unlink(git_HEAD);3568 if (!symlink(refs_heads_master, git_HEAD))3569 goto done;3570 fprintf(stderr, "no symlink - falling back to symbolic ref\n");3571 }3572#endif35733574 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);3575 if (sizeof(ref) <= len) {3576 error("refname too long: %s", refs_heads_master);3577 goto error_free_return;3578 }3579 lockpath = mkpathdup("%s.lock", git_HEAD);3580 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);3581 if (fd < 0) {3582 error("Unable to open %s for writing", lockpath);3583 goto error_free_return;3584 }3585 written = write_in_full(fd, ref, len);3586 if (close(fd) != 0 || written != len) {3587 error("Unable to write to %s", lockpath);3588 goto error_unlink_return;3589 }3590 if (rename(lockpath, git_HEAD) < 0) {3591 error("Unable to create %s", git_HEAD);3592 goto error_unlink_return;3593 }3594 if (adjust_shared_perm(git_HEAD)) {3595 error("Unable to fix permissions on %s", lockpath);3596 error_unlink_return:3597 unlink_or_warn(lockpath);3598 error_free_return:3599 free(lockpath);3600 free(git_HEAD);3601 return -1;3602 }3603 free(lockpath);36043605#ifndef NO_SYMLINK_HEAD3606 done:3607#endif3608 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&3609 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {3610 error("%s", err.buf);3611 strbuf_release(&err);3612 }36133614 free(git_HEAD);3615 return 0;3616}36173618struct read_ref_at_cb {3619 const char *refname;3620 unsigned long at_time;3621 int cnt;3622 int reccnt;3623 unsigned char *sha1;3624 int found_it;36253626 unsigned char osha1[20];3627 unsigned char nsha1[20];3628 int tz;3629 unsigned long date;3630 char **msg;3631 unsigned long *cutoff_time;3632 int *cutoff_tz;3633 int *cutoff_cnt;3634};36353636static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,3637 const char *email, unsigned long timestamp, int tz,3638 const char *message, void *cb_data)3639{3640 struct read_ref_at_cb *cb = cb_data;36413642 cb->reccnt++;3643 cb->tz = tz;3644 cb->date = timestamp;36453646 if (timestamp <= cb->at_time || cb->cnt == 0) {3647 if (cb->msg)3648 *cb->msg = xstrdup(message);3649 if (cb->cutoff_time)3650 *cb->cutoff_time = timestamp;3651 if (cb->cutoff_tz)3652 *cb->cutoff_tz = tz;3653 if (cb->cutoff_cnt)3654 *cb->cutoff_cnt = cb->reccnt - 1;3655 /*3656 * we have not yet updated cb->[n|o]sha1 so they still3657 * hold the values for the previous record.3658 */3659 if (!is_null_sha1(cb->osha1)) {3660 hashcpy(cb->sha1, nsha1);3661 if (hashcmp(cb->osha1, nsha1))3662 warning("Log for ref %s has gap after %s.",3663 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));3664 }3665 else if (cb->date == cb->at_time)3666 hashcpy(cb->sha1, nsha1);3667 else if (hashcmp(nsha1, cb->sha1))3668 warning("Log for ref %s unexpectedly ended on %s.",3669 cb->refname, show_date(cb->date, cb->tz,3670 DATE_MODE(RFC2822)));3671 hashcpy(cb->osha1, osha1);3672 hashcpy(cb->nsha1, nsha1);3673 cb->found_it = 1;3674 return 1;3675 }3676 hashcpy(cb->osha1, osha1);3677 hashcpy(cb->nsha1, nsha1);3678 if (cb->cnt > 0)3679 cb->cnt--;3680 return 0;3681}36823683static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,3684 const char *email, unsigned long timestamp,3685 int tz, const char *message, void *cb_data)3686{3687 struct read_ref_at_cb *cb = cb_data;36883689 if (cb->msg)3690 *cb->msg = xstrdup(message);3691 if (cb->cutoff_time)3692 *cb->cutoff_time = timestamp;3693 if (cb->cutoff_tz)3694 *cb->cutoff_tz = tz;3695 if (cb->cutoff_cnt)3696 *cb->cutoff_cnt = cb->reccnt;3697 hashcpy(cb->sha1, osha1);3698 if (is_null_sha1(cb->sha1))3699 hashcpy(cb->sha1, nsha1);3700 /* We just want the first entry */3701 return 1;3702}37033704int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,3705 unsigned char *sha1, char **msg,3706 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)3707{3708 struct read_ref_at_cb cb;37093710 memset(&cb, 0, sizeof(cb));3711 cb.refname = refname;3712 cb.at_time = at_time;3713 cb.cnt = cnt;3714 cb.msg = msg;3715 cb.cutoff_time = cutoff_time;3716 cb.cutoff_tz = cutoff_tz;3717 cb.cutoff_cnt = cutoff_cnt;3718 cb.sha1 = sha1;37193720 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);37213722 if (!cb.reccnt) {3723 if (flags & GET_SHA1_QUIETLY)3724 exit(128);3725 else3726 die("Log for %s is empty.", refname);3727 }3728 if (cb.found_it)3729 return 0;37303731 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);37323733 return 1;3734}37353736int reflog_exists(const char *refname)3737{3738 struct stat st;37393740 return !lstat(git_path("logs/%s", refname), &st) &&3741 S_ISREG(st.st_mode);3742}37433744int delete_reflog(const char *refname)3745{3746 return remove_path(git_path("logs/%s", refname));3747}37483749static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)3750{3751 unsigned char osha1[20], nsha1[20];3752 char *email_end, *message;3753 unsigned long timestamp;3754 int tz;37553756 /* old SP new SP name <email> SP time TAB msg LF */3757 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||3758 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||3759 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||3760 !(email_end = strchr(sb->buf + 82, '>')) ||3761 email_end[1] != ' ' ||3762 !(timestamp = strtoul(email_end + 2, &message, 10)) ||3763 !message || message[0] != ' ' ||3764 (message[1] != '+' && message[1] != '-') ||3765 !isdigit(message[2]) || !isdigit(message[3]) ||3766 !isdigit(message[4]) || !isdigit(message[5]))3767 return 0; /* corrupt? */3768 email_end[1] = '\0';3769 tz = strtol(message + 1, NULL, 10);3770 if (message[6] != '\t')3771 message += 6;3772 else3773 message += 7;3774 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);3775}37763777static char *find_beginning_of_line(char *bob, char *scan)3778{3779 while (bob < scan && *(--scan) != '\n')3780 ; /* keep scanning backwards */3781 /*3782 * Return either beginning of the buffer, or LF at the end of3783 * the previous line.3784 */3785 return scan;3786}37873788int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)3789{3790 struct strbuf sb = STRBUF_INIT;3791 FILE *logfp;3792 long pos;3793 int ret = 0, at_tail = 1;37943795 logfp = fopen(git_path("logs/%s", refname), "r");3796 if (!logfp)3797 return -1;37983799 /* Jump to the end */3800 if (fseek(logfp, 0, SEEK_END) < 0)3801 return error("cannot seek back reflog for %s: %s",3802 refname, strerror(errno));3803 pos = ftell(logfp);3804 while (!ret && 0 < pos) {3805 int cnt;3806 size_t nread;3807 char buf[BUFSIZ];3808 char *endp, *scanp;38093810 /* Fill next block from the end */3811 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;3812 if (fseek(logfp, pos - cnt, SEEK_SET))3813 return error("cannot seek back reflog for %s: %s",3814 refname, strerror(errno));3815 nread = fread(buf, cnt, 1, logfp);3816 if (nread != 1)3817 return error("cannot read %d bytes from reflog for %s: %s",3818 cnt, refname, strerror(errno));3819 pos -= cnt;38203821 scanp = endp = buf + cnt;3822 if (at_tail && scanp[-1] == '\n')3823 /* Looking at the final LF at the end of the file */3824 scanp--;3825 at_tail = 0;38263827 while (buf < scanp) {3828 /*3829 * terminating LF of the previous line, or the beginning3830 * of the buffer.3831 */3832 char *bp;38333834 bp = find_beginning_of_line(buf, scanp);38353836 if (*bp == '\n') {3837 /*3838 * The newline is the end of the previous line,3839 * so we know we have complete line starting3840 * at (bp + 1). Prefix it onto any prior data3841 * we collected for the line and process it.3842 */3843 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));3844 scanp = bp;3845 endp = bp + 1;3846 ret = show_one_reflog_ent(&sb, fn, cb_data);3847 strbuf_reset(&sb);3848 if (ret)3849 break;3850 } else if (!pos) {3851 /*3852 * We are at the start of the buffer, and the3853 * start of the file; there is no previous3854 * line, and we have everything for this one.3855 * Process it, and we can end the loop.3856 */3857 strbuf_splice(&sb, 0, 0, buf, endp - buf);3858 ret = show_one_reflog_ent(&sb, fn, cb_data);3859 strbuf_reset(&sb);3860 break;3861 }38623863 if (bp == buf) {3864 /*3865 * We are at the start of the buffer, and there3866 * is more file to read backwards. Which means3867 * we are in the middle of a line. Note that we3868 * may get here even if *bp was a newline; that3869 * just means we are at the exact end of the3870 * previous line, rather than some spot in the3871 * middle.3872 *3873 * Save away what we have to be combined with3874 * the data from the next read.3875 */3876 strbuf_splice(&sb, 0, 0, buf, endp - buf);3877 break;3878 }3879 }38803881 }3882 if (!ret && sb.len)3883 die("BUG: reverse reflog parser had leftover data");38843885 fclose(logfp);3886 strbuf_release(&sb);3887 return ret;3888}38893890int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)3891{3892 FILE *logfp;3893 struct strbuf sb = STRBUF_INIT;3894 int ret = 0;38953896 logfp = fopen(git_path("logs/%s", refname), "r");3897 if (!logfp)3898 return -1;38993900 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))3901 ret = show_one_reflog_ent(&sb, fn, cb_data);3902 fclose(logfp);3903 strbuf_release(&sb);3904 return ret;3905}3906/*3907 * Call fn for each reflog in the namespace indicated by name. name3908 * must be empty or end with '/'. Name will be used as a scratch3909 * space, but its contents will be restored before return.3910 */3911static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)3912{3913 DIR *d = opendir(git_path("logs/%s", name->buf));3914 int retval = 0;3915 struct dirent *de;3916 int oldlen = name->len;39173918 if (!d)3919 return name->len ? errno : 0;39203921 while ((de = readdir(d)) != NULL) {3922 struct stat st;39233924 if (de->d_name[0] == '.')3925 continue;3926 if (ends_with(de->d_name, ".lock"))3927 continue;3928 strbuf_addstr(name, de->d_name);3929 if (stat(git_path("logs/%s", name->buf), &st) < 0) {3930 ; /* silently ignore */3931 } else {3932 if (S_ISDIR(st.st_mode)) {3933 strbuf_addch(name, '/');3934 retval = do_for_each_reflog(name, fn, cb_data);3935 } else {3936 struct object_id oid;39373938 if (read_ref_full(name->buf, 0, oid.hash, NULL))3939 retval = error("bad ref for %s", name->buf);3940 else3941 retval = fn(name->buf, &oid, 0, cb_data);3942 }3943 if (retval)3944 break;3945 }3946 strbuf_setlen(name, oldlen);3947 }3948 closedir(d);3949 return retval;3950}39513952int for_each_reflog(each_ref_fn fn, void *cb_data)3953{3954 int retval;3955 struct strbuf name;3956 strbuf_init(&name, PATH_MAX);3957 retval = do_for_each_reflog(&name, fn, cb_data);3958 strbuf_release(&name);3959 return retval;3960}39613962/**3963 * Information needed for a single ref update. Set new_sha1 to the new3964 * value or to null_sha1 to delete the ref. To check the old value3965 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3966 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3967 * not exist before update.3968 */3969struct ref_update {3970 /*3971 * If (flags & REF_HAVE_NEW), set the reference to this value:3972 */3973 unsigned char new_sha1[20];3974 /*3975 * If (flags & REF_HAVE_OLD), check that the reference3976 * previously had this value:3977 */3978 unsigned char old_sha1[20];3979 /*3980 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3981 * REF_DELETING, and REF_ISPRUNING:3982 */3983 unsigned int flags;3984 struct ref_lock *lock;3985 int type;3986 char *msg;3987 const char refname[FLEX_ARRAY];3988};39893990/*3991 * Transaction states.3992 * OPEN: The transaction is in a valid state and can accept new updates.3993 * An OPEN transaction can be committed.3994 * CLOSED: A closed transaction is no longer active and no other operations3995 * than free can be used on it in this state.3996 * A transaction can either become closed by successfully committing3997 * an active transaction or if there is a failure while building3998 * the transaction thus rendering it failed/inactive.3999 */4000enum ref_transaction_state {4001 REF_TRANSACTION_OPEN = 0,4002 REF_TRANSACTION_CLOSED = 14003};40044005/*4006 * Data structure for holding a reference transaction, which can4007 * consist of checks and updates to multiple references, carried out4008 * as atomically as possible. This structure is opaque to callers.4009 */4010struct ref_transaction {4011 struct ref_update **updates;4012 size_t alloc;4013 size_t nr;4014 enum ref_transaction_state state;4015};40164017struct ref_transaction *ref_transaction_begin(struct strbuf *err)4018{4019 assert(err);40204021 return xcalloc(1, sizeof(struct ref_transaction));4022}40234024void ref_transaction_free(struct ref_transaction *transaction)4025{4026 int i;40274028 if (!transaction)4029 return;40304031 for (i = 0; i < transaction->nr; i++) {4032 free(transaction->updates[i]->msg);4033 free(transaction->updates[i]);4034 }4035 free(transaction->updates);4036 free(transaction);4037}40384039static struct ref_update *add_update(struct ref_transaction *transaction,4040 const char *refname)4041{4042 size_t len = strlen(refname) + 1;4043 struct ref_update *update = xcalloc(1, sizeof(*update) + len);40444045 memcpy((char *)update->refname, refname, len); /* includes NUL */4046 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);4047 transaction->updates[transaction->nr++] = update;4048 return update;4049}40504051int ref_transaction_update(struct ref_transaction *transaction,4052 const char *refname,4053 const unsigned char *new_sha1,4054 const unsigned char *old_sha1,4055 unsigned int flags, const char *msg,4056 struct strbuf *err)4057{4058 struct ref_update *update;40594060 assert(err);40614062 if (transaction->state != REF_TRANSACTION_OPEN)4063 die("BUG: update called for transaction that is not open");40644065 if (new_sha1 && !is_null_sha1(new_sha1) &&4066 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {4067 strbuf_addf(err, "refusing to update ref with bad name %s",4068 refname);4069 return -1;4070 }40714072 update = add_update(transaction, refname);4073 if (new_sha1) {4074 hashcpy(update->new_sha1, new_sha1);4075 flags |= REF_HAVE_NEW;4076 }4077 if (old_sha1) {4078 hashcpy(update->old_sha1, old_sha1);4079 flags |= REF_HAVE_OLD;4080 }4081 update->flags = flags;4082 if (msg)4083 update->msg = xstrdup(msg);4084 return 0;4085}40864087int ref_transaction_create(struct ref_transaction *transaction,4088 const char *refname,4089 const unsigned char *new_sha1,4090 unsigned int flags, const char *msg,4091 struct strbuf *err)4092{4093 if (!new_sha1 || is_null_sha1(new_sha1))4094 die("BUG: create called without valid new_sha1");4095 return ref_transaction_update(transaction, refname, new_sha1,4096 null_sha1, flags, msg, err);4097}40984099int ref_transaction_delete(struct ref_transaction *transaction,4100 const char *refname,4101 const unsigned char *old_sha1,4102 unsigned int flags, const char *msg,4103 struct strbuf *err)4104{4105 if (old_sha1 && is_null_sha1(old_sha1))4106 die("BUG: delete called with old_sha1 set to zeros");4107 return ref_transaction_update(transaction, refname,4108 null_sha1, old_sha1,4109 flags, msg, err);4110}41114112int ref_transaction_verify(struct ref_transaction *transaction,4113 const char *refname,4114 const unsigned char *old_sha1,4115 unsigned int flags,4116 struct strbuf *err)4117{4118 if (!old_sha1)4119 die("BUG: verify called with old_sha1 set to NULL");4120 return ref_transaction_update(transaction, refname,4121 NULL, old_sha1,4122 flags, NULL, err);4123}41244125int update_ref(const char *msg, const char *refname,4126 const unsigned char *new_sha1, const unsigned char *old_sha1,4127 unsigned int flags, enum action_on_err onerr)4128{4129 struct ref_transaction *t = NULL;4130 struct strbuf err = STRBUF_INIT;4131 int ret = 0;41324133 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {4134 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);4135 } else {4136 t = ref_transaction_begin(&err);4137 if (!t ||4138 ref_transaction_update(t, refname, new_sha1, old_sha1,4139 flags, msg, &err) ||4140 ref_transaction_commit(t, &err)) {4141 ret = 1;4142 ref_transaction_free(t);4143 }4144 }4145 if (ret) {4146 const char *str = "update_ref failed for ref '%s': %s";41474148 switch (onerr) {4149 case UPDATE_REFS_MSG_ON_ERR:4150 error(str, refname, err.buf);4151 break;4152 case UPDATE_REFS_DIE_ON_ERR:4153 die(str, refname, err.buf);4154 break;4155 case UPDATE_REFS_QUIET_ON_ERR:4156 break;4157 }4158 strbuf_release(&err);4159 return 1;4160 }4161 strbuf_release(&err);4162 if (t)4163 ref_transaction_free(t);4164 return 0;4165}41664167static int ref_update_reject_duplicates(struct string_list *refnames,4168 struct strbuf *err)4169{4170 int i, n = refnames->nr;41714172 assert(err);41734174 for (i = 1; i < n; i++)4175 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {4176 strbuf_addf(err,4177 "Multiple updates for ref '%s' not allowed.",4178 refnames->items[i].string);4179 return 1;4180 }4181 return 0;4182}41834184int ref_transaction_commit(struct ref_transaction *transaction,4185 struct strbuf *err)4186{4187 int ret = 0, i;4188 int n = transaction->nr;4189 struct ref_update **updates = transaction->updates;4190 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4191 struct string_list_item *ref_to_delete;4192 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41934194 assert(err);41954196 if (transaction->state != REF_TRANSACTION_OPEN)4197 die("BUG: commit called for transaction that is not open");41984199 if (!n) {4200 transaction->state = REF_TRANSACTION_CLOSED;4201 return 0;4202 }42034204 /* Fail if a refname appears more than once in the transaction: */4205 for (i = 0; i < n; i++)4206 string_list_append(&affected_refnames, updates[i]->refname);4207 string_list_sort(&affected_refnames);4208 if (ref_update_reject_duplicates(&affected_refnames, err)) {4209 ret = TRANSACTION_GENERIC_ERROR;4210 goto cleanup;4211 }42124213 /*4214 * Acquire all locks, verify old values if provided, check4215 * that new values are valid, and write new values to the4216 * lockfiles, ready to be activated. Only keep one lockfile4217 * open at a time to avoid running out of file descriptors.4218 */4219 for (i = 0; i < n; i++) {4220 struct ref_update *update = updates[i];42214222 if ((update->flags & REF_HAVE_NEW) &&4223 is_null_sha1(update->new_sha1))4224 update->flags |= REF_DELETING;4225 update->lock = lock_ref_sha1_basic(4226 update->refname,4227 ((update->flags & REF_HAVE_OLD) ?4228 update->old_sha1 : NULL),4229 &affected_refnames, NULL,4230 update->flags,4231 &update->type,4232 err);4233 if (!update->lock) {4234 char *reason;42354236 ret = (errno == ENOTDIR)4237 ? TRANSACTION_NAME_CONFLICT4238 : TRANSACTION_GENERIC_ERROR;4239 reason = strbuf_detach(err, NULL);4240 strbuf_addf(err, "cannot lock ref '%s': %s",4241 update->refname, reason);4242 free(reason);4243 goto cleanup;4244 }4245 if ((update->flags & REF_HAVE_NEW) &&4246 !(update->flags & REF_DELETING)) {4247 int overwriting_symref = ((update->type & REF_ISSYMREF) &&4248 (update->flags & REF_NODEREF));42494250 if (!overwriting_symref &&4251 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4252 /*4253 * The reference already has the desired4254 * value, so we don't need to write it.4255 */4256 } else if (write_ref_to_lockfile(update->lock,4257 update->new_sha1,4258 err)) {4259 char *write_err = strbuf_detach(err, NULL);42604261 /*4262 * The lock was freed upon failure of4263 * write_ref_to_lockfile():4264 */4265 update->lock = NULL;4266 strbuf_addf(err,4267 "cannot update the ref '%s': %s",4268 update->refname, write_err);4269 free(write_err);4270 ret = TRANSACTION_GENERIC_ERROR;4271 goto cleanup;4272 } else {4273 update->flags |= REF_NEEDS_COMMIT;4274 }4275 }4276 if (!(update->flags & REF_NEEDS_COMMIT)) {4277 /*4278 * We didn't have to write anything to the lockfile.4279 * Close it to free up the file descriptor:4280 */4281 if (close_ref(update->lock)) {4282 strbuf_addf(err, "Couldn't close %s.lock",4283 update->refname);4284 goto cleanup;4285 }4286 }4287 }42884289 /* Perform updates first so live commits remain referenced */4290 for (i = 0; i < n; i++) {4291 struct ref_update *update = updates[i];42924293 if (update->flags & REF_NEEDS_COMMIT) {4294 if (commit_ref_update(update->lock,4295 update->new_sha1, update->msg,4296 update->flags, err)) {4297 /* freed by commit_ref_update(): */4298 update->lock = NULL;4299 ret = TRANSACTION_GENERIC_ERROR;4300 goto cleanup;4301 } else {4302 /* freed by commit_ref_update(): */4303 update->lock = NULL;4304 }4305 }4306 }43074308 /* Perform deletes now that updates are safely completed */4309 for (i = 0; i < n; i++) {4310 struct ref_update *update = updates[i];43114312 if (update->flags & REF_DELETING) {4313 if (delete_ref_loose(update->lock, update->type, err)) {4314 ret = TRANSACTION_GENERIC_ERROR;4315 goto cleanup;4316 }43174318 if (!(update->flags & REF_ISPRUNING))4319 string_list_append(&refs_to_delete,4320 update->lock->ref_name);4321 }4322 }43234324 if (repack_without_refs(&refs_to_delete, err)) {4325 ret = TRANSACTION_GENERIC_ERROR;4326 goto cleanup;4327 }4328 for_each_string_list_item(ref_to_delete, &refs_to_delete)4329 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4330 clear_loose_ref_cache(&ref_cache);43314332cleanup:4333 transaction->state = REF_TRANSACTION_CLOSED;43344335 for (i = 0; i < n; i++)4336 if (updates[i]->lock)4337 unlock_ref(updates[i]->lock);4338 string_list_clear(&refs_to_delete, 0);4339 string_list_clear(&affected_refnames, 0);4340 return ret;4341}43424343static int ref_present(const char *refname,4344 const struct object_id *oid, int flags, void *cb_data)4345{4346 struct string_list *affected_refnames = cb_data;43474348 return string_list_has_string(affected_refnames, refname);4349}43504351int initial_ref_transaction_commit(struct ref_transaction *transaction,4352 struct strbuf *err)4353{4354 int ret = 0, i;4355 int n = transaction->nr;4356 struct ref_update **updates = transaction->updates;4357 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;43584359 assert(err);43604361 if (transaction->state != REF_TRANSACTION_OPEN)4362 die("BUG: commit called for transaction that is not open");43634364 /* Fail if a refname appears more than once in the transaction: */4365 for (i = 0; i < n; i++)4366 string_list_append(&affected_refnames, updates[i]->refname);4367 string_list_sort(&affected_refnames);4368 if (ref_update_reject_duplicates(&affected_refnames, err)) {4369 ret = TRANSACTION_GENERIC_ERROR;4370 goto cleanup;4371 }43724373 /*4374 * It's really undefined to call this function in an active4375 * repository or when there are existing references: we are4376 * only locking and changing packed-refs, so (1) any4377 * simultaneous processes might try to change a reference at4378 * the same time we do, and (2) any existing loose versions of4379 * the references that we are setting would have precedence4380 * over our values. But some remote helpers create the remote4381 * "HEAD" and "master" branches before calling this function,4382 * so here we really only check that none of the references4383 * that we are creating already exists.4384 */4385 if (for_each_rawref(ref_present, &affected_refnames))4386 die("BUG: initial ref transaction called with existing refs");43874388 for (i = 0; i < n; i++) {4389 struct ref_update *update = updates[i];43904391 if ((update->flags & REF_HAVE_OLD) &&4392 !is_null_sha1(update->old_sha1))4393 die("BUG: initial ref transaction with old_sha1 set");4394 if (verify_refname_available(update->refname,4395 &affected_refnames, NULL,4396 err)) {4397 ret = TRANSACTION_NAME_CONFLICT;4398 goto cleanup;4399 }4400 }44014402 if (lock_packed_refs(0)) {4403 strbuf_addf(err, "unable to lock packed-refs file: %s",4404 strerror(errno));4405 ret = TRANSACTION_GENERIC_ERROR;4406 goto cleanup;4407 }44084409 for (i = 0; i < n; i++) {4410 struct ref_update *update = updates[i];44114412 if ((update->flags & REF_HAVE_NEW) &&4413 !is_null_sha1(update->new_sha1))4414 add_packed_ref(update->refname, update->new_sha1);4415 }44164417 if (commit_packed_refs()) {4418 strbuf_addf(err, "unable to commit packed-refs file: %s",4419 strerror(errno));4420 ret = TRANSACTION_GENERIC_ERROR;4421 goto cleanup;4422 }44234424cleanup:4425 transaction->state = REF_TRANSACTION_CLOSED;4426 string_list_clear(&affected_refnames, 0);4427 return ret;4428}44294430char *shorten_unambiguous_ref(const char *refname, int strict)4431{4432 int i;4433 static char **scanf_fmts;4434 static int nr_rules;4435 char *short_name;44364437 if (!nr_rules) {4438 /*4439 * Pre-generate scanf formats from ref_rev_parse_rules[].4440 * Generate a format suitable for scanf from a4441 * ref_rev_parse_rules rule by interpolating "%s" at the4442 * location of the "%.*s".4443 */4444 size_t total_len = 0;4445 size_t offset = 0;44464447 /* the rule list is NULL terminated, count them first */4448 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)4449 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4450 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;44514452 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);44534454 offset = 0;4455 for (i = 0; i < nr_rules; i++) {4456 assert(offset < total_len);4457 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;4458 offset += snprintf(scanf_fmts[i], total_len - offset,4459 ref_rev_parse_rules[i], 2, "%s") + 1;4460 }4461 }44624463 /* bail out if there are no rules */4464 if (!nr_rules)4465 return xstrdup(refname);44664467 /* buffer for scanf result, at most refname must fit */4468 short_name = xstrdup(refname);44694470 /* skip first rule, it will always match */4471 for (i = nr_rules - 1; i > 0 ; --i) {4472 int j;4473 int rules_to_fail = i;4474 int short_name_len;44754476 if (1 != sscanf(refname, scanf_fmts[i], short_name))4477 continue;44784479 short_name_len = strlen(short_name);44804481 /*4482 * in strict mode, all (except the matched one) rules4483 * must fail to resolve to a valid non-ambiguous ref4484 */4485 if (strict)4486 rules_to_fail = nr_rules;44874488 /*4489 * check if the short name resolves to a valid ref,4490 * but use only rules prior to the matched one4491 */4492 for (j = 0; j < rules_to_fail; j++) {4493 const char *rule = ref_rev_parse_rules[j];4494 char refname[PATH_MAX];44954496 /* skip matched rule */4497 if (i == j)4498 continue;44994500 /*4501 * the short name is ambiguous, if it resolves4502 * (with this previous rule) to a valid ref4503 * read_ref() returns 0 on success4504 */4505 mksnpath(refname, sizeof(refname),4506 rule, short_name_len, short_name);4507 if (ref_exists(refname))4508 break;4509 }45104511 /*4512 * short name is non-ambiguous if all previous rules4513 * haven't resolved to a valid ref4514 */4515 if (j == rules_to_fail)4516 return short_name;4517 }45184519 free(short_name);4520 return xstrdup(refname);4521}45224523static struct string_list *hide_refs;45244525int parse_hide_refs_config(const char *var, const char *value, const char *section)4526{4527 if (!strcmp("transfer.hiderefs", var) ||4528 /* NEEDSWORK: use parse_config_key() once both are merged */4529 (starts_with(var, section) && var[strlen(section)] == '.' &&4530 !strcmp(var + strlen(section), ".hiderefs"))) {4531 char *ref;4532 int len;45334534 if (!value)4535 return config_error_nonbool(var);4536 ref = xstrdup(value);4537 len = strlen(ref);4538 while (len && ref[len - 1] == '/')4539 ref[--len] = '\0';4540 if (!hide_refs) {4541 hide_refs = xcalloc(1, sizeof(*hide_refs));4542 hide_refs->strdup_strings = 1;4543 }4544 string_list_append(hide_refs, ref);4545 }4546 return 0;4547}45484549int ref_is_hidden(const char *refname)4550{4551 int i;45524553 if (!hide_refs)4554 return 0;4555 for (i = hide_refs->nr - 1; i >= 0; i--) {4556 const char *match = hide_refs->items[i].string;4557 int neg = 0;4558 int len;45594560 if (*match == '!') {4561 neg = 1;4562 match++;4563 }45644565 if (!starts_with(refname, match))4566 continue;4567 len = strlen(match);4568 if (!refname[len] || refname[len] == '/')4569 return !neg;4570 }4571 return 0;4572}45734574struct expire_reflog_cb {4575 unsigned int flags;4576 reflog_expiry_should_prune_fn *should_prune_fn;4577 void *policy_cb;4578 FILE *newlog;4579 unsigned char last_kept_sha1[20];4580};45814582static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,4583 const char *email, unsigned long timestamp, int tz,4584 const char *message, void *cb_data)4585{4586 struct expire_reflog_cb *cb = cb_data;4587 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;45884589 if (cb->flags & EXPIRE_REFLOGS_REWRITE)4590 osha1 = cb->last_kept_sha1;45914592 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4593 message, policy_cb)) {4594 if (!cb->newlog)4595 printf("would prune %s", message);4596 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)4597 printf("prune %s", message);4598 } else {4599 if (cb->newlog) {4600 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",4601 sha1_to_hex(osha1), sha1_to_hex(nsha1),4602 email, timestamp, tz, message);4603 hashcpy(cb->last_kept_sha1, nsha1);4604 }4605 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)4606 printf("keep %s", message);4607 }4608 return 0;4609}46104611int reflog_expire(const char *refname, const unsigned char *sha1,4612 unsigned int flags,4613 reflog_expiry_prepare_fn prepare_fn,4614 reflog_expiry_should_prune_fn should_prune_fn,4615 reflog_expiry_cleanup_fn cleanup_fn,4616 void *policy_cb_data)4617{4618 static struct lock_file reflog_lock;4619 struct expire_reflog_cb cb;4620 struct ref_lock *lock;4621 char *log_file;4622 int status = 0;4623 int type;4624 struct strbuf err = STRBUF_INIT;46254626 memset(&cb, 0, sizeof(cb));4627 cb.flags = flags;4628 cb.policy_cb = policy_cb_data;4629 cb.should_prune_fn = should_prune_fn;46304631 /*4632 * The reflog file is locked by holding the lock on the4633 * reference itself, plus we might need to update the4634 * reference if --updateref was specified:4635 */4636 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);4637 if (!lock) {4638 error("cannot lock ref '%s': %s", refname, err.buf);4639 strbuf_release(&err);4640 return -1;4641 }4642 if (!reflog_exists(refname)) {4643 unlock_ref(lock);4644 return 0;4645 }46464647 log_file = git_pathdup("logs/%s", refname);4648 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4649 /*4650 * Even though holding $GIT_DIR/logs/$reflog.lock has4651 * no locking implications, we use the lock_file4652 * machinery here anyway because it does a lot of the4653 * work we need, including cleaning up if the program4654 * exits unexpectedly.4655 */4656 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {4657 struct strbuf err = STRBUF_INIT;4658 unable_to_lock_message(log_file, errno, &err);4659 error("%s", err.buf);4660 strbuf_release(&err);4661 goto failure;4662 }4663 cb.newlog = fdopen_lock_file(&reflog_lock, "w");4664 if (!cb.newlog) {4665 error("cannot fdopen %s (%s)",4666 get_lock_file_path(&reflog_lock), strerror(errno));4667 goto failure;4668 }4669 }46704671 (*prepare_fn)(refname, sha1, cb.policy_cb);4672 for_each_reflog_ent(refname, expire_reflog_ent, &cb);4673 (*cleanup_fn)(cb.policy_cb);46744675 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4676 /*4677 * It doesn't make sense to adjust a reference pointed4678 * to by a symbolic ref based on expiring entries in4679 * the symbolic reference's reflog. Nor can we update4680 * a reference if there are no remaining reflog4681 * entries.4682 */4683 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4684 !(type & REF_ISSYMREF) &&4685 !is_null_sha1(cb.last_kept_sha1);46864687 if (close_lock_file(&reflog_lock)) {4688 status |= error("couldn't write %s: %s", log_file,4689 strerror(errno));4690 } else if (update &&4691 (write_in_full(get_lock_file_fd(lock->lk),4692 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||4693 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||4694 close_ref(lock) < 0)) {4695 status |= error("couldn't write %s",4696 get_lock_file_path(lock->lk));4697 rollback_lock_file(&reflog_lock);4698 } else if (commit_lock_file(&reflog_lock)) {4699 status |= error("unable to commit reflog '%s' (%s)",4700 log_file, strerror(errno));4701 } else if (update && commit_ref(lock)) {4702 status |= error("couldn't set %s", lock->ref_name);4703 }4704 }4705 free(log_file);4706 unlock_ref(lock);4707 return status;47084709 failure:4710 rollback_lock_file(&reflog_lock);4711 free(log_file);4712 unlock_ref(lock);4713 return -1;4714}