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 9/* 10 * How to handle various characters in refnames: 11 * 0: An acceptable character for refs 12 * 1: End-of-component 13 * 2: ., look for a preceding . to reject .. in refs 14 * 3: {, look for a preceding @ to reject @{ in refs 15 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 16 */ 17static unsigned char refname_disposition[256] = { 18 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 19 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 20 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1, 21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0, 24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4 26}; 27 28/* 29 * Used as a flag to ref_transaction_delete when a loose ref is being 30 * pruned. 31 */ 32#define REF_ISPRUNING 0x0100 33/* 34 * Try to read one refname component from the front of refname. 35 * Return the length of the component found, or -1 if the component is 36 * not legal. It is legal if it is something reasonable to have under 37 * ".git/refs/"; We do not like it if: 38 * 39 * - any path component of it begins with ".", or 40 * - it has double dots "..", or 41 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 42 * - it ends with a "/". 43 * - it ends with ".lock" 44 * - it contains a "\" (backslash) 45 */ 46static int check_refname_component(const char *refname, int flags) 47{ 48 const char *cp; 49 char last = '\0'; 50 51 for (cp = refname; ; cp++) { 52 int ch = *cp & 255; 53 unsigned char disp = refname_disposition[ch]; 54 switch (disp) { 55 case 1: 56 goto out; 57 case 2: 58 if (last == '.') 59 return -1; /* Refname contains "..". */ 60 break; 61 case 3: 62 if (last == '@') 63 return -1; /* Refname contains "@{". */ 64 break; 65 case 4: 66 return -1; 67 } 68 last = ch; 69 } 70out: 71 if (cp == refname) 72 return 0; /* Component has zero length. */ 73 if (refname[0] == '.') 74 return -1; /* Component starts with '.'. */ 75 if (cp - refname >= LOCK_SUFFIX_LEN && 76 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 77 return -1; /* Refname ends with ".lock". */ 78 return cp - refname; 79} 80 81int check_refname_format(const char *refname, int flags) 82{ 83 int component_len, component_count = 0; 84 85 if (!strcmp(refname, "@")) 86 /* Refname is a single character '@'. */ 87 return -1; 88 89 while (1) { 90 /* We are at the start of a path component. */ 91 component_len = check_refname_component(refname, flags); 92 if (component_len <= 0) { 93 if ((flags & REFNAME_REFSPEC_PATTERN) && 94 refname[0] == '*' && 95 (refname[1] == '\0' || refname[1] == '/')) { 96 /* Accept one wildcard as a full refname component. */ 97 flags &= ~REFNAME_REFSPEC_PATTERN; 98 component_len = 1; 99 } else { 100 return -1; 101 } 102 } 103 component_count++; 104 if (refname[component_len] == '\0') 105 break; 106 /* Skip to next component. */ 107 refname += component_len + 1; 108 } 109 110 if (refname[component_len - 1] == '.') 111 return -1; /* Refname ends with '.'. */ 112 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2) 113 return -1; /* Refname has only one component. */ 114 return 0; 115} 116 117struct ref_entry; 118 119/* 120 * Information used (along with the information in ref_entry) to 121 * describe a single cached reference. This data structure only 122 * occurs embedded in a union in struct ref_entry, and only when 123 * (ref_entry->flag & REF_DIR) is zero. 124 */ 125struct ref_value { 126 /* 127 * The name of the object to which this reference resolves 128 * (which may be a tag object). If REF_ISBROKEN, this is 129 * null. If REF_ISSYMREF, then this is the name of the object 130 * referred to by the last reference in the symlink chain. 131 */ 132 unsigned char sha1[20]; 133 134 /* 135 * If REF_KNOWS_PEELED, then this field holds the peeled value 136 * of this reference, or null if the reference is known not to 137 * be peelable. See the documentation for peel_ref() for an 138 * exact definition of "peelable". 139 */ 140 unsigned char peeled[20]; 141}; 142 143struct ref_cache; 144 145/* 146 * Information used (along with the information in ref_entry) to 147 * describe a level in the hierarchy of references. This data 148 * structure only occurs embedded in a union in struct ref_entry, and 149 * only when (ref_entry.flag & REF_DIR) is set. In that case, 150 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 151 * in the directory have already been read: 152 * 153 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 154 * or packed references, already read. 155 * 156 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 157 * references that hasn't been read yet (nor has any of its 158 * subdirectories). 159 * 160 * Entries within a directory are stored within a growable array of 161 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 162 * sorted are sorted by their component name in strcmp() order and the 163 * remaining entries are unsorted. 164 * 165 * Loose references are read lazily, one directory at a time. When a 166 * directory of loose references is read, then all of the references 167 * in that directory are stored, and REF_INCOMPLETE stubs are created 168 * for any subdirectories, but the subdirectories themselves are not 169 * read. The reading is triggered by get_ref_dir(). 170 */ 171struct ref_dir { 172 int nr, alloc; 173 174 /* 175 * Entries with index 0 <= i < sorted are sorted by name. New 176 * entries are appended to the list unsorted, and are sorted 177 * only when required; thus we avoid the need to sort the list 178 * after the addition of every reference. 179 */ 180 int sorted; 181 182 /* A pointer to the ref_cache that contains this ref_dir. */ 183 struct ref_cache *ref_cache; 184 185 struct ref_entry **entries; 186}; 187 188/* 189 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 190 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 191 * public values; see refs.h. 192 */ 193 194/* 195 * The field ref_entry->u.value.peeled of this value entry contains 196 * the correct peeled value for the reference, which might be 197 * null_sha1 if the reference is not a tag or if it is broken. 198 */ 199#define REF_KNOWS_PEELED 0x10 200 201/* ref_entry represents a directory of references */ 202#define REF_DIR 0x20 203 204/* 205 * Entry has not yet been read from disk (used only for REF_DIR 206 * entries representing loose references) 207 */ 208#define REF_INCOMPLETE 0x40 209 210/* 211 * A ref_entry represents either a reference or a "subdirectory" of 212 * references. 213 * 214 * Each directory in the reference namespace is represented by a 215 * ref_entry with (flags & REF_DIR) set and containing a subdir member 216 * that holds the entries in that directory that have been read so 217 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 218 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 219 * used for loose reference directories. 220 * 221 * References are represented by a ref_entry with (flags & REF_DIR) 222 * unset and a value member that describes the reference's value. The 223 * flag member is at the ref_entry level, but it is also needed to 224 * interpret the contents of the value field (in other words, a 225 * ref_value object is not very much use without the enclosing 226 * ref_entry). 227 * 228 * Reference names cannot end with slash and directories' names are 229 * always stored with a trailing slash (except for the top-level 230 * directory, which is always denoted by ""). This has two nice 231 * consequences: (1) when the entries in each subdir are sorted 232 * lexicographically by name (as they usually are), the references in 233 * a whole tree can be generated in lexicographic order by traversing 234 * the tree in left-to-right, depth-first order; (2) the names of 235 * references and subdirectories cannot conflict, and therefore the 236 * presence of an empty subdirectory does not block the creation of a 237 * similarly-named reference. (The fact that reference names with the 238 * same leading components can conflict *with each other* is a 239 * separate issue that is regulated by is_refname_available().) 240 * 241 * Please note that the name field contains the fully-qualified 242 * reference (or subdirectory) name. Space could be saved by only 243 * storing the relative names. But that would require the full names 244 * to be generated on the fly when iterating in do_for_each_ref(), and 245 * would break callback functions, who have always been able to assume 246 * that the name strings that they are passed will not be freed during 247 * the iteration. 248 */ 249struct ref_entry { 250 unsigned char flag; /* ISSYMREF? ISPACKED? */ 251 union { 252 struct ref_value value; /* if not (flags&REF_DIR) */ 253 struct ref_dir subdir; /* if (flags&REF_DIR) */ 254 } u; 255 /* 256 * The full name of the reference (e.g., "refs/heads/master") 257 * or the full name of the directory with a trailing slash 258 * (e.g., "refs/heads/"): 259 */ 260 char name[FLEX_ARRAY]; 261}; 262 263static void read_loose_refs(const char *dirname, struct ref_dir *dir); 264 265static struct ref_dir *get_ref_dir(struct ref_entry *entry) 266{ 267 struct ref_dir *dir; 268 assert(entry->flag & REF_DIR); 269 dir = &entry->u.subdir; 270 if (entry->flag & REF_INCOMPLETE) { 271 read_loose_refs(entry->name, dir); 272 entry->flag &= ~REF_INCOMPLETE; 273 } 274 return dir; 275} 276 277/* 278 * Check if a refname is safe. 279 * For refs that start with "refs/" we consider it safe as long they do 280 * not try to resolve to outside of refs/. 281 * 282 * For all other refs we only consider them safe iff they only contain 283 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 284 * "config"). 285 */ 286static int refname_is_safe(const char *refname) 287{ 288 if (starts_with(refname, "refs/")) { 289 char *buf; 290 int result; 291 292 buf = xmalloc(strlen(refname) + 1); 293 /* 294 * Does the refname try to escape refs/? 295 * For example: refs/foo/../bar is safe but refs/foo/../../bar 296 * is not. 297 */ 298 result = !normalize_path_copy(buf, refname + strlen("refs/")); 299 free(buf); 300 return result; 301 } 302 while (*refname) { 303 if (!isupper(*refname) && *refname != '_') 304 return 0; 305 refname++; 306 } 307 return 1; 308} 309 310static struct ref_entry *create_ref_entry(const char *refname, 311 const unsigned char *sha1, int flag, 312 int check_name) 313{ 314 int len; 315 struct ref_entry *ref; 316 317 if (check_name && 318 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 319 die("Reference has invalid format: '%s'", refname); 320 if (!check_name && !refname_is_safe(refname)) 321 die("Reference has invalid name: '%s'", refname); 322 len = strlen(refname) + 1; 323 ref = xmalloc(sizeof(struct ref_entry) + len); 324 hashcpy(ref->u.value.sha1, sha1); 325 hashclr(ref->u.value.peeled); 326 memcpy(ref->name, refname, len); 327 ref->flag = flag; 328 return ref; 329} 330 331static void clear_ref_dir(struct ref_dir *dir); 332 333static void free_ref_entry(struct ref_entry *entry) 334{ 335 if (entry->flag & REF_DIR) { 336 /* 337 * Do not use get_ref_dir() here, as that might 338 * trigger the reading of loose refs. 339 */ 340 clear_ref_dir(&entry->u.subdir); 341 } 342 free(entry); 343} 344 345/* 346 * Add a ref_entry to the end of dir (unsorted). Entry is always 347 * stored directly in dir; no recursion into subdirectories is 348 * done. 349 */ 350static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry) 351{ 352 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc); 353 dir->entries[dir->nr++] = entry; 354 /* optimize for the case that entries are added in order */ 355 if (dir->nr == 1 || 356 (dir->nr == dir->sorted + 1 && 357 strcmp(dir->entries[dir->nr - 2]->name, 358 dir->entries[dir->nr - 1]->name) < 0)) 359 dir->sorted = dir->nr; 360} 361 362/* 363 * Clear and free all entries in dir, recursively. 364 */ 365static void clear_ref_dir(struct ref_dir *dir) 366{ 367 int i; 368 for (i = 0; i < dir->nr; i++) 369 free_ref_entry(dir->entries[i]); 370 free(dir->entries); 371 dir->sorted = dir->nr = dir->alloc = 0; 372 dir->entries = NULL; 373} 374 375/* 376 * Create a struct ref_entry object for the specified dirname. 377 * dirname is the name of the directory with a trailing slash (e.g., 378 * "refs/heads/") or "" for the top-level directory. 379 */ 380static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 381 const char *dirname, size_t len, 382 int incomplete) 383{ 384 struct ref_entry *direntry; 385 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1); 386 memcpy(direntry->name, dirname, len); 387 direntry->name[len] = '\0'; 388 direntry->u.subdir.ref_cache = ref_cache; 389 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0); 390 return direntry; 391} 392 393static int ref_entry_cmp(const void *a, const void *b) 394{ 395 struct ref_entry *one = *(struct ref_entry **)a; 396 struct ref_entry *two = *(struct ref_entry **)b; 397 return strcmp(one->name, two->name); 398} 399 400static void sort_ref_dir(struct ref_dir *dir); 401 402struct string_slice { 403 size_t len; 404 const char *str; 405}; 406 407static int ref_entry_cmp_sslice(const void *key_, const void *ent_) 408{ 409 const struct string_slice *key = key_; 410 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_; 411 int cmp = strncmp(key->str, ent->name, key->len); 412 if (cmp) 413 return cmp; 414 return '\0' - (unsigned char)ent->name[key->len]; 415} 416 417/* 418 * Return the index of the entry with the given refname from the 419 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 420 * no such entry is found. dir must already be complete. 421 */ 422static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len) 423{ 424 struct ref_entry **r; 425 struct string_slice key; 426 427 if (refname == NULL || !dir->nr) 428 return -1; 429 430 sort_ref_dir(dir); 431 key.len = len; 432 key.str = refname; 433 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries), 434 ref_entry_cmp_sslice); 435 436 if (r == NULL) 437 return -1; 438 439 return r - dir->entries; 440} 441 442/* 443 * Search for a directory entry directly within dir (without 444 * recursing). Sort dir if necessary. subdirname must be a directory 445 * name (i.e., end in '/'). If mkdir is set, then create the 446 * directory if it is missing; otherwise, return NULL if the desired 447 * directory cannot be found. dir must already be complete. 448 */ 449static struct ref_dir *search_for_subdir(struct ref_dir *dir, 450 const char *subdirname, size_t len, 451 int mkdir) 452{ 453 int entry_index = search_ref_dir(dir, subdirname, len); 454 struct ref_entry *entry; 455 if (entry_index == -1) { 456 if (!mkdir) 457 return NULL; 458 /* 459 * Since dir is complete, the absence of a subdir 460 * means that the subdir really doesn't exist; 461 * therefore, create an empty record for it but mark 462 * the record complete. 463 */ 464 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0); 465 add_entry_to_dir(dir, entry); 466 } else { 467 entry = dir->entries[entry_index]; 468 } 469 return get_ref_dir(entry); 470} 471 472/* 473 * If refname is a reference name, find the ref_dir within the dir 474 * tree that should hold refname. If refname is a directory name 475 * (i.e., ends in '/'), then return that ref_dir itself. dir must 476 * represent the top-level directory and must already be complete. 477 * Sort ref_dirs and recurse into subdirectories as necessary. If 478 * mkdir is set, then create any missing directories; otherwise, 479 * return NULL if the desired directory cannot be found. 480 */ 481static struct ref_dir *find_containing_dir(struct ref_dir *dir, 482 const char *refname, int mkdir) 483{ 484 const char *slash; 485 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 486 size_t dirnamelen = slash - refname + 1; 487 struct ref_dir *subdir; 488 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir); 489 if (!subdir) { 490 dir = NULL; 491 break; 492 } 493 dir = subdir; 494 } 495 496 return dir; 497} 498 499/* 500 * Find the value entry with the given name in dir, sorting ref_dirs 501 * and recursing into subdirectories as necessary. If the name is not 502 * found or it corresponds to a directory entry, return NULL. 503 */ 504static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname) 505{ 506 int entry_index; 507 struct ref_entry *entry; 508 dir = find_containing_dir(dir, refname, 0); 509 if (!dir) 510 return NULL; 511 entry_index = search_ref_dir(dir, refname, strlen(refname)); 512 if (entry_index == -1) 513 return NULL; 514 entry = dir->entries[entry_index]; 515 return (entry->flag & REF_DIR) ? NULL : entry; 516} 517 518/* 519 * Remove the entry with the given name from dir, recursing into 520 * subdirectories as necessary. If refname is the name of a directory 521 * (i.e., ends with '/'), then remove the directory and its contents. 522 * If the removal was successful, return the number of entries 523 * remaining in the directory entry that contained the deleted entry. 524 * If the name was not found, return -1. Please note that this 525 * function only deletes the entry from the cache; it does not delete 526 * it from the filesystem or ensure that other cache entries (which 527 * might be symbolic references to the removed entry) are updated. 528 * Nor does it remove any containing dir entries that might be made 529 * empty by the removal. dir must represent the top-level directory 530 * and must already be complete. 531 */ 532static int remove_entry(struct ref_dir *dir, const char *refname) 533{ 534 int refname_len = strlen(refname); 535 int entry_index; 536 struct ref_entry *entry; 537 int is_dir = refname[refname_len - 1] == '/'; 538 if (is_dir) { 539 /* 540 * refname represents a reference directory. Remove 541 * the trailing slash; otherwise we will get the 542 * directory *representing* refname rather than the 543 * one *containing* it. 544 */ 545 char *dirname = xmemdupz(refname, refname_len - 1); 546 dir = find_containing_dir(dir, dirname, 0); 547 free(dirname); 548 } else { 549 dir = find_containing_dir(dir, refname, 0); 550 } 551 if (!dir) 552 return -1; 553 entry_index = search_ref_dir(dir, refname, refname_len); 554 if (entry_index == -1) 555 return -1; 556 entry = dir->entries[entry_index]; 557 558 memmove(&dir->entries[entry_index], 559 &dir->entries[entry_index + 1], 560 (dir->nr - entry_index - 1) * sizeof(*dir->entries) 561 ); 562 dir->nr--; 563 if (dir->sorted > entry_index) 564 dir->sorted--; 565 free_ref_entry(entry); 566 return dir->nr; 567} 568 569/* 570 * Add a ref_entry to the ref_dir (unsorted), recursing into 571 * subdirectories as necessary. dir must represent the top-level 572 * directory. Return 0 on success. 573 */ 574static int add_ref(struct ref_dir *dir, struct ref_entry *ref) 575{ 576 dir = find_containing_dir(dir, ref->name, 1); 577 if (!dir) 578 return -1; 579 add_entry_to_dir(dir, ref); 580 return 0; 581} 582 583/* 584 * Emit a warning and return true iff ref1 and ref2 have the same name 585 * and the same sha1. Die if they have the same name but different 586 * sha1s. 587 */ 588static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2) 589{ 590 if (strcmp(ref1->name, ref2->name)) 591 return 0; 592 593 /* Duplicate name; make sure that they don't conflict: */ 594 595 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 596 /* This is impossible by construction */ 597 die("Reference directory conflict: %s", ref1->name); 598 599 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 600 die("Duplicated ref, and SHA1s don't match: %s", ref1->name); 601 602 warning("Duplicated ref: %s", ref1->name); 603 return 1; 604} 605 606/* 607 * Sort the entries in dir non-recursively (if they are not already 608 * sorted) and remove any duplicate entries. 609 */ 610static void sort_ref_dir(struct ref_dir *dir) 611{ 612 int i, j; 613 struct ref_entry *last = NULL; 614 615 /* 616 * This check also prevents passing a zero-length array to qsort(), 617 * which is a problem on some platforms. 618 */ 619 if (dir->sorted == dir->nr) 620 return; 621 622 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp); 623 624 /* Remove any duplicates: */ 625 for (i = 0, j = 0; j < dir->nr; j++) { 626 struct ref_entry *entry = dir->entries[j]; 627 if (last && is_dup_ref(last, entry)) 628 free_ref_entry(entry); 629 else 630 last = dir->entries[i++] = entry; 631 } 632 dir->sorted = dir->nr = i; 633} 634 635/* Include broken references in a do_for_each_ref*() iteration: */ 636#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 637 638/* 639 * Return true iff the reference described by entry can be resolved to 640 * an object in the database. Emit a warning if the referred-to 641 * object does not exist. 642 */ 643static int ref_resolves_to_object(struct ref_entry *entry) 644{ 645 if (entry->flag & REF_ISBROKEN) 646 return 0; 647 if (!has_sha1_file(entry->u.value.sha1)) { 648 error("%s does not point to a valid object!", entry->name); 649 return 0; 650 } 651 return 1; 652} 653 654/* 655 * current_ref is a performance hack: when iterating over references 656 * using the for_each_ref*() functions, current_ref is set to the 657 * current reference's entry before calling the callback function. If 658 * the callback function calls peel_ref(), then peel_ref() first 659 * checks whether the reference to be peeled is the current reference 660 * (it usually is) and if so, returns that reference's peeled version 661 * if it is available. This avoids a refname lookup in a common case. 662 */ 663static struct ref_entry *current_ref; 664 665typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data); 666 667struct ref_entry_cb { 668 const char *base; 669 int trim; 670 int flags; 671 each_ref_fn *fn; 672 void *cb_data; 673}; 674 675/* 676 * Handle one reference in a do_for_each_ref*()-style iteration, 677 * calling an each_ref_fn for each entry. 678 */ 679static int do_one_ref(struct ref_entry *entry, void *cb_data) 680{ 681 struct ref_entry_cb *data = cb_data; 682 struct ref_entry *old_current_ref; 683 int retval; 684 685 if (!starts_with(entry->name, data->base)) 686 return 0; 687 688 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 689 !ref_resolves_to_object(entry)) 690 return 0; 691 692 /* Store the old value, in case this is a recursive call: */ 693 old_current_ref = current_ref; 694 current_ref = entry; 695 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 696 entry->flag, data->cb_data); 697 current_ref = old_current_ref; 698 return retval; 699} 700 701/* 702 * Call fn for each reference in dir that has index in the range 703 * offset <= index < dir->nr. Recurse into subdirectories that are in 704 * that index range, sorting them before iterating. This function 705 * does not sort dir itself; it should be sorted beforehand. fn is 706 * called for all references, including broken ones. 707 */ 708static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset, 709 each_ref_entry_fn fn, void *cb_data) 710{ 711 int i; 712 assert(dir->sorted == dir->nr); 713 for (i = offset; i < dir->nr; i++) { 714 struct ref_entry *entry = dir->entries[i]; 715 int retval; 716 if (entry->flag & REF_DIR) { 717 struct ref_dir *subdir = get_ref_dir(entry); 718 sort_ref_dir(subdir); 719 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data); 720 } else { 721 retval = fn(entry, cb_data); 722 } 723 if (retval) 724 return retval; 725 } 726 return 0; 727} 728 729/* 730 * Call fn for each reference in the union of dir1 and dir2, in order 731 * by refname. Recurse into subdirectories. If a value entry appears 732 * in both dir1 and dir2, then only process the version that is in 733 * dir2. The input dirs must already be sorted, but subdirs will be 734 * sorted as needed. fn is called for all references, including 735 * broken ones. 736 */ 737static int do_for_each_entry_in_dirs(struct ref_dir *dir1, 738 struct ref_dir *dir2, 739 each_ref_entry_fn fn, void *cb_data) 740{ 741 int retval; 742 int i1 = 0, i2 = 0; 743 744 assert(dir1->sorted == dir1->nr); 745 assert(dir2->sorted == dir2->nr); 746 while (1) { 747 struct ref_entry *e1, *e2; 748 int cmp; 749 if (i1 == dir1->nr) { 750 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data); 751 } 752 if (i2 == dir2->nr) { 753 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data); 754 } 755 e1 = dir1->entries[i1]; 756 e2 = dir2->entries[i2]; 757 cmp = strcmp(e1->name, e2->name); 758 if (cmp == 0) { 759 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 760 /* Both are directories; descend them in parallel. */ 761 struct ref_dir *subdir1 = get_ref_dir(e1); 762 struct ref_dir *subdir2 = get_ref_dir(e2); 763 sort_ref_dir(subdir1); 764 sort_ref_dir(subdir2); 765 retval = do_for_each_entry_in_dirs( 766 subdir1, subdir2, fn, cb_data); 767 i1++; 768 i2++; 769 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 770 /* Both are references; ignore the one from dir1. */ 771 retval = fn(e2, cb_data); 772 i1++; 773 i2++; 774 } else { 775 die("conflict between reference and directory: %s", 776 e1->name); 777 } 778 } else { 779 struct ref_entry *e; 780 if (cmp < 0) { 781 e = e1; 782 i1++; 783 } else { 784 e = e2; 785 i2++; 786 } 787 if (e->flag & REF_DIR) { 788 struct ref_dir *subdir = get_ref_dir(e); 789 sort_ref_dir(subdir); 790 retval = do_for_each_entry_in_dir( 791 subdir, 0, fn, cb_data); 792 } else { 793 retval = fn(e, cb_data); 794 } 795 } 796 if (retval) 797 return retval; 798 } 799} 800 801/* 802 * Load all of the refs from the dir into our in-memory cache. The hard work 803 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 804 * through all of the sub-directories. We do not even need to care about 805 * sorting, as traversal order does not matter to us. 806 */ 807static void prime_ref_dir(struct ref_dir *dir) 808{ 809 int i; 810 for (i = 0; i < dir->nr; i++) { 811 struct ref_entry *entry = dir->entries[i]; 812 if (entry->flag & REF_DIR) 813 prime_ref_dir(get_ref_dir(entry)); 814 } 815} 816 817static int entry_matches(struct ref_entry *entry, const struct string_list *list) 818{ 819 return list && string_list_has_string(list, entry->name); 820} 821 822struct nonmatching_ref_data { 823 const struct string_list *skip; 824 struct ref_entry *found; 825}; 826 827static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata) 828{ 829 struct nonmatching_ref_data *data = vdata; 830 831 if (entry_matches(entry, data->skip)) 832 return 0; 833 834 data->found = entry; 835 return 1; 836} 837 838static void report_refname_conflict(struct ref_entry *entry, 839 const char *refname) 840{ 841 error("'%s' exists; cannot create '%s'", entry->name, refname); 842} 843 844/* 845 * Return true iff a reference named refname could be created without 846 * conflicting with the name of an existing reference in dir. If 847 * skip is non-NULL, ignore potential conflicts with refs in skip 848 * (e.g., because they are scheduled for deletion in the same 849 * operation). 850 * 851 * Two reference names conflict if one of them exactly matches the 852 * leading components of the other; e.g., "foo/bar" conflicts with 853 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 854 * "foo/barbados". 855 * 856 * skip must be sorted. 857 */ 858static int is_refname_available(const char *refname, 859 const struct string_list *skip, 860 struct ref_dir *dir) 861{ 862 const char *slash; 863 size_t len; 864 int pos; 865 char *dirname; 866 867 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 868 /* 869 * We are still at a leading dir of the refname; we are 870 * looking for a conflict with a leaf entry. 871 * 872 * If we find one, we still must make sure it is 873 * not in "skip". 874 */ 875 pos = search_ref_dir(dir, refname, slash - refname); 876 if (pos >= 0) { 877 struct ref_entry *entry = dir->entries[pos]; 878 if (entry_matches(entry, skip)) 879 return 1; 880 report_refname_conflict(entry, refname); 881 return 0; 882 } 883 884 885 /* 886 * Otherwise, we can try to continue our search with 887 * the next component; if we come up empty, we know 888 * there is nothing under this whole prefix. 889 */ 890 pos = search_ref_dir(dir, refname, slash + 1 - refname); 891 if (pos < 0) 892 return 1; 893 894 dir = get_ref_dir(dir->entries[pos]); 895 } 896 897 /* 898 * We are at the leaf of our refname; we want to 899 * make sure there are no directories which match it. 900 */ 901 len = strlen(refname); 902 dirname = xmallocz(len + 1); 903 sprintf(dirname, "%s/", refname); 904 pos = search_ref_dir(dir, dirname, len + 1); 905 free(dirname); 906 907 if (pos >= 0) { 908 /* 909 * We found a directory named "refname". It is a 910 * problem iff it contains any ref that is not 911 * in "skip". 912 */ 913 struct ref_entry *entry = dir->entries[pos]; 914 struct ref_dir *dir = get_ref_dir(entry); 915 struct nonmatching_ref_data data; 916 917 data.skip = skip; 918 sort_ref_dir(dir); 919 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) 920 return 1; 921 922 report_refname_conflict(data.found, refname); 923 return 0; 924 } 925 926 /* 927 * There is no point in searching for another leaf 928 * node which matches it; such an entry would be the 929 * ref we are looking for, not a conflict. 930 */ 931 return 1; 932} 933 934struct packed_ref_cache { 935 struct ref_entry *root; 936 937 /* 938 * Count of references to the data structure in this instance, 939 * including the pointer from ref_cache::packed if any. The 940 * data will not be freed as long as the reference count is 941 * nonzero. 942 */ 943 unsigned int referrers; 944 945 /* 946 * Iff the packed-refs file associated with this instance is 947 * currently locked for writing, this points at the associated 948 * lock (which is owned by somebody else). The referrer count 949 * is also incremented when the file is locked and decremented 950 * when it is unlocked. 951 */ 952 struct lock_file *lock; 953 954 /* The metadata from when this packed-refs cache was read */ 955 struct stat_validity validity; 956}; 957 958/* 959 * Future: need to be in "struct repository" 960 * when doing a full libification. 961 */ 962static struct ref_cache { 963 struct ref_cache *next; 964 struct ref_entry *loose; 965 struct packed_ref_cache *packed; 966 /* 967 * The submodule name, or "" for the main repo. We allocate 968 * length 1 rather than FLEX_ARRAY so that the main ref_cache 969 * is initialized correctly. 970 */ 971 char name[1]; 972} ref_cache, *submodule_ref_caches; 973 974/* Lock used for the main packed-refs file: */ 975static struct lock_file packlock; 976 977/* 978 * Increment the reference count of *packed_refs. 979 */ 980static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 981{ 982 packed_refs->referrers++; 983} 984 985/* 986 * Decrease the reference count of *packed_refs. If it goes to zero, 987 * free *packed_refs and return true; otherwise return false. 988 */ 989static int release_packed_ref_cache(struct packed_ref_cache *packed_refs) 990{ 991 if (!--packed_refs->referrers) { 992 free_ref_entry(packed_refs->root); 993 stat_validity_clear(&packed_refs->validity); 994 free(packed_refs); 995 return 1; 996 } else { 997 return 0; 998 } 999}10001001static void clear_packed_ref_cache(struct ref_cache *refs)1002{1003 if (refs->packed) {1004 struct packed_ref_cache *packed_refs = refs->packed;10051006 if (packed_refs->lock)1007 die("internal error: packed-ref cache cleared while locked");1008 refs->packed = NULL;1009 release_packed_ref_cache(packed_refs);1010 }1011}10121013static void clear_loose_ref_cache(struct ref_cache *refs)1014{1015 if (refs->loose) {1016 free_ref_entry(refs->loose);1017 refs->loose = NULL;1018 }1019}10201021static struct ref_cache *create_ref_cache(const char *submodule)1022{1023 int len;1024 struct ref_cache *refs;1025 if (!submodule)1026 submodule = "";1027 len = strlen(submodule) + 1;1028 refs = xcalloc(1, sizeof(struct ref_cache) + len);1029 memcpy(refs->name, submodule, len);1030 return refs;1031}10321033/*1034 * Return a pointer to a ref_cache for the specified submodule. For1035 * the main repository, use submodule==NULL. The returned structure1036 * will be allocated and initialized but not necessarily populated; it1037 * should not be freed.1038 */1039static struct ref_cache *get_ref_cache(const char *submodule)1040{1041 struct ref_cache *refs;10421043 if (!submodule || !*submodule)1044 return &ref_cache;10451046 for (refs = submodule_ref_caches; refs; refs = refs->next)1047 if (!strcmp(submodule, refs->name))1048 return refs;10491050 refs = create_ref_cache(submodule);1051 refs->next = submodule_ref_caches;1052 submodule_ref_caches = refs;1053 return refs;1054}10551056/* The length of a peeled reference line in packed-refs, including EOL: */1057#define PEELED_LINE_LENGTH 4210581059/*1060 * The packed-refs header line that we write out. Perhaps other1061 * traits will be added later. The trailing space is required.1062 */1063static const char PACKED_REFS_HEADER[] =1064 "# pack-refs with: peeled fully-peeled \n";10651066/*1067 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1068 * Return a pointer to the refname within the line (null-terminated),1069 * or NULL if there was a problem.1070 */1071static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)1072{1073 const char *ref;10741075 /*1076 * 42: the answer to everything.1077 *1078 * In this case, it happens to be the answer to1079 * 40 (length of sha1 hex representation)1080 * +1 (space in between hex and name)1081 * +1 (newline at the end of the line)1082 */1083 if (line->len <= 42)1084 return NULL;10851086 if (get_sha1_hex(line->buf, sha1) < 0)1087 return NULL;1088 if (!isspace(line->buf[40]))1089 return NULL;10901091 ref = line->buf + 41;1092 if (isspace(*ref))1093 return NULL;10941095 if (line->buf[line->len - 1] != '\n')1096 return NULL;1097 line->buf[--line->len] = 0;10981099 return ref;1100}11011102/*1103 * Read f, which is a packed-refs file, into dir.1104 *1105 * A comment line of the form "# pack-refs with: " may contain zero or1106 * more traits. We interpret the traits as follows:1107 *1108 * No traits:1109 *1110 * Probably no references are peeled. But if the file contains a1111 * peeled value for a reference, we will use it.1112 *1113 * peeled:1114 *1115 * References under "refs/tags/", if they *can* be peeled, *are*1116 * peeled in this file. References outside of "refs/tags/" are1117 * probably not peeled even if they could have been, but if we find1118 * a peeled value for such a reference we will use it.1119 *1120 * fully-peeled:1121 *1122 * All references in the file that can be peeled are peeled.1123 * Inversely (and this is more important), any references in the1124 * file for which no peeled value is recorded is not peelable. This1125 * trait should typically be written alongside "peeled" for1126 * compatibility with older clients, but we do not require it1127 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1128 */1129static void read_packed_refs(FILE *f, struct ref_dir *dir)1130{1131 struct ref_entry *last = NULL;1132 struct strbuf line = STRBUF_INIT;1133 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11341135 while (strbuf_getwholeline(&line, f, '\n') != EOF) {1136 unsigned char sha1[20];1137 const char *refname;1138 const char *traits;11391140 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {1141 if (strstr(traits, " fully-peeled "))1142 peeled = PEELED_FULLY;1143 else if (strstr(traits, " peeled "))1144 peeled = PEELED_TAGS;1145 /* perhaps other traits later as well */1146 continue;1147 }11481149 refname = parse_ref_line(&line, sha1);1150 if (refname) {1151 int flag = REF_ISPACKED;11521153 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1154 hashclr(sha1);1155 flag |= REF_BAD_NAME | REF_ISBROKEN;1156 }1157 last = create_ref_entry(refname, sha1, flag, 0);1158 if (peeled == PEELED_FULLY ||1159 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))1160 last->flag |= REF_KNOWS_PEELED;1161 add_ref(dir, last);1162 continue;1163 }1164 if (last &&1165 line.buf[0] == '^' &&1166 line.len == PEELED_LINE_LENGTH &&1167 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&1168 !get_sha1_hex(line.buf + 1, sha1)) {1169 hashcpy(last->u.value.peeled, sha1);1170 /*1171 * Regardless of what the file header said,1172 * we definitely know the value of *this*1173 * reference:1174 */1175 last->flag |= REF_KNOWS_PEELED;1176 }1177 }11781179 strbuf_release(&line);1180}11811182/*1183 * Get the packed_ref_cache for the specified ref_cache, creating it1184 * if necessary.1185 */1186static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1187{1188 const char *packed_refs_file;11891190 if (*refs->name)1191 packed_refs_file = git_path_submodule(refs->name, "packed-refs");1192 else1193 packed_refs_file = git_path("packed-refs");11941195 if (refs->packed &&1196 !stat_validity_check(&refs->packed->validity, packed_refs_file))1197 clear_packed_ref_cache(refs);11981199 if (!refs->packed) {1200 FILE *f;12011202 refs->packed = xcalloc(1, sizeof(*refs->packed));1203 acquire_packed_ref_cache(refs->packed);1204 refs->packed->root = create_dir_entry(refs, "", 0, 0);1205 f = fopen(packed_refs_file, "r");1206 if (f) {1207 stat_validity_update(&refs->packed->validity, fileno(f));1208 read_packed_refs(f, get_ref_dir(refs->packed->root));1209 fclose(f);1210 }1211 }1212 return refs->packed;1213}12141215static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1216{1217 return get_ref_dir(packed_ref_cache->root);1218}12191220static struct ref_dir *get_packed_refs(struct ref_cache *refs)1221{1222 return get_packed_ref_dir(get_packed_ref_cache(refs));1223}12241225void add_packed_ref(const char *refname, const unsigned char *sha1)1226{1227 struct packed_ref_cache *packed_ref_cache =1228 get_packed_ref_cache(&ref_cache);12291230 if (!packed_ref_cache->lock)1231 die("internal error: packed refs not locked");1232 add_ref(get_packed_ref_dir(packed_ref_cache),1233 create_ref_entry(refname, sha1, REF_ISPACKED, 1));1234}12351236/*1237 * Read the loose references from the namespace dirname into dir1238 * (without recursing). dirname must end with '/'. dir must be the1239 * directory entry corresponding to dirname.1240 */1241static void read_loose_refs(const char *dirname, struct ref_dir *dir)1242{1243 struct ref_cache *refs = dir->ref_cache;1244 DIR *d;1245 const char *path;1246 struct dirent *de;1247 int dirnamelen = strlen(dirname);1248 struct strbuf refname;12491250 if (*refs->name)1251 path = git_path_submodule(refs->name, "%s", dirname);1252 else1253 path = git_path("%s", dirname);12541255 d = opendir(path);1256 if (!d)1257 return;12581259 strbuf_init(&refname, dirnamelen + 257);1260 strbuf_add(&refname, dirname, dirnamelen);12611262 while ((de = readdir(d)) != NULL) {1263 unsigned char sha1[20];1264 struct stat st;1265 int flag;1266 const char *refdir;12671268 if (de->d_name[0] == '.')1269 continue;1270 if (ends_with(de->d_name, ".lock"))1271 continue;1272 strbuf_addstr(&refname, de->d_name);1273 refdir = *refs->name1274 ? git_path_submodule(refs->name, "%s", refname.buf)1275 : git_path("%s", refname.buf);1276 if (stat(refdir, &st) < 0) {1277 ; /* silently ignore */1278 } else if (S_ISDIR(st.st_mode)) {1279 strbuf_addch(&refname, '/');1280 add_entry_to_dir(dir,1281 create_dir_entry(refs, refname.buf,1282 refname.len, 1));1283 } else {1284 int read_ok;12851286 if (*refs->name) {1287 hashclr(sha1);1288 flag = 0;1289 read_ok = !resolve_gitlink_ref(refs->name,1290 refname.buf, sha1);1291 } else {1292 read_ok = !read_ref_full(refname.buf,1293 RESOLVE_REF_READING,1294 sha1, &flag);1295 }12961297 if (!read_ok) {1298 hashclr(sha1);1299 flag |= REF_ISBROKEN;1300 }13011302 if (check_refname_format(refname.buf,1303 REFNAME_ALLOW_ONELEVEL)) {1304 hashclr(sha1);1305 flag |= REF_BAD_NAME | REF_ISBROKEN;1306 }1307 add_entry_to_dir(dir,1308 create_ref_entry(refname.buf, sha1, flag, 0));1309 }1310 strbuf_setlen(&refname, dirnamelen);1311 }1312 strbuf_release(&refname);1313 closedir(d);1314}13151316static struct ref_dir *get_loose_refs(struct ref_cache *refs)1317{1318 if (!refs->loose) {1319 /*1320 * Mark the top-level directory complete because we1321 * are about to read the only subdirectory that can1322 * hold references:1323 */1324 refs->loose = create_dir_entry(refs, "", 0, 0);1325 /*1326 * Create an incomplete entry for "refs/":1327 */1328 add_entry_to_dir(get_ref_dir(refs->loose),1329 create_dir_entry(refs, "refs/", 5, 1));1330 }1331 return get_ref_dir(refs->loose);1332}13331334/* We allow "recursive" symbolic refs. Only within reason, though */1335#define MAXDEPTH 51336#define MAXREFLEN (1024)13371338/*1339 * Called by resolve_gitlink_ref_recursive() after it failed to read1340 * from the loose refs in ref_cache refs. Find <refname> in the1341 * packed-refs file for the submodule.1342 */1343static int resolve_gitlink_packed_ref(struct ref_cache *refs,1344 const char *refname, unsigned char *sha1)1345{1346 struct ref_entry *ref;1347 struct ref_dir *dir = get_packed_refs(refs);13481349 ref = find_ref(dir, refname);1350 if (ref == NULL)1351 return -1;13521353 hashcpy(sha1, ref->u.value.sha1);1354 return 0;1355}13561357static int resolve_gitlink_ref_recursive(struct ref_cache *refs,1358 const char *refname, unsigned char *sha1,1359 int recursion)1360{1361 int fd, len;1362 char buffer[128], *p;1363 char *path;13641365 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)1366 return -1;1367 path = *refs->name1368 ? git_path_submodule(refs->name, "%s", refname)1369 : git_path("%s", refname);1370 fd = open(path, O_RDONLY);1371 if (fd < 0)1372 return resolve_gitlink_packed_ref(refs, refname, sha1);13731374 len = read(fd, buffer, sizeof(buffer)-1);1375 close(fd);1376 if (len < 0)1377 return -1;1378 while (len && isspace(buffer[len-1]))1379 len--;1380 buffer[len] = 0;13811382 /* Was it a detached head or an old-fashioned symlink? */1383 if (!get_sha1_hex(buffer, sha1))1384 return 0;13851386 /* Symref? */1387 if (strncmp(buffer, "ref:", 4))1388 return -1;1389 p = buffer + 4;1390 while (isspace(*p))1391 p++;13921393 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1394}13951396int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)1397{1398 int len = strlen(path), retval;1399 char *submodule;1400 struct ref_cache *refs;14011402 while (len && path[len-1] == '/')1403 len--;1404 if (!len)1405 return -1;1406 submodule = xstrndup(path, len);1407 refs = get_ref_cache(submodule);1408 free(submodule);14091410 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);1411 return retval;1412}14131414/*1415 * Return the ref_entry for the given refname from the packed1416 * references. If it does not exist, return NULL.1417 */1418static struct ref_entry *get_packed_ref(const char *refname)1419{1420 return find_ref(get_packed_refs(&ref_cache), refname);1421}14221423/*1424 * A loose ref file doesn't exist; check for a packed ref. The1425 * options are forwarded from resolve_safe_unsafe().1426 */1427static int resolve_missing_loose_ref(const char *refname,1428 int resolve_flags,1429 unsigned char *sha1,1430 int *flags)1431{1432 struct ref_entry *entry;14331434 /*1435 * The loose reference file does not exist; check for a packed1436 * reference.1437 */1438 entry = get_packed_ref(refname);1439 if (entry) {1440 hashcpy(sha1, entry->u.value.sha1);1441 if (flags)1442 *flags |= REF_ISPACKED;1443 return 0;1444 }1445 /* The reference is not a packed reference, either. */1446 if (resolve_flags & RESOLVE_REF_READING) {1447 errno = ENOENT;1448 return -1;1449 } else {1450 hashclr(sha1);1451 return 0;1452 }1453}14541455/* This function needs to return a meaningful errno on failure */1456const char *resolve_ref_unsafe(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)1457{1458 int depth = MAXDEPTH;1459 ssize_t len;1460 char buffer[256];1461 static char refname_buffer[256];1462 int bad_name = 0;14631464 if (flags)1465 *flags = 0;14661467 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1468 if (flags)1469 *flags |= REF_BAD_NAME;14701471 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1472 !refname_is_safe(refname)) {1473 errno = EINVAL;1474 return NULL;1475 }1476 /*1477 * dwim_ref() uses REF_ISBROKEN to distinguish between1478 * missing refs and refs that were present but invalid,1479 * to complain about the latter to stderr.1480 *1481 * We don't know whether the ref exists, so don't set1482 * REF_ISBROKEN yet.1483 */1484 bad_name = 1;1485 }1486 for (;;) {1487 char path[PATH_MAX];1488 struct stat st;1489 char *buf;1490 int fd;14911492 if (--depth < 0) {1493 errno = ELOOP;1494 return NULL;1495 }14961497 git_snpath(path, sizeof(path), "%s", refname);14981499 /*1500 * We might have to loop back here to avoid a race1501 * condition: first we lstat() the file, then we try1502 * to read it as a link or as a file. But if somebody1503 * changes the type of the file (file <-> directory1504 * <-> symlink) between the lstat() and reading, then1505 * we don't want to report that as an error but rather1506 * try again starting with the lstat().1507 */1508 stat_ref:1509 if (lstat(path, &st) < 0) {1510 if (errno != ENOENT)1511 return NULL;1512 if (resolve_missing_loose_ref(refname, resolve_flags,1513 sha1, flags))1514 return NULL;1515 if (bad_name) {1516 hashclr(sha1);1517 if (flags)1518 *flags |= REF_ISBROKEN;1519 }1520 return refname;1521 }15221523 /* Follow "normalized" - ie "refs/.." symlinks by hand */1524 if (S_ISLNK(st.st_mode)) {1525 len = readlink(path, buffer, sizeof(buffer)-1);1526 if (len < 0) {1527 if (errno == ENOENT || errno == EINVAL)1528 /* inconsistent with lstat; retry */1529 goto stat_ref;1530 else1531 return NULL;1532 }1533 buffer[len] = 0;1534 if (starts_with(buffer, "refs/") &&1535 !check_refname_format(buffer, 0)) {1536 strcpy(refname_buffer, buffer);1537 refname = refname_buffer;1538 if (flags)1539 *flags |= REF_ISSYMREF;1540 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1541 hashclr(sha1);1542 return refname;1543 }1544 continue;1545 }1546 }15471548 /* Is it a directory? */1549 if (S_ISDIR(st.st_mode)) {1550 errno = EISDIR;1551 return NULL;1552 }15531554 /*1555 * Anything else, just open it and try to use it as1556 * a ref1557 */1558 fd = open(path, O_RDONLY);1559 if (fd < 0) {1560 if (errno == ENOENT)1561 /* inconsistent with lstat; retry */1562 goto stat_ref;1563 else1564 return NULL;1565 }1566 len = read_in_full(fd, buffer, sizeof(buffer)-1);1567 if (len < 0) {1568 int save_errno = errno;1569 close(fd);1570 errno = save_errno;1571 return NULL;1572 }1573 close(fd);1574 while (len && isspace(buffer[len-1]))1575 len--;1576 buffer[len] = '\0';15771578 /*1579 * Is it a symbolic ref?1580 */1581 if (!starts_with(buffer, "ref:")) {1582 /*1583 * Please note that FETCH_HEAD has a second1584 * line containing other data.1585 */1586 if (get_sha1_hex(buffer, sha1) ||1587 (buffer[40] != '\0' && !isspace(buffer[40]))) {1588 if (flags)1589 *flags |= REF_ISBROKEN;1590 errno = EINVAL;1591 return NULL;1592 }1593 if (bad_name) {1594 hashclr(sha1);1595 if (flags)1596 *flags |= REF_ISBROKEN;1597 }1598 return refname;1599 }1600 if (flags)1601 *flags |= REF_ISSYMREF;1602 buf = buffer + 4;1603 while (isspace(*buf))1604 buf++;1605 refname = strcpy(refname_buffer, buf);1606 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1607 hashclr(sha1);1608 return refname;1609 }1610 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1611 if (flags)1612 *flags |= REF_ISBROKEN;16131614 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1615 !refname_is_safe(buf)) {1616 errno = EINVAL;1617 return NULL;1618 }1619 bad_name = 1;1620 }1621 }1622}16231624char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)1625{1626 return xstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1627}16281629/* The argument to filter_refs */1630struct ref_filter {1631 const char *pattern;1632 each_ref_fn *fn;1633 void *cb_data;1634};16351636int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)1637{1638 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1639 return 0;1640 return -1;1641}16421643int read_ref(const char *refname, unsigned char *sha1)1644{1645 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1646}16471648int ref_exists(const char *refname)1649{1650 unsigned char sha1[20];1651 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1652}16531654static int filter_refs(const char *refname, const unsigned char *sha1, int flags,1655 void *data)1656{1657 struct ref_filter *filter = (struct ref_filter *)data;1658 if (wildmatch(filter->pattern, refname, 0, NULL))1659 return 0;1660 return filter->fn(refname, sha1, flags, filter->cb_data);1661}16621663enum peel_status {1664 /* object was peeled successfully: */1665 PEEL_PEELED = 0,16661667 /*1668 * object cannot be peeled because the named object (or an1669 * object referred to by a tag in the peel chain), does not1670 * exist.1671 */1672 PEEL_INVALID = -1,16731674 /* object cannot be peeled because it is not a tag: */1675 PEEL_NON_TAG = -2,16761677 /* ref_entry contains no peeled value because it is a symref: */1678 PEEL_IS_SYMREF = -3,16791680 /*1681 * ref_entry cannot be peeled because it is broken (i.e., the1682 * symbolic reference cannot even be resolved to an object1683 * name):1684 */1685 PEEL_BROKEN = -41686};16871688/*1689 * Peel the named object; i.e., if the object is a tag, resolve the1690 * tag recursively until a non-tag is found. If successful, store the1691 * result to sha1 and return PEEL_PEELED. If the object is not a tag1692 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1693 * and leave sha1 unchanged.1694 */1695static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)1696{1697 struct object *o = lookup_unknown_object(name);16981699 if (o->type == OBJ_NONE) {1700 int type = sha1_object_info(name, NULL);1701 if (type < 0 || !object_as_type(o, type, 0))1702 return PEEL_INVALID;1703 }17041705 if (o->type != OBJ_TAG)1706 return PEEL_NON_TAG;17071708 o = deref_tag_noverify(o);1709 if (!o)1710 return PEEL_INVALID;17111712 hashcpy(sha1, o->sha1);1713 return PEEL_PEELED;1714}17151716/*1717 * Peel the entry (if possible) and return its new peel_status. If1718 * repeel is true, re-peel the entry even if there is an old peeled1719 * value that is already stored in it.1720 *1721 * It is OK to call this function with a packed reference entry that1722 * might be stale and might even refer to an object that has since1723 * been garbage-collected. In such a case, if the entry has1724 * REF_KNOWS_PEELED then leave the status unchanged and return1725 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1726 */1727static enum peel_status peel_entry(struct ref_entry *entry, int repeel)1728{1729 enum peel_status status;17301731 if (entry->flag & REF_KNOWS_PEELED) {1732 if (repeel) {1733 entry->flag &= ~REF_KNOWS_PEELED;1734 hashclr(entry->u.value.peeled);1735 } else {1736 return is_null_sha1(entry->u.value.peeled) ?1737 PEEL_NON_TAG : PEEL_PEELED;1738 }1739 }1740 if (entry->flag & REF_ISBROKEN)1741 return PEEL_BROKEN;1742 if (entry->flag & REF_ISSYMREF)1743 return PEEL_IS_SYMREF;17441745 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);1746 if (status == PEEL_PEELED || status == PEEL_NON_TAG)1747 entry->flag |= REF_KNOWS_PEELED;1748 return status;1749}17501751int peel_ref(const char *refname, unsigned char *sha1)1752{1753 int flag;1754 unsigned char base[20];17551756 if (current_ref && (current_ref->name == refname1757 || !strcmp(current_ref->name, refname))) {1758 if (peel_entry(current_ref, 0))1759 return -1;1760 hashcpy(sha1, current_ref->u.value.peeled);1761 return 0;1762 }17631764 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1765 return -1;17661767 /*1768 * If the reference is packed, read its ref_entry from the1769 * cache in the hope that we already know its peeled value.1770 * We only try this optimization on packed references because1771 * (a) forcing the filling of the loose reference cache could1772 * be expensive and (b) loose references anyway usually do not1773 * have REF_KNOWS_PEELED.1774 */1775 if (flag & REF_ISPACKED) {1776 struct ref_entry *r = get_packed_ref(refname);1777 if (r) {1778 if (peel_entry(r, 0))1779 return -1;1780 hashcpy(sha1, r->u.value.peeled);1781 return 0;1782 }1783 }17841785 return peel_object(base, sha1);1786}17871788struct warn_if_dangling_data {1789 FILE *fp;1790 const char *refname;1791 const struct string_list *refnames;1792 const char *msg_fmt;1793};17941795static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,1796 int flags, void *cb_data)1797{1798 struct warn_if_dangling_data *d = cb_data;1799 const char *resolves_to;1800 unsigned char junk[20];18011802 if (!(flags & REF_ISSYMREF))1803 return 0;18041805 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);1806 if (!resolves_to1807 || (d->refname1808 ? strcmp(resolves_to, d->refname)1809 : !string_list_has_string(d->refnames, resolves_to))) {1810 return 0;1811 }18121813 fprintf(d->fp, d->msg_fmt, refname);1814 fputc('\n', d->fp);1815 return 0;1816}18171818void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)1819{1820 struct warn_if_dangling_data data;18211822 data.fp = fp;1823 data.refname = refname;1824 data.refnames = NULL;1825 data.msg_fmt = msg_fmt;1826 for_each_rawref(warn_if_dangling_symref, &data);1827}18281829void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)1830{1831 struct warn_if_dangling_data data;18321833 data.fp = fp;1834 data.refname = NULL;1835 data.refnames = refnames;1836 data.msg_fmt = msg_fmt;1837 for_each_rawref(warn_if_dangling_symref, &data);1838}18391840/*1841 * Call fn for each reference in the specified ref_cache, omitting1842 * references not in the containing_dir of base. fn is called for all1843 * references, including broken ones. If fn ever returns a non-zero1844 * value, stop the iteration and return that value; otherwise, return1845 * 0.1846 */1847static int do_for_each_entry(struct ref_cache *refs, const char *base,1848 each_ref_entry_fn fn, void *cb_data)1849{1850 struct packed_ref_cache *packed_ref_cache;1851 struct ref_dir *loose_dir;1852 struct ref_dir *packed_dir;1853 int retval = 0;18541855 /*1856 * We must make sure that all loose refs are read before accessing the1857 * packed-refs file; this avoids a race condition in which loose refs1858 * are migrated to the packed-refs file by a simultaneous process, but1859 * our in-memory view is from before the migration. get_packed_ref_cache()1860 * takes care of making sure our view is up to date with what is on1861 * disk.1862 */1863 loose_dir = get_loose_refs(refs);1864 if (base && *base) {1865 loose_dir = find_containing_dir(loose_dir, base, 0);1866 }1867 if (loose_dir)1868 prime_ref_dir(loose_dir);18691870 packed_ref_cache = get_packed_ref_cache(refs);1871 acquire_packed_ref_cache(packed_ref_cache);1872 packed_dir = get_packed_ref_dir(packed_ref_cache);1873 if (base && *base) {1874 packed_dir = find_containing_dir(packed_dir, base, 0);1875 }18761877 if (packed_dir && loose_dir) {1878 sort_ref_dir(packed_dir);1879 sort_ref_dir(loose_dir);1880 retval = do_for_each_entry_in_dirs(1881 packed_dir, loose_dir, fn, cb_data);1882 } else if (packed_dir) {1883 sort_ref_dir(packed_dir);1884 retval = do_for_each_entry_in_dir(1885 packed_dir, 0, fn, cb_data);1886 } else if (loose_dir) {1887 sort_ref_dir(loose_dir);1888 retval = do_for_each_entry_in_dir(1889 loose_dir, 0, fn, cb_data);1890 }18911892 release_packed_ref_cache(packed_ref_cache);1893 return retval;1894}18951896/*1897 * Call fn for each reference in the specified ref_cache for which the1898 * refname begins with base. If trim is non-zero, then trim that many1899 * characters off the beginning of each refname before passing the1900 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1901 * broken references in the iteration. If fn ever returns a non-zero1902 * value, stop the iteration and return that value; otherwise, return1903 * 0.1904 */1905static int do_for_each_ref(struct ref_cache *refs, const char *base,1906 each_ref_fn fn, int trim, int flags, void *cb_data)1907{1908 struct ref_entry_cb data;1909 data.base = base;1910 data.trim = trim;1911 data.flags = flags;1912 data.fn = fn;1913 data.cb_data = cb_data;19141915 if (ref_paranoia < 0)1916 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);1917 if (ref_paranoia)1918 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;19191920 return do_for_each_entry(refs, base, do_one_ref, &data);1921}19221923static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)1924{1925 unsigned char sha1[20];1926 int flag;19271928 if (submodule) {1929 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)1930 return fn("HEAD", sha1, 0, cb_data);19311932 return 0;1933 }19341935 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1936 return fn("HEAD", sha1, flag, cb_data);19371938 return 0;1939}19401941int head_ref(each_ref_fn fn, void *cb_data)1942{1943 return do_head_ref(NULL, fn, cb_data);1944}19451946int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1947{1948 return do_head_ref(submodule, fn, cb_data);1949}19501951int for_each_ref(each_ref_fn fn, void *cb_data)1952{1953 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);1954}19551956int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1957{1958 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);1959}19601961int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)1962{1963 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);1964}19651966int for_each_ref_in_submodule(const char *submodule, const char *prefix,1967 each_ref_fn fn, void *cb_data)1968{1969 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);1970}19711972int for_each_tag_ref(each_ref_fn fn, void *cb_data)1973{1974 return for_each_ref_in("refs/tags/", fn, cb_data);1975}19761977int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1978{1979 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);1980}19811982int for_each_branch_ref(each_ref_fn fn, void *cb_data)1983{1984 return for_each_ref_in("refs/heads/", fn, cb_data);1985}19861987int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1988{1989 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);1990}19911992int for_each_remote_ref(each_ref_fn fn, void *cb_data)1993{1994 return for_each_ref_in("refs/remotes/", fn, cb_data);1995}19961997int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1998{1999 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);2000}20012002int for_each_replace_ref(each_ref_fn fn, void *cb_data)2003{2004 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);2005}20062007int head_ref_namespaced(each_ref_fn fn, void *cb_data)2008{2009 struct strbuf buf = STRBUF_INIT;2010 int ret = 0;2011 unsigned char sha1[20];2012 int flag;20132014 strbuf_addf(&buf, "%sHEAD", get_git_namespace());2015 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2016 ret = fn(buf.buf, sha1, flag, cb_data);2017 strbuf_release(&buf);20182019 return ret;2020}20212022int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)2023{2024 struct strbuf buf = STRBUF_INIT;2025 int ret;2026 strbuf_addf(&buf, "%srefs/", get_git_namespace());2027 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);2028 strbuf_release(&buf);2029 return ret;2030}20312032int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,2033 const char *prefix, void *cb_data)2034{2035 struct strbuf real_pattern = STRBUF_INIT;2036 struct ref_filter filter;2037 int ret;20382039 if (!prefix && !starts_with(pattern, "refs/"))2040 strbuf_addstr(&real_pattern, "refs/");2041 else if (prefix)2042 strbuf_addstr(&real_pattern, prefix);2043 strbuf_addstr(&real_pattern, pattern);20442045 if (!has_glob_specials(pattern)) {2046 /* Append implied '/' '*' if not present. */2047 if (real_pattern.buf[real_pattern.len - 1] != '/')2048 strbuf_addch(&real_pattern, '/');2049 /* No need to check for '*', there is none. */2050 strbuf_addch(&real_pattern, '*');2051 }20522053 filter.pattern = real_pattern.buf;2054 filter.fn = fn;2055 filter.cb_data = cb_data;2056 ret = for_each_ref(filter_refs, &filter);20572058 strbuf_release(&real_pattern);2059 return ret;2060}20612062int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)2063{2064 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);2065}20662067int for_each_rawref(each_ref_fn fn, void *cb_data)2068{2069 return do_for_each_ref(&ref_cache, "", fn, 0,2070 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2071}20722073const char *prettify_refname(const char *name)2074{2075 return name + (2076 starts_with(name, "refs/heads/") ? 11 :2077 starts_with(name, "refs/tags/") ? 10 :2078 starts_with(name, "refs/remotes/") ? 13 :2079 0);2080}20812082static const char *ref_rev_parse_rules[] = {2083 "%.*s",2084 "refs/%.*s",2085 "refs/tags/%.*s",2086 "refs/heads/%.*s",2087 "refs/remotes/%.*s",2088 "refs/remotes/%.*s/HEAD",2089 NULL2090};20912092int refname_match(const char *abbrev_name, const char *full_name)2093{2094 const char **p;2095 const int abbrev_name_len = strlen(abbrev_name);20962097 for (p = ref_rev_parse_rules; *p; p++) {2098 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {2099 return 1;2100 }2101 }21022103 return 0;2104}21052106/* This function should make sure errno is meaningful on error */2107static struct ref_lock *verify_lock(struct ref_lock *lock,2108 const unsigned char *old_sha1, int mustexist)2109{2110 if (read_ref_full(lock->ref_name,2111 mustexist ? RESOLVE_REF_READING : 0,2112 lock->old_sha1, NULL)) {2113 int save_errno = errno;2114 error("Can't verify ref %s", lock->ref_name);2115 unlock_ref(lock);2116 errno = save_errno;2117 return NULL;2118 }2119 if (hashcmp(lock->old_sha1, old_sha1)) {2120 error("Ref %s is at %s but expected %s", lock->ref_name,2121 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));2122 unlock_ref(lock);2123 errno = EBUSY;2124 return NULL;2125 }2126 return lock;2127}21282129static int remove_empty_directories(const char *file)2130{2131 /* we want to create a file but there is a directory there;2132 * if that is an empty directory (or a directory that contains2133 * only empty directories), remove them.2134 */2135 struct strbuf path;2136 int result, save_errno;21372138 strbuf_init(&path, 20);2139 strbuf_addstr(&path, file);21402141 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2142 save_errno = errno;21432144 strbuf_release(&path);2145 errno = save_errno;21462147 return result;2148}21492150/*2151 * *string and *len will only be substituted, and *string returned (for2152 * later free()ing) if the string passed in is a magic short-hand form2153 * to name a branch.2154 */2155static char *substitute_branch_name(const char **string, int *len)2156{2157 struct strbuf buf = STRBUF_INIT;2158 int ret = interpret_branch_name(*string, *len, &buf);21592160 if (ret == *len) {2161 size_t size;2162 *string = strbuf_detach(&buf, &size);2163 *len = size;2164 return (char *)*string;2165 }21662167 return NULL;2168}21692170int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)2171{2172 char *last_branch = substitute_branch_name(&str, &len);2173 const char **p, *r;2174 int refs_found = 0;21752176 *ref = NULL;2177 for (p = ref_rev_parse_rules; *p; p++) {2178 char fullref[PATH_MAX];2179 unsigned char sha1_from_ref[20];2180 unsigned char *this_result;2181 int flag;21822183 this_result = refs_found ? sha1_from_ref : sha1;2184 mksnpath(fullref, sizeof(fullref), *p, len, str);2185 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2186 this_result, &flag);2187 if (r) {2188 if (!refs_found++)2189 *ref = xstrdup(r);2190 if (!warn_ambiguous_refs)2191 break;2192 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {2193 warning("ignoring dangling symref %s.", fullref);2194 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {2195 warning("ignoring broken ref %s.", fullref);2196 }2197 }2198 free(last_branch);2199 return refs_found;2200}22012202int dwim_log(const char *str, int len, unsigned char *sha1, char **log)2203{2204 char *last_branch = substitute_branch_name(&str, &len);2205 const char **p;2206 int logs_found = 0;22072208 *log = NULL;2209 for (p = ref_rev_parse_rules; *p; p++) {2210 unsigned char hash[20];2211 char path[PATH_MAX];2212 const char *ref, *it;22132214 mksnpath(path, sizeof(path), *p, len, str);2215 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,2216 hash, NULL);2217 if (!ref)2218 continue;2219 if (reflog_exists(path))2220 it = path;2221 else if (strcmp(ref, path) && reflog_exists(ref))2222 it = ref;2223 else2224 continue;2225 if (!logs_found++) {2226 *log = xstrdup(it);2227 hashcpy(sha1, hash);2228 }2229 if (!warn_ambiguous_refs)2230 break;2231 }2232 free(last_branch);2233 return logs_found;2234}22352236/*2237 * Locks a ref returning the lock on success and NULL on failure.2238 * On failure errno is set to something meaningful.2239 */2240static struct ref_lock *lock_ref_sha1_basic(const char *refname,2241 const unsigned char *old_sha1,2242 const struct string_list *skip,2243 int flags, int *type_p)2244{2245 char *ref_file;2246 const char *orig_refname = refname;2247 struct ref_lock *lock;2248 int last_errno = 0;2249 int type, lflags;2250 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2251 int resolve_flags = 0;2252 int missing = 0;2253 int attempts_remaining = 3;22542255 lock = xcalloc(1, sizeof(struct ref_lock));2256 lock->lock_fd = -1;22572258 if (mustexist)2259 resolve_flags |= RESOLVE_REF_READING;2260 if (flags & REF_DELETING) {2261 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2262 if (flags & REF_NODEREF)2263 resolve_flags |= RESOLVE_REF_NO_RECURSE;2264 }22652266 refname = resolve_ref_unsafe(refname, resolve_flags,2267 lock->old_sha1, &type);2268 if (!refname && errno == EISDIR) {2269 /* we are trying to lock foo but we used to2270 * have foo/bar which now does not exist;2271 * it is normal for the empty directory 'foo'2272 * to remain.2273 */2274 ref_file = git_path("%s", orig_refname);2275 if (remove_empty_directories(ref_file)) {2276 last_errno = errno;2277 error("there are still refs under '%s'", orig_refname);2278 goto error_return;2279 }2280 refname = resolve_ref_unsafe(orig_refname, resolve_flags,2281 lock->old_sha1, &type);2282 }2283 if (type_p)2284 *type_p = type;2285 if (!refname) {2286 last_errno = errno;2287 error("unable to resolve reference %s: %s",2288 orig_refname, strerror(errno));2289 goto error_return;2290 }2291 missing = is_null_sha1(lock->old_sha1);2292 /* When the ref did not exist and we are creating it,2293 * make sure there is no existing ref that is packed2294 * whose name begins with our refname, nor a ref whose2295 * name is a proper prefix of our refname.2296 */2297 if (missing &&2298 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {2299 last_errno = ENOTDIR;2300 goto error_return;2301 }23022303 lock->lk = xcalloc(1, sizeof(struct lock_file));23042305 lflags = 0;2306 if (flags & REF_NODEREF) {2307 refname = orig_refname;2308 lflags |= LOCK_NO_DEREF;2309 }2310 lock->ref_name = xstrdup(refname);2311 lock->orig_ref_name = xstrdup(orig_refname);2312 ref_file = git_path("%s", refname);2313 if (missing)2314 lock->force_write = 1;2315 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))2316 lock->force_write = 1;23172318 retry:2319 switch (safe_create_leading_directories(ref_file)) {2320 case SCLD_OK:2321 break; /* success */2322 case SCLD_VANISHED:2323 if (--attempts_remaining > 0)2324 goto retry;2325 /* fall through */2326 default:2327 last_errno = errno;2328 error("unable to create directory for %s", ref_file);2329 goto error_return;2330 }23312332 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);2333 if (lock->lock_fd < 0) {2334 last_errno = errno;2335 if (errno == ENOENT && --attempts_remaining > 0)2336 /*2337 * Maybe somebody just deleted one of the2338 * directories leading to ref_file. Try2339 * again:2340 */2341 goto retry;2342 else {2343 struct strbuf err = STRBUF_INIT;2344 unable_to_lock_message(ref_file, errno, &err);2345 error("%s", err.buf);2346 strbuf_release(&err);2347 goto error_return;2348 }2349 }2350 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;23512352 error_return:2353 unlock_ref(lock);2354 errno = last_errno;2355 return NULL;2356}23572358struct ref_lock *lock_any_ref_for_update(const char *refname,2359 const unsigned char *old_sha1,2360 int flags, int *type_p)2361{2362 return lock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);2363}23642365/*2366 * Write an entry to the packed-refs file for the specified refname.2367 * If peeled is non-NULL, write it as the entry's peeled value.2368 */2369static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,2370 unsigned char *peeled)2371{2372 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);2373 if (peeled)2374 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));2375}23762377/*2378 * An each_ref_entry_fn that writes the entry to a packed-refs file.2379 */2380static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)2381{2382 enum peel_status peel_status = peel_entry(entry, 0);23832384 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2385 error("internal error: %s is not a valid packed reference!",2386 entry->name);2387 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2388 peel_status == PEEL_PEELED ?2389 entry->u.value.peeled : NULL);2390 return 0;2391}23922393/* This should return a meaningful errno on failure */2394int lock_packed_refs(int flags)2395{2396 struct packed_ref_cache *packed_ref_cache;23972398 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)2399 return -1;2400 /*2401 * Get the current packed-refs while holding the lock. If the2402 * packed-refs file has been modified since we last read it,2403 * this will automatically invalidate the cache and re-read2404 * the packed-refs file.2405 */2406 packed_ref_cache = get_packed_ref_cache(&ref_cache);2407 packed_ref_cache->lock = &packlock;2408 /* Increment the reference count to prevent it from being freed: */2409 acquire_packed_ref_cache(packed_ref_cache);2410 return 0;2411}24122413/*2414 * Commit the packed refs changes.2415 * On error we must make sure that errno contains a meaningful value.2416 */2417int commit_packed_refs(void)2418{2419 struct packed_ref_cache *packed_ref_cache =2420 get_packed_ref_cache(&ref_cache);2421 int error = 0;2422 int save_errno = 0;2423 FILE *out;24242425 if (!packed_ref_cache->lock)2426 die("internal error: packed-refs not locked");24272428 out = fdopen_lock_file(packed_ref_cache->lock, "w");2429 if (!out)2430 die_errno("unable to fdopen packed-refs descriptor");24312432 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);2433 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),2434 0, write_packed_entry_fn, out);24352436 if (commit_lock_file(packed_ref_cache->lock)) {2437 save_errno = errno;2438 error = -1;2439 }2440 packed_ref_cache->lock = NULL;2441 release_packed_ref_cache(packed_ref_cache);2442 errno = save_errno;2443 return error;2444}24452446void rollback_packed_refs(void)2447{2448 struct packed_ref_cache *packed_ref_cache =2449 get_packed_ref_cache(&ref_cache);24502451 if (!packed_ref_cache->lock)2452 die("internal error: packed-refs not locked");2453 rollback_lock_file(packed_ref_cache->lock);2454 packed_ref_cache->lock = NULL;2455 release_packed_ref_cache(packed_ref_cache);2456 clear_packed_ref_cache(&ref_cache);2457}24582459struct ref_to_prune {2460 struct ref_to_prune *next;2461 unsigned char sha1[20];2462 char name[FLEX_ARRAY];2463};24642465struct pack_refs_cb_data {2466 unsigned int flags;2467 struct ref_dir *packed_refs;2468 struct ref_to_prune *ref_to_prune;2469};24702471/*2472 * An each_ref_entry_fn that is run over loose references only. If2473 * the loose reference can be packed, add an entry in the packed ref2474 * cache. If the reference should be pruned, also add it to2475 * ref_to_prune in the pack_refs_cb_data.2476 */2477static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)2478{2479 struct pack_refs_cb_data *cb = cb_data;2480 enum peel_status peel_status;2481 struct ref_entry *packed_entry;2482 int is_tag_ref = starts_with(entry->name, "refs/tags/");24832484 /* ALWAYS pack tags */2485 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2486 return 0;24872488 /* Do not pack symbolic or broken refs: */2489 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2490 return 0;24912492 /* Add a packed ref cache entry equivalent to the loose entry. */2493 peel_status = peel_entry(entry, 1);2494 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2495 die("internal error peeling reference %s (%s)",2496 entry->name, sha1_to_hex(entry->u.value.sha1));2497 packed_entry = find_ref(cb->packed_refs, entry->name);2498 if (packed_entry) {2499 /* Overwrite existing packed entry with info from loose entry */2500 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2501 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2502 } else {2503 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,2504 REF_ISPACKED | REF_KNOWS_PEELED, 0);2505 add_ref(cb->packed_refs, packed_entry);2506 }2507 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25082509 /* Schedule the loose reference for pruning if requested. */2510 if ((cb->flags & PACK_REFS_PRUNE)) {2511 int namelen = strlen(entry->name) + 1;2512 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);2513 hashcpy(n->sha1, entry->u.value.sha1);2514 strcpy(n->name, entry->name);2515 n->next = cb->ref_to_prune;2516 cb->ref_to_prune = n;2517 }2518 return 0;2519}25202521/*2522 * Remove empty parents, but spare refs/ and immediate subdirs.2523 * Note: munges *name.2524 */2525static void try_remove_empty_parents(char *name)2526{2527 char *p, *q;2528 int i;2529 p = name;2530 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */2531 while (*p && *p != '/')2532 p++;2533 /* tolerate duplicate slashes; see check_refname_format() */2534 while (*p == '/')2535 p++;2536 }2537 for (q = p; *q; q++)2538 ;2539 while (1) {2540 while (q > p && *q != '/')2541 q--;2542 while (q > p && *(q-1) == '/')2543 q--;2544 if (q == p)2545 break;2546 *q = '\0';2547 if (rmdir(git_path("%s", name)))2548 break;2549 }2550}25512552/* make sure nobody touched the ref, and unlink */2553static void prune_ref(struct ref_to_prune *r)2554{2555 struct ref_transaction *transaction;2556 struct strbuf err = STRBUF_INIT;25572558 if (check_refname_format(r->name, 0))2559 return;25602561 transaction = ref_transaction_begin(&err);2562 if (!transaction ||2563 ref_transaction_delete(transaction, r->name, r->sha1,2564 REF_ISPRUNING, 1, NULL, &err) ||2565 ref_transaction_commit(transaction, &err)) {2566 ref_transaction_free(transaction);2567 error("%s", err.buf);2568 strbuf_release(&err);2569 return;2570 }2571 ref_transaction_free(transaction);2572 strbuf_release(&err);2573 try_remove_empty_parents(r->name);2574}25752576static void prune_refs(struct ref_to_prune *r)2577{2578 while (r) {2579 prune_ref(r);2580 r = r->next;2581 }2582}25832584int pack_refs(unsigned int flags)2585{2586 struct pack_refs_cb_data cbdata;25872588 memset(&cbdata, 0, sizeof(cbdata));2589 cbdata.flags = flags;25902591 lock_packed_refs(LOCK_DIE_ON_ERROR);2592 cbdata.packed_refs = get_packed_refs(&ref_cache);25932594 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,2595 pack_if_possible_fn, &cbdata);25962597 if (commit_packed_refs())2598 die_errno("unable to overwrite old ref-pack file");25992600 prune_refs(cbdata.ref_to_prune);2601 return 0;2602}26032604int repack_without_refs(struct string_list *refnames, struct strbuf *err)2605{2606 struct ref_dir *packed;2607 struct string_list_item *refname;2608 int ret, needs_repacking = 0, removed = 0;26092610 assert(err);26112612 /* Look for a packed ref */2613 for_each_string_list_item(refname, refnames) {2614 if (get_packed_ref(refname->string)) {2615 needs_repacking = 1;2616 break;2617 }2618 }26192620 /* Avoid locking if we have nothing to do */2621 if (!needs_repacking)2622 return 0; /* no refname exists in packed refs */26232624 if (lock_packed_refs(0)) {2625 unable_to_lock_message(git_path("packed-refs"), errno, err);2626 return -1;2627 }2628 packed = get_packed_refs(&ref_cache);26292630 /* Remove refnames from the cache */2631 for_each_string_list_item(refname, refnames)2632 if (remove_entry(packed, refname->string) != -1)2633 removed = 1;2634 if (!removed) {2635 /*2636 * All packed entries disappeared while we were2637 * acquiring the lock.2638 */2639 rollback_packed_refs();2640 return 0;2641 }26422643 /* Write what remains */2644 ret = commit_packed_refs();2645 if (ret)2646 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",2647 strerror(errno));2648 return ret;2649}26502651static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)2652{2653 assert(err);26542655 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2656 /*2657 * loose. The loose file name is the same as the2658 * lockfile name, minus ".lock":2659 */2660 char *loose_filename = get_locked_file_path(lock->lk);2661 int res = unlink_or_msg(loose_filename, err);2662 free(loose_filename);2663 if (res)2664 return 1;2665 }2666 return 0;2667}26682669int delete_ref(const char *refname, const unsigned char *sha1, int delopt)2670{2671 struct ref_transaction *transaction;2672 struct strbuf err = STRBUF_INIT;26732674 transaction = ref_transaction_begin(&err);2675 if (!transaction ||2676 ref_transaction_delete(transaction, refname, sha1, delopt,2677 sha1 && !is_null_sha1(sha1), NULL, &err) ||2678 ref_transaction_commit(transaction, &err)) {2679 error("%s", err.buf);2680 ref_transaction_free(transaction);2681 strbuf_release(&err);2682 return 1;2683 }2684 ref_transaction_free(transaction);2685 strbuf_release(&err);2686 return 0;2687}26882689/*2690 * People using contrib's git-new-workdir have .git/logs/refs ->2691 * /some/other/path/.git/logs/refs, and that may live on another device.2692 *2693 * IOW, to avoid cross device rename errors, the temporary renamed log must2694 * live into logs/refs.2695 */2696#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"26972698static int rename_tmp_log(const char *newrefname)2699{2700 int attempts_remaining = 4;27012702 retry:2703 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {2704 case SCLD_OK:2705 break; /* success */2706 case SCLD_VANISHED:2707 if (--attempts_remaining > 0)2708 goto retry;2709 /* fall through */2710 default:2711 error("unable to create directory for %s", newrefname);2712 return -1;2713 }27142715 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {2716 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {2717 /*2718 * rename(a, b) when b is an existing2719 * directory ought to result in ISDIR, but2720 * Solaris 5.8 gives ENOTDIR. Sheesh.2721 */2722 if (remove_empty_directories(git_path("logs/%s", newrefname))) {2723 error("Directory not empty: logs/%s", newrefname);2724 return -1;2725 }2726 goto retry;2727 } else if (errno == ENOENT && --attempts_remaining > 0) {2728 /*2729 * Maybe another process just deleted one of2730 * the directories in the path to newrefname.2731 * Try again from the beginning.2732 */2733 goto retry;2734 } else {2735 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",2736 newrefname, strerror(errno));2737 return -1;2738 }2739 }2740 return 0;2741}27422743static int rename_ref_available(const char *oldname, const char *newname)2744{2745 struct string_list skip = STRING_LIST_INIT_NODUP;2746 int ret;27472748 string_list_insert(&skip, oldname);2749 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))2750 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));2751 string_list_clear(&skip, 0);2752 return ret;2753}27542755static int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1,2756 const char *logmsg);27572758int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)2759{2760 unsigned char sha1[20], orig_sha1[20];2761 int flag = 0, logmoved = 0;2762 struct ref_lock *lock;2763 struct stat loginfo;2764 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2765 const char *symref = NULL;27662767 if (log && S_ISLNK(loginfo.st_mode))2768 return error("reflog for %s is a symlink", oldrefname);27692770 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2771 orig_sha1, &flag);2772 if (flag & REF_ISSYMREF)2773 return error("refname %s is a symbolic ref, renaming it is not supported",2774 oldrefname);2775 if (!symref)2776 return error("refname %s not found", oldrefname);27772778 if (!rename_ref_available(oldrefname, newrefname))2779 return 1;27802781 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))2782 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",2783 oldrefname, strerror(errno));27842785 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2786 error("unable to delete old %s", oldrefname);2787 goto rollback;2788 }27892790 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2791 delete_ref(newrefname, sha1, REF_NODEREF)) {2792 if (errno==EISDIR) {2793 if (remove_empty_directories(git_path("%s", newrefname))) {2794 error("Directory not empty: %s", newrefname);2795 goto rollback;2796 }2797 } else {2798 error("unable to delete existing %s", newrefname);2799 goto rollback;2800 }2801 }28022803 if (log && rename_tmp_log(newrefname))2804 goto rollback;28052806 logmoved = log;28072808 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);2809 if (!lock) {2810 error("unable to lock %s for update", newrefname);2811 goto rollback;2812 }2813 lock->force_write = 1;2814 hashcpy(lock->old_sha1, orig_sha1);2815 if (write_ref_sha1(lock, orig_sha1, logmsg)) {2816 error("unable to write current sha1 into %s", newrefname);2817 goto rollback;2818 }28192820 return 0;28212822 rollback:2823 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);2824 if (!lock) {2825 error("unable to lock %s for rollback", oldrefname);2826 goto rollbacklog;2827 }28282829 lock->force_write = 1;2830 flag = log_all_ref_updates;2831 log_all_ref_updates = 0;2832 if (write_ref_sha1(lock, orig_sha1, NULL))2833 error("unable to write current sha1 into %s", oldrefname);2834 log_all_ref_updates = flag;28352836 rollbacklog:2837 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))2838 error("unable to restore logfile %s from %s: %s",2839 oldrefname, newrefname, strerror(errno));2840 if (!logmoved && log &&2841 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))2842 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",2843 oldrefname, strerror(errno));28442845 return 1;2846}28472848int close_ref(struct ref_lock *lock)2849{2850 if (close_lock_file(lock->lk))2851 return -1;2852 lock->lock_fd = -1;2853 return 0;2854}28552856int commit_ref(struct ref_lock *lock)2857{2858 if (commit_lock_file(lock->lk))2859 return -1;2860 lock->lock_fd = -1;2861 return 0;2862}28632864void unlock_ref(struct ref_lock *lock)2865{2866 /* Do not free lock->lk -- atexit() still looks at them */2867 if (lock->lk)2868 rollback_lock_file(lock->lk);2869 free(lock->ref_name);2870 free(lock->orig_ref_name);2871 free(lock);2872}28732874/*2875 * copy the reflog message msg to buf, which has been allocated sufficiently2876 * large, while cleaning up the whitespaces. Especially, convert LF to space,2877 * because reflog file is one line per entry.2878 */2879static int copy_msg(char *buf, const char *msg)2880{2881 char *cp = buf;2882 char c;2883 int wasspace = 1;28842885 *cp++ = '\t';2886 while ((c = *msg++)) {2887 if (wasspace && isspace(c))2888 continue;2889 wasspace = isspace(c);2890 if (wasspace)2891 c = ' ';2892 *cp++ = c;2893 }2894 while (buf < cp && isspace(cp[-1]))2895 cp--;2896 *cp++ = '\n';2897 return cp - buf;2898}28992900/* This function must set a meaningful errno on failure */2901int log_ref_setup(const char *refname, char *logfile, int bufsize)2902{2903 int logfd, oflags = O_APPEND | O_WRONLY;29042905 git_snpath(logfile, bufsize, "logs/%s", refname);2906 if (log_all_ref_updates &&2907 (starts_with(refname, "refs/heads/") ||2908 starts_with(refname, "refs/remotes/") ||2909 starts_with(refname, "refs/notes/") ||2910 !strcmp(refname, "HEAD"))) {2911 if (safe_create_leading_directories(logfile) < 0) {2912 int save_errno = errno;2913 error("unable to create directory for %s", logfile);2914 errno = save_errno;2915 return -1;2916 }2917 oflags |= O_CREAT;2918 }29192920 logfd = open(logfile, oflags, 0666);2921 if (logfd < 0) {2922 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2923 return 0;29242925 if (errno == EISDIR) {2926 if (remove_empty_directories(logfile)) {2927 int save_errno = errno;2928 error("There are still logs under '%s'",2929 logfile);2930 errno = save_errno;2931 return -1;2932 }2933 logfd = open(logfile, oflags, 0666);2934 }29352936 if (logfd < 0) {2937 int save_errno = errno;2938 error("Unable to append to %s: %s", logfile,2939 strerror(errno));2940 errno = save_errno;2941 return -1;2942 }2943 }29442945 adjust_shared_perm(logfile);2946 close(logfd);2947 return 0;2948}29492950static int log_ref_write(const char *refname, const unsigned char *old_sha1,2951 const unsigned char *new_sha1, const char *msg)2952{2953 int logfd, result, written, oflags = O_APPEND | O_WRONLY;2954 unsigned maxlen, len;2955 int msglen;2956 char log_file[PATH_MAX];2957 char *logrec;2958 const char *committer;29592960 if (log_all_ref_updates < 0)2961 log_all_ref_updates = !is_bare_repository();29622963 result = log_ref_setup(refname, log_file, sizeof(log_file));2964 if (result)2965 return result;29662967 logfd = open(log_file, oflags);2968 if (logfd < 0)2969 return 0;2970 msglen = msg ? strlen(msg) : 0;2971 committer = git_committer_info(0);2972 maxlen = strlen(committer) + msglen + 100;2973 logrec = xmalloc(maxlen);2974 len = sprintf(logrec, "%s %s %s\n",2975 sha1_to_hex(old_sha1),2976 sha1_to_hex(new_sha1),2977 committer);2978 if (msglen)2979 len += copy_msg(logrec + len - 1, msg) - 1;2980 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;2981 free(logrec);2982 if (written != len) {2983 int save_errno = errno;2984 close(logfd);2985 error("Unable to append to %s", log_file);2986 errno = save_errno;2987 return -1;2988 }2989 if (close(logfd)) {2990 int save_errno = errno;2991 error("Unable to append to %s", log_file);2992 errno = save_errno;2993 return -1;2994 }2995 return 0;2996}29972998int is_branch(const char *refname)2999{3000 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");3001}30023003/*3004 * Write sha1 into the ref specified by the lock. Make sure that errno3005 * is sane on error.3006 */3007static int write_ref_sha1(struct ref_lock *lock,3008 const unsigned char *sha1, const char *logmsg)3009{3010 static char term = '\n';3011 struct object *o;30123013 if (!lock) {3014 errno = EINVAL;3015 return -1;3016 }3017 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3018 unlock_ref(lock);3019 return 0;3020 }3021 o = parse_object(sha1);3022 if (!o) {3023 error("Trying to write ref %s with nonexistent object %s",3024 lock->ref_name, sha1_to_hex(sha1));3025 unlock_ref(lock);3026 errno = EINVAL;3027 return -1;3028 }3029 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {3030 error("Trying to write non-commit object %s to branch %s",3031 sha1_to_hex(sha1), lock->ref_name);3032 unlock_ref(lock);3033 errno = EINVAL;3034 return -1;3035 }3036 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||3037 write_in_full(lock->lock_fd, &term, 1) != 1 ||3038 close_ref(lock) < 0) {3039 int save_errno = errno;3040 error("Couldn't write %s", lock->lk->filename.buf);3041 unlock_ref(lock);3042 errno = save_errno;3043 return -1;3044 }3045 clear_loose_ref_cache(&ref_cache);3046 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||3047 (strcmp(lock->ref_name, lock->orig_ref_name) &&3048 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {3049 unlock_ref(lock);3050 return -1;3051 }3052 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {3053 /*3054 * Special hack: If a branch is updated directly and HEAD3055 * points to it (may happen on the remote side of a push3056 * for example) then logically the HEAD reflog should be3057 * updated too.3058 * A generic solution implies reverse symref information,3059 * but finding all symrefs pointing to the given branch3060 * would be rather costly for this rare event (the direct3061 * update of a branch) to be worth it. So let's cheat and3062 * check with HEAD only which should cover 99% of all usage3063 * scenarios (even 100% of the default ones).3064 */3065 unsigned char head_sha1[20];3066 int head_flag;3067 const char *head_ref;3068 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3069 head_sha1, &head_flag);3070 if (head_ref && (head_flag & REF_ISSYMREF) &&3071 !strcmp(head_ref, lock->ref_name))3072 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3073 }3074 if (commit_ref(lock)) {3075 error("Couldn't set %s", lock->ref_name);3076 unlock_ref(lock);3077 return -1;3078 }3079 unlock_ref(lock);3080 return 0;3081}30823083int create_symref(const char *ref_target, const char *refs_heads_master,3084 const char *logmsg)3085{3086 const char *lockpath;3087 char ref[1000];3088 int fd, len, written;3089 char *git_HEAD = git_pathdup("%s", ref_target);3090 unsigned char old_sha1[20], new_sha1[20];30913092 if (logmsg && read_ref(ref_target, old_sha1))3093 hashclr(old_sha1);30943095 if (safe_create_leading_directories(git_HEAD) < 0)3096 return error("unable to create directory for %s", git_HEAD);30973098#ifndef NO_SYMLINK_HEAD3099 if (prefer_symlink_refs) {3100 unlink(git_HEAD);3101 if (!symlink(refs_heads_master, git_HEAD))3102 goto done;3103 fprintf(stderr, "no symlink - falling back to symbolic ref\n");3104 }3105#endif31063107 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);3108 if (sizeof(ref) <= len) {3109 error("refname too long: %s", refs_heads_master);3110 goto error_free_return;3111 }3112 lockpath = mkpath("%s.lock", git_HEAD);3113 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);3114 if (fd < 0) {3115 error("Unable to open %s for writing", lockpath);3116 goto error_free_return;3117 }3118 written = write_in_full(fd, ref, len);3119 if (close(fd) != 0 || written != len) {3120 error("Unable to write to %s", lockpath);3121 goto error_unlink_return;3122 }3123 if (rename(lockpath, git_HEAD) < 0) {3124 error("Unable to create %s", git_HEAD);3125 goto error_unlink_return;3126 }3127 if (adjust_shared_perm(git_HEAD)) {3128 error("Unable to fix permissions on %s", lockpath);3129 error_unlink_return:3130 unlink_or_warn(lockpath);3131 error_free_return:3132 free(git_HEAD);3133 return -1;3134 }31353136#ifndef NO_SYMLINK_HEAD3137 done:3138#endif3139 if (logmsg && !read_ref(refs_heads_master, new_sha1))3140 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);31413142 free(git_HEAD);3143 return 0;3144}31453146struct read_ref_at_cb {3147 const char *refname;3148 unsigned long at_time;3149 int cnt;3150 int reccnt;3151 unsigned char *sha1;3152 int found_it;31533154 unsigned char osha1[20];3155 unsigned char nsha1[20];3156 int tz;3157 unsigned long date;3158 char **msg;3159 unsigned long *cutoff_time;3160 int *cutoff_tz;3161 int *cutoff_cnt;3162};31633164static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,3165 const char *email, unsigned long timestamp, int tz,3166 const char *message, void *cb_data)3167{3168 struct read_ref_at_cb *cb = cb_data;31693170 cb->reccnt++;3171 cb->tz = tz;3172 cb->date = timestamp;31733174 if (timestamp <= cb->at_time || cb->cnt == 0) {3175 if (cb->msg)3176 *cb->msg = xstrdup(message);3177 if (cb->cutoff_time)3178 *cb->cutoff_time = timestamp;3179 if (cb->cutoff_tz)3180 *cb->cutoff_tz = tz;3181 if (cb->cutoff_cnt)3182 *cb->cutoff_cnt = cb->reccnt - 1;3183 /*3184 * we have not yet updated cb->[n|o]sha1 so they still3185 * hold the values for the previous record.3186 */3187 if (!is_null_sha1(cb->osha1)) {3188 hashcpy(cb->sha1, nsha1);3189 if (hashcmp(cb->osha1, nsha1))3190 warning("Log for ref %s has gap after %s.",3191 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));3192 }3193 else if (cb->date == cb->at_time)3194 hashcpy(cb->sha1, nsha1);3195 else if (hashcmp(nsha1, cb->sha1))3196 warning("Log for ref %s unexpectedly ended on %s.",3197 cb->refname, show_date(cb->date, cb->tz,3198 DATE_RFC2822));3199 hashcpy(cb->osha1, osha1);3200 hashcpy(cb->nsha1, nsha1);3201 cb->found_it = 1;3202 return 1;3203 }3204 hashcpy(cb->osha1, osha1);3205 hashcpy(cb->nsha1, nsha1);3206 if (cb->cnt > 0)3207 cb->cnt--;3208 return 0;3209}32103211static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,3212 const char *email, unsigned long timestamp,3213 int tz, const char *message, void *cb_data)3214{3215 struct read_ref_at_cb *cb = cb_data;32163217 if (cb->msg)3218 *cb->msg = xstrdup(message);3219 if (cb->cutoff_time)3220 *cb->cutoff_time = timestamp;3221 if (cb->cutoff_tz)3222 *cb->cutoff_tz = tz;3223 if (cb->cutoff_cnt)3224 *cb->cutoff_cnt = cb->reccnt;3225 hashcpy(cb->sha1, osha1);3226 if (is_null_sha1(cb->sha1))3227 hashcpy(cb->sha1, nsha1);3228 /* We just want the first entry */3229 return 1;3230}32313232int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,3233 unsigned char *sha1, char **msg,3234 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)3235{3236 struct read_ref_at_cb cb;32373238 memset(&cb, 0, sizeof(cb));3239 cb.refname = refname;3240 cb.at_time = at_time;3241 cb.cnt = cnt;3242 cb.msg = msg;3243 cb.cutoff_time = cutoff_time;3244 cb.cutoff_tz = cutoff_tz;3245 cb.cutoff_cnt = cutoff_cnt;3246 cb.sha1 = sha1;32473248 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);32493250 if (!cb.reccnt) {3251 if (flags & GET_SHA1_QUIETLY)3252 exit(128);3253 else3254 die("Log for %s is empty.", refname);3255 }3256 if (cb.found_it)3257 return 0;32583259 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);32603261 return 1;3262}32633264int reflog_exists(const char *refname)3265{3266 struct stat st;32673268 return !lstat(git_path("logs/%s", refname), &st) &&3269 S_ISREG(st.st_mode);3270}32713272int delete_reflog(const char *refname)3273{3274 return remove_path(git_path("logs/%s", refname));3275}32763277static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)3278{3279 unsigned char osha1[20], nsha1[20];3280 char *email_end, *message;3281 unsigned long timestamp;3282 int tz;32833284 /* old SP new SP name <email> SP time TAB msg LF */3285 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||3286 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||3287 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||3288 !(email_end = strchr(sb->buf + 82, '>')) ||3289 email_end[1] != ' ' ||3290 !(timestamp = strtoul(email_end + 2, &message, 10)) ||3291 !message || message[0] != ' ' ||3292 (message[1] != '+' && message[1] != '-') ||3293 !isdigit(message[2]) || !isdigit(message[3]) ||3294 !isdigit(message[4]) || !isdigit(message[5]))3295 return 0; /* corrupt? */3296 email_end[1] = '\0';3297 tz = strtol(message + 1, NULL, 10);3298 if (message[6] != '\t')3299 message += 6;3300 else3301 message += 7;3302 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);3303}33043305static char *find_beginning_of_line(char *bob, char *scan)3306{3307 while (bob < scan && *(--scan) != '\n')3308 ; /* keep scanning backwards */3309 /*3310 * Return either beginning of the buffer, or LF at the end of3311 * the previous line.3312 */3313 return scan;3314}33153316int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)3317{3318 struct strbuf sb = STRBUF_INIT;3319 FILE *logfp;3320 long pos;3321 int ret = 0, at_tail = 1;33223323 logfp = fopen(git_path("logs/%s", refname), "r");3324 if (!logfp)3325 return -1;33263327 /* Jump to the end */3328 if (fseek(logfp, 0, SEEK_END) < 0)3329 return error("cannot seek back reflog for %s: %s",3330 refname, strerror(errno));3331 pos = ftell(logfp);3332 while (!ret && 0 < pos) {3333 int cnt;3334 size_t nread;3335 char buf[BUFSIZ];3336 char *endp, *scanp;33373338 /* Fill next block from the end */3339 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;3340 if (fseek(logfp, pos - cnt, SEEK_SET))3341 return error("cannot seek back reflog for %s: %s",3342 refname, strerror(errno));3343 nread = fread(buf, cnt, 1, logfp);3344 if (nread != 1)3345 return error("cannot read %d bytes from reflog for %s: %s",3346 cnt, refname, strerror(errno));3347 pos -= cnt;33483349 scanp = endp = buf + cnt;3350 if (at_tail && scanp[-1] == '\n')3351 /* Looking at the final LF at the end of the file */3352 scanp--;3353 at_tail = 0;33543355 while (buf < scanp) {3356 /*3357 * terminating LF of the previous line, or the beginning3358 * of the buffer.3359 */3360 char *bp;33613362 bp = find_beginning_of_line(buf, scanp);33633364 if (*bp == '\n') {3365 /*3366 * The newline is the end of the previous line,3367 * so we know we have complete line starting3368 * at (bp + 1). Prefix it onto any prior data3369 * we collected for the line and process it.3370 */3371 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));3372 scanp = bp;3373 endp = bp + 1;3374 ret = show_one_reflog_ent(&sb, fn, cb_data);3375 strbuf_reset(&sb);3376 if (ret)3377 break;3378 } else if (!pos) {3379 /*3380 * We are at the start of the buffer, and the3381 * start of the file; there is no previous3382 * line, and we have everything for this one.3383 * Process it, and we can end the loop.3384 */3385 strbuf_splice(&sb, 0, 0, buf, endp - buf);3386 ret = show_one_reflog_ent(&sb, fn, cb_data);3387 strbuf_reset(&sb);3388 break;3389 }33903391 if (bp == buf) {3392 /*3393 * We are at the start of the buffer, and there3394 * is more file to read backwards. Which means3395 * we are in the middle of a line. Note that we3396 * may get here even if *bp was a newline; that3397 * just means we are at the exact end of the3398 * previous line, rather than some spot in the3399 * middle.3400 *3401 * Save away what we have to be combined with3402 * the data from the next read.3403 */3404 strbuf_splice(&sb, 0, 0, buf, endp - buf);3405 break;3406 }3407 }34083409 }3410 if (!ret && sb.len)3411 die("BUG: reverse reflog parser had leftover data");34123413 fclose(logfp);3414 strbuf_release(&sb);3415 return ret;3416}34173418int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)3419{3420 FILE *logfp;3421 struct strbuf sb = STRBUF_INIT;3422 int ret = 0;34233424 logfp = fopen(git_path("logs/%s", refname), "r");3425 if (!logfp)3426 return -1;34273428 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))3429 ret = show_one_reflog_ent(&sb, fn, cb_data);3430 fclose(logfp);3431 strbuf_release(&sb);3432 return ret;3433}3434/*3435 * Call fn for each reflog in the namespace indicated by name. name3436 * must be empty or end with '/'. Name will be used as a scratch3437 * space, but its contents will be restored before return.3438 */3439static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)3440{3441 DIR *d = opendir(git_path("logs/%s", name->buf));3442 int retval = 0;3443 struct dirent *de;3444 int oldlen = name->len;34453446 if (!d)3447 return name->len ? errno : 0;34483449 while ((de = readdir(d)) != NULL) {3450 struct stat st;34513452 if (de->d_name[0] == '.')3453 continue;3454 if (ends_with(de->d_name, ".lock"))3455 continue;3456 strbuf_addstr(name, de->d_name);3457 if (stat(git_path("logs/%s", name->buf), &st) < 0) {3458 ; /* silently ignore */3459 } else {3460 if (S_ISDIR(st.st_mode)) {3461 strbuf_addch(name, '/');3462 retval = do_for_each_reflog(name, fn, cb_data);3463 } else {3464 unsigned char sha1[20];3465 if (read_ref_full(name->buf, 0, sha1, NULL))3466 retval = error("bad ref for %s", name->buf);3467 else3468 retval = fn(name->buf, sha1, 0, cb_data);3469 }3470 if (retval)3471 break;3472 }3473 strbuf_setlen(name, oldlen);3474 }3475 closedir(d);3476 return retval;3477}34783479int for_each_reflog(each_ref_fn fn, void *cb_data)3480{3481 int retval;3482 struct strbuf name;3483 strbuf_init(&name, PATH_MAX);3484 retval = do_for_each_reflog(&name, fn, cb_data);3485 strbuf_release(&name);3486 return retval;3487}34883489/**3490 * Information needed for a single ref update. Set new_sha1 to the3491 * new value or to zero to delete the ref. To check the old value3492 * while locking the ref, set have_old to 1 and set old_sha1 to the3493 * value or to zero to ensure the ref does not exist before update.3494 */3495struct ref_update {3496 unsigned char new_sha1[20];3497 unsigned char old_sha1[20];3498 int flags; /* REF_NODEREF? */3499 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */3500 struct ref_lock *lock;3501 int type;3502 char *msg;3503 const char refname[FLEX_ARRAY];3504};35053506/*3507 * Transaction states.3508 * OPEN: The transaction is in a valid state and can accept new updates.3509 * An OPEN transaction can be committed.3510 * CLOSED: A closed transaction is no longer active and no other operations3511 * than free can be used on it in this state.3512 * A transaction can either become closed by successfully committing3513 * an active transaction or if there is a failure while building3514 * the transaction thus rendering it failed/inactive.3515 */3516enum ref_transaction_state {3517 REF_TRANSACTION_OPEN = 0,3518 REF_TRANSACTION_CLOSED = 13519};35203521/*3522 * Data structure for holding a reference transaction, which can3523 * consist of checks and updates to multiple references, carried out3524 * as atomically as possible. This structure is opaque to callers.3525 */3526struct ref_transaction {3527 struct ref_update **updates;3528 size_t alloc;3529 size_t nr;3530 enum ref_transaction_state state;3531};35323533struct ref_transaction *ref_transaction_begin(struct strbuf *err)3534{3535 assert(err);35363537 return xcalloc(1, sizeof(struct ref_transaction));3538}35393540void ref_transaction_free(struct ref_transaction *transaction)3541{3542 int i;35433544 if (!transaction)3545 return;35463547 for (i = 0; i < transaction->nr; i++) {3548 free(transaction->updates[i]->msg);3549 free(transaction->updates[i]);3550 }3551 free(transaction->updates);3552 free(transaction);3553}35543555static struct ref_update *add_update(struct ref_transaction *transaction,3556 const char *refname)3557{3558 size_t len = strlen(refname);3559 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);35603561 strcpy((char *)update->refname, refname);3562 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);3563 transaction->updates[transaction->nr++] = update;3564 return update;3565}35663567int ref_transaction_update(struct ref_transaction *transaction,3568 const char *refname,3569 const unsigned char *new_sha1,3570 const unsigned char *old_sha1,3571 int flags, int have_old, const char *msg,3572 struct strbuf *err)3573{3574 struct ref_update *update;35753576 assert(err);35773578 if (transaction->state != REF_TRANSACTION_OPEN)3579 die("BUG: update called for transaction that is not open");35803581 if (have_old && !old_sha1)3582 die("BUG: have_old is true but old_sha1 is NULL");35833584 if (!is_null_sha1(new_sha1) &&3585 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3586 strbuf_addf(err, "refusing to update ref with bad name %s",3587 refname);3588 return -1;3589 }35903591 update = add_update(transaction, refname);3592 hashcpy(update->new_sha1, new_sha1);3593 update->flags = flags;3594 update->have_old = have_old;3595 if (have_old)3596 hashcpy(update->old_sha1, old_sha1);3597 if (msg)3598 update->msg = xstrdup(msg);3599 return 0;3600}36013602int ref_transaction_create(struct ref_transaction *transaction,3603 const char *refname,3604 const unsigned char *new_sha1,3605 int flags, const char *msg,3606 struct strbuf *err)3607{3608 struct ref_update *update;36093610 assert(err);36113612 if (transaction->state != REF_TRANSACTION_OPEN)3613 die("BUG: create called for transaction that is not open");36143615 if (!new_sha1 || is_null_sha1(new_sha1))3616 die("BUG: create ref with null new_sha1");36173618 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3619 strbuf_addf(err, "refusing to create ref with bad name %s",3620 refname);3621 return -1;3622 }36233624 update = add_update(transaction, refname);36253626 hashcpy(update->new_sha1, new_sha1);3627 hashclr(update->old_sha1);3628 update->flags = flags;3629 update->have_old = 1;3630 if (msg)3631 update->msg = xstrdup(msg);3632 return 0;3633}36343635int ref_transaction_delete(struct ref_transaction *transaction,3636 const char *refname,3637 const unsigned char *old_sha1,3638 int flags, int have_old, const char *msg,3639 struct strbuf *err)3640{3641 struct ref_update *update;36423643 assert(err);36443645 if (transaction->state != REF_TRANSACTION_OPEN)3646 die("BUG: delete called for transaction that is not open");36473648 if (have_old && !old_sha1)3649 die("BUG: have_old is true but old_sha1 is NULL");36503651 update = add_update(transaction, refname);3652 update->flags = flags;3653 update->have_old = have_old;3654 if (have_old) {3655 assert(!is_null_sha1(old_sha1));3656 hashcpy(update->old_sha1, old_sha1);3657 }3658 if (msg)3659 update->msg = xstrdup(msg);3660 return 0;3661}36623663int update_ref(const char *action, const char *refname,3664 const unsigned char *sha1, const unsigned char *oldval,3665 int flags, enum action_on_err onerr)3666{3667 struct ref_transaction *t;3668 struct strbuf err = STRBUF_INIT;36693670 t = ref_transaction_begin(&err);3671 if (!t ||3672 ref_transaction_update(t, refname, sha1, oldval, flags,3673 !!oldval, action, &err) ||3674 ref_transaction_commit(t, &err)) {3675 const char *str = "update_ref failed for ref '%s': %s";36763677 ref_transaction_free(t);3678 switch (onerr) {3679 case UPDATE_REFS_MSG_ON_ERR:3680 error(str, refname, err.buf);3681 break;3682 case UPDATE_REFS_DIE_ON_ERR:3683 die(str, refname, err.buf);3684 break;3685 case UPDATE_REFS_QUIET_ON_ERR:3686 break;3687 }3688 strbuf_release(&err);3689 return 1;3690 }3691 strbuf_release(&err);3692 ref_transaction_free(t);3693 return 0;3694}36953696static int ref_update_compare(const void *r1, const void *r2)3697{3698 const struct ref_update * const *u1 = r1;3699 const struct ref_update * const *u2 = r2;3700 return strcmp((*u1)->refname, (*u2)->refname);3701}37023703static int ref_update_reject_duplicates(struct ref_update **updates, int n,3704 struct strbuf *err)3705{3706 int i;37073708 assert(err);37093710 for (i = 1; i < n; i++)3711 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {3712 strbuf_addf(err,3713 "Multiple updates for ref '%s' not allowed.",3714 updates[i]->refname);3715 return 1;3716 }3717 return 0;3718}37193720int ref_transaction_commit(struct ref_transaction *transaction,3721 struct strbuf *err)3722{3723 int ret = 0, i;3724 int n = transaction->nr;3725 struct ref_update **updates = transaction->updates;3726 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3727 struct string_list_item *ref_to_delete;37283729 assert(err);37303731 if (transaction->state != REF_TRANSACTION_OPEN)3732 die("BUG: commit called for transaction that is not open");37333734 if (!n) {3735 transaction->state = REF_TRANSACTION_CLOSED;3736 return 0;3737 }37383739 /* Copy, sort, and reject duplicate refs */3740 qsort(updates, n, sizeof(*updates), ref_update_compare);3741 if (ref_update_reject_duplicates(updates, n, err)) {3742 ret = TRANSACTION_GENERIC_ERROR;3743 goto cleanup;3744 }37453746 /* Acquire all locks while verifying old values */3747 for (i = 0; i < n; i++) {3748 struct ref_update *update = updates[i];3749 int flags = update->flags;37503751 if (is_null_sha1(update->new_sha1))3752 flags |= REF_DELETING;3753 update->lock = lock_ref_sha1_basic(update->refname,3754 (update->have_old ?3755 update->old_sha1 :3756 NULL),3757 NULL,3758 flags,3759 &update->type);3760 if (!update->lock) {3761 ret = (errno == ENOTDIR)3762 ? TRANSACTION_NAME_CONFLICT3763 : TRANSACTION_GENERIC_ERROR;3764 strbuf_addf(err, "Cannot lock the ref '%s'.",3765 update->refname);3766 goto cleanup;3767 }3768 }37693770 /* Perform updates first so live commits remain referenced */3771 for (i = 0; i < n; i++) {3772 struct ref_update *update = updates[i];37733774 if (!is_null_sha1(update->new_sha1)) {3775 if (write_ref_sha1(update->lock, update->new_sha1,3776 update->msg)) {3777 update->lock = NULL; /* freed by write_ref_sha1 */3778 strbuf_addf(err, "Cannot update the ref '%s'.",3779 update->refname);3780 ret = TRANSACTION_GENERIC_ERROR;3781 goto cleanup;3782 }3783 update->lock = NULL; /* freed by write_ref_sha1 */3784 }3785 }37863787 /* Perform deletes now that updates are safely completed */3788 for (i = 0; i < n; i++) {3789 struct ref_update *update = updates[i];37903791 if (update->lock) {3792 if (delete_ref_loose(update->lock, update->type, err)) {3793 ret = TRANSACTION_GENERIC_ERROR;3794 goto cleanup;3795 }37963797 if (!(update->flags & REF_ISPRUNING))3798 string_list_append(&refs_to_delete,3799 update->lock->ref_name);3800 }3801 }38023803 if (repack_without_refs(&refs_to_delete, err)) {3804 ret = TRANSACTION_GENERIC_ERROR;3805 goto cleanup;3806 }3807 for_each_string_list_item(ref_to_delete, &refs_to_delete)3808 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3809 clear_loose_ref_cache(&ref_cache);38103811cleanup:3812 transaction->state = REF_TRANSACTION_CLOSED;38133814 for (i = 0; i < n; i++)3815 if (updates[i]->lock)3816 unlock_ref(updates[i]->lock);3817 string_list_clear(&refs_to_delete, 0);3818 return ret;3819}38203821char *shorten_unambiguous_ref(const char *refname, int strict)3822{3823 int i;3824 static char **scanf_fmts;3825 static int nr_rules;3826 char *short_name;38273828 if (!nr_rules) {3829 /*3830 * Pre-generate scanf formats from ref_rev_parse_rules[].3831 * Generate a format suitable for scanf from a3832 * ref_rev_parse_rules rule by interpolating "%s" at the3833 * location of the "%.*s".3834 */3835 size_t total_len = 0;3836 size_t offset = 0;38373838 /* the rule list is NULL terminated, count them first */3839 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)3840 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3841 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;38423843 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);38443845 offset = 0;3846 for (i = 0; i < nr_rules; i++) {3847 assert(offset < total_len);3848 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;3849 offset += snprintf(scanf_fmts[i], total_len - offset,3850 ref_rev_parse_rules[i], 2, "%s") + 1;3851 }3852 }38533854 /* bail out if there are no rules */3855 if (!nr_rules)3856 return xstrdup(refname);38573858 /* buffer for scanf result, at most refname must fit */3859 short_name = xstrdup(refname);38603861 /* skip first rule, it will always match */3862 for (i = nr_rules - 1; i > 0 ; --i) {3863 int j;3864 int rules_to_fail = i;3865 int short_name_len;38663867 if (1 != sscanf(refname, scanf_fmts[i], short_name))3868 continue;38693870 short_name_len = strlen(short_name);38713872 /*3873 * in strict mode, all (except the matched one) rules3874 * must fail to resolve to a valid non-ambiguous ref3875 */3876 if (strict)3877 rules_to_fail = nr_rules;38783879 /*3880 * check if the short name resolves to a valid ref,3881 * but use only rules prior to the matched one3882 */3883 for (j = 0; j < rules_to_fail; j++) {3884 const char *rule = ref_rev_parse_rules[j];3885 char refname[PATH_MAX];38863887 /* skip matched rule */3888 if (i == j)3889 continue;38903891 /*3892 * the short name is ambiguous, if it resolves3893 * (with this previous rule) to a valid ref3894 * read_ref() returns 0 on success3895 */3896 mksnpath(refname, sizeof(refname),3897 rule, short_name_len, short_name);3898 if (ref_exists(refname))3899 break;3900 }39013902 /*3903 * short name is non-ambiguous if all previous rules3904 * haven't resolved to a valid ref3905 */3906 if (j == rules_to_fail)3907 return short_name;3908 }39093910 free(short_name);3911 return xstrdup(refname);3912}39133914static struct string_list *hide_refs;39153916int parse_hide_refs_config(const char *var, const char *value, const char *section)3917{3918 if (!strcmp("transfer.hiderefs", var) ||3919 /* NEEDSWORK: use parse_config_key() once both are merged */3920 (starts_with(var, section) && var[strlen(section)] == '.' &&3921 !strcmp(var + strlen(section), ".hiderefs"))) {3922 char *ref;3923 int len;39243925 if (!value)3926 return config_error_nonbool(var);3927 ref = xstrdup(value);3928 len = strlen(ref);3929 while (len && ref[len - 1] == '/')3930 ref[--len] = '\0';3931 if (!hide_refs) {3932 hide_refs = xcalloc(1, sizeof(*hide_refs));3933 hide_refs->strdup_strings = 1;3934 }3935 string_list_append(hide_refs, ref);3936 }3937 return 0;3938}39393940int ref_is_hidden(const char *refname)3941{3942 struct string_list_item *item;39433944 if (!hide_refs)3945 return 0;3946 for_each_string_list_item(item, hide_refs) {3947 int len;3948 if (!starts_with(refname, item->string))3949 continue;3950 len = strlen(item->string);3951 if (!refname[len] || refname[len] == '/')3952 return 1;3953 }3954 return 0;3955}