refs: split filesystem-based refs code into a new file
As another step in the move to pluggable reference backends, move the code that is specific to the filesystem-based reference backend (i.e., the current system of storing references as loose and packed files) into a separate file, refs/files-backend.c. Aside from a tiny bit of file header boilerplate, this commit only moves a subset of the code verbatim from refs.c to the new file, as can easily be verified using patience diff: git diff --patience $commit^:refs.c $commit:refs.c git diff --patience $commit^:refs.c $commit:refs/files-backend.c Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Jeff King <peff@peff.net>
Michael Haggerty committed
Nov 9, 2015 at 14:34 UTC
7bd9bcf372d4c03bb7034346d72ae1318e2d0742
3 files changed
+3761
-3752
Makefile
+2
-1
@@ -768,6 +768,7 @@ LIB_OBJS += reachable.o
768
LIB_OBJS += read-cache.o
769
LIB_OBJS += reflog-walk.o
770
LIB_OBJS += refs.o
771
+LIB_OBJS += refs/files-backend.o
772
LIB_OBJS += ref-filter.o
773
LIB_OBJS += remote.o
774
LIB_OBJS += replace_object.o
@@ -2419,7 +2420,7 @@ profile-clean:
2420
$(RM) $(addsuffix *.gcno,$(addprefix $(PROFILE_DIR)/, $(object_dirs)))
2421
2422
clean: profile-clean coverage-clean
2422
- $(RM) *.o *.res block-sha1/*.o ppc/*.o compat/*.o compat/*/*.o
2423
+ $(RM) *.o *.res refs/*.o block-sha1/*.o ppc/*.o compat/*.o compat/*/*.o
2424
$(RM) xdiff/*.o vcs-svn/*.o ewah/*.o builtin/*.o
2425
$(RM) $(LIB_FILE) $(XDIFF_LIB) $(VCSSVN_LIB)
2426
$(RM) $(ALL_PROGRAMS) $(SCRIPT_LIB) $(BUILT_INS) git$X
refs.c
+220
-3751
@@ -1,18 +1,13 @@
1
+/*
2
+ * The backend-independent part of the reference module.
3
+ */
4
+
5
#include "cache.h"
6
#include "lockfile.h"
7
#include "refs.h"
8
#include "refs/refs-internal.h"
9
#include "object.h"
10
#include "tag.h"
7
-#include "dir.h"
8
-#include "string-list.h"
9
-
10
-struct ref_lock {
11
- char *ref_name;
12
- char *orig_ref_name;
13
- struct lock_file *lk;
14
- struct object_id old_oid;
15
-};
11
12
/*
13
* How to handle various characters in refnames:
@@ -123,189 +118,6 @@ int check_refname_format(const char *refname, int flags)
118
return 0;
119
}
120
126
-struct ref_entry;
127
-
128
-/*
129
- * Information used (along with the information in ref_entry) to
130
- * describe a single cached reference. This data structure only
131
- * occurs embedded in a union in struct ref_entry, and only when
132
- * (ref_entry->flag & REF_DIR) is zero.
133
- */
134
-struct ref_value {
135
- /*
136
- * The name of the object to which this reference resolves
137
- * (which may be a tag object). If REF_ISBROKEN, this is
138
- * null. If REF_ISSYMREF, then this is the name of the object
139
- * referred to by the last reference in the symlink chain.
140
- */
141
- struct object_id oid;
142
-
143
- /*
144
- * If REF_KNOWS_PEELED, then this field holds the peeled value
145
- * of this reference, or null if the reference is known not to
146
- * be peelable. See the documentation for peel_ref() for an
147
- * exact definition of "peelable".
148
- */
149
- struct object_id peeled;
150
-};
151
-
152
-struct ref_cache;
153
-
154
-/*
155
- * Information used (along with the information in ref_entry) to
156
- * describe a level in the hierarchy of references. This data
157
- * structure only occurs embedded in a union in struct ref_entry, and
158
- * only when (ref_entry.flag & REF_DIR) is set. In that case,
159
- * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
160
- * in the directory have already been read:
161
- *
162
- * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
163
- * or packed references, already read.
164
- *
165
- * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
166
- * references that hasn't been read yet (nor has any of its
167
- * subdirectories).
168
- *
169
- * Entries within a directory are stored within a growable array of
170
- * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
171
- * sorted are sorted by their component name in strcmp() order and the
172
- * remaining entries are unsorted.
173
- *
174
- * Loose references are read lazily, one directory at a time. When a
175
- * directory of loose references is read, then all of the references
176
- * in that directory are stored, and REF_INCOMPLETE stubs are created
177
- * for any subdirectories, but the subdirectories themselves are not
178
- * read. The reading is triggered by get_ref_dir().
179
- */
180
-struct ref_dir {
181
- int nr, alloc;
182
-
183
- /*
184
- * Entries with index 0 <= i < sorted are sorted by name. New
185
- * entries are appended to the list unsorted, and are sorted
186
- * only when required; thus we avoid the need to sort the list
187
- * after the addition of every reference.
188
- */
189
- int sorted;
190
-
191
- /* A pointer to the ref_cache that contains this ref_dir. */
192
- struct ref_cache *ref_cache;
193
-
194
- struct ref_entry **entries;
195
-};
196
-
197
-/*
198
- * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
199
- * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
200
- * public values; see refs.h.
201
- */
202
-
203
-/*
204
- * The field ref_entry->u.value.peeled of this value entry contains
205
- * the correct peeled value for the reference, which might be
206
- * null_sha1 if the reference is not a tag or if it is broken.
207
- */
208
-#define REF_KNOWS_PEELED 0x10
209
-
210
-/* ref_entry represents a directory of references */
211
-#define REF_DIR 0x20
212
-
213
-/*
214
- * Entry has not yet been read from disk (used only for REF_DIR
215
- * entries representing loose references)
216
- */
217
-#define REF_INCOMPLETE 0x40
218
-
219
-/*
220
- * A ref_entry represents either a reference or a "subdirectory" of
221
- * references.
222
- *
223
- * Each directory in the reference namespace is represented by a
224
- * ref_entry with (flags & REF_DIR) set and containing a subdir member
225
- * that holds the entries in that directory that have been read so
226
- * far. If (flags & REF_INCOMPLETE) is set, then the directory and
227
- * its subdirectories haven't been read yet. REF_INCOMPLETE is only
228
- * used for loose reference directories.
229
- *
230
- * References are represented by a ref_entry with (flags & REF_DIR)
231
- * unset and a value member that describes the reference's value. The
232
- * flag member is at the ref_entry level, but it is also needed to
233
- * interpret the contents of the value field (in other words, a
234
- * ref_value object is not very much use without the enclosing
235
- * ref_entry).
236
- *
237
- * Reference names cannot end with slash and directories' names are
238
- * always stored with a trailing slash (except for the top-level
239
- * directory, which is always denoted by ""). This has two nice
240
- * consequences: (1) when the entries in each subdir are sorted
241
- * lexicographically by name (as they usually are), the references in
242
- * a whole tree can be generated in lexicographic order by traversing
243
- * the tree in left-to-right, depth-first order; (2) the names of
244
- * references and subdirectories cannot conflict, and therefore the
245
- * presence of an empty subdirectory does not block the creation of a
246
- * similarly-named reference. (The fact that reference names with the
247
- * same leading components can conflict *with each other* is a
248
- * separate issue that is regulated by verify_refname_available().)
249
- *
250
- * Please note that the name field contains the fully-qualified
251
- * reference (or subdirectory) name. Space could be saved by only
252
- * storing the relative names. But that would require the full names
253
- * to be generated on the fly when iterating in do_for_each_ref(), and
254
- * would break callback functions, who have always been able to assume
255
- * that the name strings that they are passed will not be freed during
256
- * the iteration.
257
- */
258
-struct ref_entry {
259
- unsigned char flag; /* ISSYMREF? ISPACKED? */
260
- union {
261
- struct ref_value value; /* if not (flags&REF_DIR) */
262
- struct ref_dir subdir; /* if (flags&REF_DIR) */
263
- } u;
264
- /*
265
- * The full name of the reference (e.g., "refs/heads/master")
266
- * or the full name of the directory with a trailing slash
267
- * (e.g., "refs/heads/"):
268
- */
269
- char name[FLEX_ARRAY];
270
-};
271
-
272
-static void read_loose_refs(const char *dirname, struct ref_dir *dir);
273
-static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
274
-static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
275
- const char *dirname, size_t len,
276
- int incomplete);
277
-static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
278
-
279
-static struct ref_dir *get_ref_dir(struct ref_entry *entry)
280
-{
281
- struct ref_dir *dir;
282
- assert(entry->flag & REF_DIR);
283
- dir = &entry->u.subdir;
284
- if (entry->flag & REF_INCOMPLETE) {
285
- read_loose_refs(entry->name, dir);
286
-
287
- /*
288
- * Manually add refs/bisect, which, being
289
- * per-worktree, might not appear in the directory
290
- * listing for refs/ in the main repo.
291
- */
292
- if (!strcmp(entry->name, "refs/")) {
293
- int pos = search_ref_dir(dir, "refs/bisect/", 12);
294
- if (pos < 0) {
295
- struct ref_entry *child_entry;
296
- child_entry = create_dir_entry(dir->ref_cache,
297
- "refs/bisect/",
298
- 12, 1);
299
- add_entry_to_dir(dir, child_entry);
300
- read_loose_refs("refs/bisect",
301
- &child_entry->u.subdir);
302
- }
303
- }
304
- entry->flag &= ~REF_INCOMPLETE;
305
- }
306
- return dir;
307
-}
308
-
121
int refname_is_safe(const char *refname)
122
{
123
if (starts_with(refname, "refs/")) {
@@ -330,2479 +142,317 @@ int refname_is_safe(const char *refname)
142
return 1;
143
}
144
333
-static struct ref_entry *create_ref_entry(const char *refname,
334
- const unsigned char *sha1, int flag,
335
- int check_name)
145
+char *resolve_refdup(const char *refname, int resolve_flags,
146
+ unsigned char *sha1, int *flags)
147
{
337
- int len;
338
- struct ref_entry *ref;
339
-
340
- if (check_name &&
341
- check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
342
- die("Reference has invalid format: '%s'", refname);
343
- len = strlen(refname) + 1;
344
- ref = xmalloc(sizeof(struct ref_entry) + len);
345
- hashcpy(ref->u.value.oid.hash, sha1);
346
- oidclr(&ref->u.value.peeled);
347
- memcpy(ref->name, refname, len);
348
- ref->flag = flag;
349
- return ref;
148
+ return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
149
+ sha1, flags));
150
}
151
352
-static void clear_ref_dir(struct ref_dir *dir);
152
+/* The argument to filter_refs */
153
+struct ref_filter {
154
+ const char *pattern;
155
+ each_ref_fn *fn;
156
+ void *cb_data;
157
+};
158
354
-static void free_ref_entry(struct ref_entry *entry)
159
+int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
160
{
356
- if (entry->flag & REF_DIR) {
357
- /*
358
- * Do not use get_ref_dir() here, as that might
359
- * trigger the reading of loose refs.
360
- */
361
- clear_ref_dir(&entry->u.subdir);
362
- }
363
- free(entry);
161
+ if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
162
+ return 0;
163
+ return -1;
164
}
165
366
-/*
367
- * Add a ref_entry to the end of dir (unsorted). Entry is always
368
- * stored directly in dir; no recursion into subdirectories is
369
- * done.
370
- */
371
-static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
166
+int read_ref(const char *refname, unsigned char *sha1)
167
{
373
- ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
374
- dir->entries[dir->nr++] = entry;
375
- /* optimize for the case that entries are added in order */
376
- if (dir->nr == 1 ||
377
- (dir->nr == dir->sorted + 1 &&
378
- strcmp(dir->entries[dir->nr - 2]->name,
379
- dir->entries[dir->nr - 1]->name) < 0))
380
- dir->sorted = dir->nr;
168
+ return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
169
}
170
383
-/*
384
- * Clear and free all entries in dir, recursively.
385
- */
386
-static void clear_ref_dir(struct ref_dir *dir)
171
+int ref_exists(const char *refname)
172
{
388
- int i;
389
- for (i = 0; i < dir->nr; i++)
390
- free_ref_entry(dir->entries[i]);
391
- free(dir->entries);
392
- dir->sorted = dir->nr = dir->alloc = 0;
393
- dir->entries = NULL;
173
+ unsigned char sha1[20];
174
+ return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
175
}
176
396
-/*
397
- * Create a struct ref_entry object for the specified dirname.
398
- * dirname is the name of the directory with a trailing slash (e.g.,
399
- * "refs/heads/") or "" for the top-level directory.
400
- */
401
-static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
402
- const char *dirname, size_t len,
403
- int incomplete)
177
+static int filter_refs(const char *refname, const struct object_id *oid,
178
+ int flags, void *data)
179
{
405
- struct ref_entry *direntry;
406
- direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
407
- memcpy(direntry->name, dirname, len);
408
- direntry->name[len] = '\0';
409
- direntry->u.subdir.ref_cache = ref_cache;
410
- direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
411
- return direntry;
180
+ struct ref_filter *filter = (struct ref_filter *)data;
181
+
182
+ if (wildmatch(filter->pattern, refname, 0, NULL))
183
+ return 0;
184
+ return filter->fn(refname, oid, flags, filter->cb_data);
185
}
186
414
-static int ref_entry_cmp(const void *a, const void *b)
187
+enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
188
{
416
- struct ref_entry *one = *(struct ref_entry **)a;
417
- struct ref_entry *two = *(struct ref_entry **)b;
418
- return strcmp(one->name, two->name);
419
-}
189
+ struct object *o = lookup_unknown_object(name);
190
421
-static void sort_ref_dir(struct ref_dir *dir);
191
+ if (o->type == OBJ_NONE) {
192
+ int type = sha1_object_info(name, NULL);
193
+ if (type < 0 || !object_as_type(o, type, 0))
194
+ return PEEL_INVALID;
195
+ }
196
423
-struct string_slice {
424
- size_t len;
425
- const char *str;
426
-};
197
+ if (o->type != OBJ_TAG)
198
+ return PEEL_NON_TAG;
199
428
-static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
429
-{
430
- const struct string_slice *key = key_;
431
- const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
432
- int cmp = strncmp(key->str, ent->name, key->len);
433
- if (cmp)
434
- return cmp;
435
- return '\0' - (unsigned char)ent->name[key->len];
200
+ o = deref_tag_noverify(o);
201
+ if (!o)
202
+ return PEEL_INVALID;
203
+
204
+ hashcpy(sha1, o->sha1);
205
+ return PEEL_PEELED;
206
}
207
438
-/*
439
- * Return the index of the entry with the given refname from the
440
- * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
441
- * no such entry is found. dir must already be complete.
442
- */
443
-static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
444
-{
445
- struct ref_entry **r;
446
- struct string_slice key;
208
+struct warn_if_dangling_data {
209
+ FILE *fp;
210
+ const char *refname;
211
+ const struct string_list *refnames;
212
+ const char *msg_fmt;
213
+};
214
448
- if (refname == NULL || !dir->nr)
449
- return -1;
215
+static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
216
+ int flags, void *cb_data)
217
+{
218
+ struct warn_if_dangling_data *d = cb_data;
219
+ const char *resolves_to;
220
+ struct object_id junk;
221
451
- sort_ref_dir(dir);
452
- key.len = len;
453
- key.str = refname;
454
- r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
455
- ref_entry_cmp_sslice);
222
+ if (!(flags & REF_ISSYMREF))
223
+ return 0;
224
457
- if (r == NULL)
458
- return -1;
225
+ resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
226
+ if (!resolves_to
227
+ || (d->refname
228
+ ? strcmp(resolves_to, d->refname)
229
+ : !string_list_has_string(d->refnames, resolves_to))) {
230
+ return 0;
231
+ }
232
460
- return r - dir->entries;
233
+ fprintf(d->fp, d->msg_fmt, refname);
234
+ fputc('\n', d->fp);
235
+ return 0;
236
}
237
463
-/*
464
- * Search for a directory entry directly within dir (without
465
- * recursing). Sort dir if necessary. subdirname must be a directory
466
- * name (i.e., end in '/'). If mkdir is set, then create the
467
- * directory if it is missing; otherwise, return NULL if the desired
468
- * directory cannot be found. dir must already be complete.
469
- */
470
-static struct ref_dir *search_for_subdir(struct ref_dir *dir,
471
- const char *subdirname, size_t len,
472
- int mkdir)
238
+void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
239
{
474
- int entry_index = search_ref_dir(dir, subdirname, len);
475
- struct ref_entry *entry;
476
- if (entry_index == -1) {
477
- if (!mkdir)
478
- return NULL;
479
- /*
480
- * Since dir is complete, the absence of a subdir
481
- * means that the subdir really doesn't exist;
482
- * therefore, create an empty record for it but mark
483
- * the record complete.
484
- */
485
- entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
486
- add_entry_to_dir(dir, entry);
487
- } else {
488
- entry = dir->entries[entry_index];
489
- }
490
- return get_ref_dir(entry);
240
+ struct warn_if_dangling_data data;
241
+
242
+ data.fp = fp;
243
+ data.refname = refname;
244
+ data.refnames = NULL;
245
+ data.msg_fmt = msg_fmt;
246
+ for_each_rawref(warn_if_dangling_symref, &data);
247
}
248
493
-/*
494
- * If refname is a reference name, find the ref_dir within the dir
495
- * tree that should hold refname. If refname is a directory name
496
- * (i.e., ends in '/'), then return that ref_dir itself. dir must
497
- * represent the top-level directory and must already be complete.
498
- * Sort ref_dirs and recurse into subdirectories as necessary. If
499
- * mkdir is set, then create any missing directories; otherwise,
500
- * return NULL if the desired directory cannot be found.
501
- */
502
-static struct ref_dir *find_containing_dir(struct ref_dir *dir,
503
- const char *refname, int mkdir)
249
+void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
250
{
505
- const char *slash;
506
- for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
507
- size_t dirnamelen = slash - refname + 1;
508
- struct ref_dir *subdir;
509
- subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
510
- if (!subdir) {
511
- dir = NULL;
512
- break;
513
- }
514
- dir = subdir;
515
- }
251
+ struct warn_if_dangling_data data;
252
517
- return dir;
253
+ data.fp = fp;
254
+ data.refname = NULL;
255
+ data.refnames = refnames;
256
+ data.msg_fmt = msg_fmt;
257
+ for_each_rawref(warn_if_dangling_symref, &data);
258
}
259
520
-/*
521
- * Find the value entry with the given name in dir, sorting ref_dirs
522
- * and recursing into subdirectories as necessary. If the name is not
523
- * found or it corresponds to a directory entry, return NULL.
524
- */
525
-static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
260
+int for_each_tag_ref(each_ref_fn fn, void *cb_data)
261
{
527
- int entry_index;
528
- struct ref_entry *entry;
529
- dir = find_containing_dir(dir, refname, 0);
530
- if (!dir)
531
- return NULL;
532
- entry_index = search_ref_dir(dir, refname, strlen(refname));
533
- if (entry_index == -1)
534
- return NULL;
535
- entry = dir->entries[entry_index];
536
- return (entry->flag & REF_DIR) ? NULL : entry;
262
+ return for_each_ref_in("refs/tags/", fn, cb_data);
263
}
264
539
-/*
540
- * Remove the entry with the given name from dir, recursing into
541
- * subdirectories as necessary. If refname is the name of a directory
542
- * (i.e., ends with '/'), then remove the directory and its contents.
543
- * If the removal was successful, return the number of entries
544
- * remaining in the directory entry that contained the deleted entry.
545
- * If the name was not found, return -1. Please note that this
546
- * function only deletes the entry from the cache; it does not delete
547
- * it from the filesystem or ensure that other cache entries (which
548
- * might be symbolic references to the removed entry) are updated.
549
- * Nor does it remove any containing dir entries that might be made
550
- * empty by the removal. dir must represent the top-level directory
551
- * and must already be complete.
552
- */
553
-static int remove_entry(struct ref_dir *dir, const char *refname)
265
+int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
266
{
555
- int refname_len = strlen(refname);
556
- int entry_index;
557
- struct ref_entry *entry;
558
- int is_dir = refname[refname_len - 1] == '/';
559
- if (is_dir) {
560
- /*
561
- * refname represents a reference directory. Remove
562
- * the trailing slash; otherwise we will get the
563
- * directory *representing* refname rather than the
564
- * one *containing* it.
565
- */
566
- char *dirname = xmemdupz(refname, refname_len - 1);
567
- dir = find_containing_dir(dir, dirname, 0);
568
- free(dirname);
569
- } else {
570
- dir = find_containing_dir(dir, refname, 0);
571
- }
572
- if (!dir)
573
- return -1;
574
- entry_index = search_ref_dir(dir, refname, refname_len);
575
- if (entry_index == -1)
576
- return -1;
577
- entry = dir->entries[entry_index];
578
-
579
- memmove(&dir->entries[entry_index],
580
- &dir->entries[entry_index + 1],
581
- (dir->nr - entry_index - 1) * sizeof(*dir->entries)
582
- );
583
- dir->nr--;
584
- if (dir->sorted > entry_index)
585
- dir->sorted--;
586
- free_ref_entry(entry);
587
- return dir->nr;
267
+ return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
268
}
269
590
-/*
591
- * Add a ref_entry to the ref_dir (unsorted), recursing into
592
- * subdirectories as necessary. dir must represent the top-level
593
- * directory. Return 0 on success.
594
- */
595
-static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
270
+int for_each_branch_ref(each_ref_fn fn, void *cb_data)
271
{
597
- dir = find_containing_dir(dir, ref->name, 1);
598
- if (!dir)
599
- return -1;
600
- add_entry_to_dir(dir, ref);
601
- return 0;
272
+ return for_each_ref_in("refs/heads/", fn, cb_data);
273
}
274
604
-/*
605
- * Emit a warning and return true iff ref1 and ref2 have the same name
606
- * and the same sha1. Die if they have the same name but different
607
- * sha1s.
608
- */
609
-static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
275
+int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
276
{
611
- if (strcmp(ref1->name, ref2->name))
612
- return 0;
613
-
614
- /* Duplicate name; make sure that they don't conflict: */
615
-
616
- if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
617
- /* This is impossible by construction */
618
- die("Reference directory conflict: %s", ref1->name);
619
-
620
- if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
621
- die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
622
-
623
- warning("Duplicated ref: %s", ref1->name);
624
- return 1;
277
+ return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
278
}
279
627
-/*
628
- * Sort the entries in dir non-recursively (if they are not already
629
- * sorted) and remove any duplicate entries.
630
- */
631
-static void sort_ref_dir(struct ref_dir *dir)
280
+int for_each_remote_ref(each_ref_fn fn, void *cb_data)
281
{
633
- int i, j;
634
- struct ref_entry *last = NULL;
635
-
636
- /*
637
- * This check also prevents passing a zero-length array to qsort(),
638
- * which is a problem on some platforms.
639
- */
640
- if (dir->sorted == dir->nr)
641
- return;
642
-
643
- qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
644
-
645
- /* Remove any duplicates: */
646
- for (i = 0, j = 0; j < dir->nr; j++) {
647
- struct ref_entry *entry = dir->entries[j];
648
- if (last && is_dup_ref(last, entry))
649
- free_ref_entry(entry);
650
- else
651
- last = dir->entries[i++] = entry;
652
- }
653
- dir->sorted = dir->nr = i;
282
+ return for_each_ref_in("refs/remotes/", fn, cb_data);
283
}
284
656
-/* Include broken references in a do_for_each_ref*() iteration: */
657
-#define DO_FOR_EACH_INCLUDE_BROKEN 0x01
658
-
659
-/*
660
- * Return true iff the reference described by entry can be resolved to
661
- * an object in the database. Emit a warning if the referred-to
662
- * object does not exist.
663
- */
664
-static int ref_resolves_to_object(struct ref_entry *entry)
285
+int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
286
{
666
- if (entry->flag & REF_ISBROKEN)
667
- return 0;
668
- if (!has_sha1_file(entry->u.value.oid.hash)) {
669
- error("%s does not point to a valid object!", entry->name);
670
- return 0;
671
- }
672
- return 1;
287
+ return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
288
}
289
675
-/*
676
- * current_ref is a performance hack: when iterating over references
677
- * using the for_each_ref*() functions, current_ref is set to the
678
- * current reference's entry before calling the callback function. If
679
- * the callback function calls peel_ref(), then peel_ref() first
680
- * checks whether the reference to be peeled is the current reference
681
- * (it usually is) and if so, returns that reference's peeled version
682
- * if it is available. This avoids a refname lookup in a common case.
683
- */
684
-static struct ref_entry *current_ref;
290
+int head_ref_namespaced(each_ref_fn fn, void *cb_data)
291
+{
292
+ struct strbuf buf = STRBUF_INIT;
293
+ int ret = 0;
294
+ struct object_id oid;
295
+ int flag;
296
686
-typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
297
+ strbuf_addf(&buf, "%sHEAD", get_git_namespace());
298
+ if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
299
+ ret = fn(buf.buf, &oid, flag, cb_data);
300
+ strbuf_release(&buf);
301
688
-struct ref_entry_cb {
689
- const char *base;
690
- int trim;
691
- int flags;
692
- each_ref_fn *fn;
693
- void *cb_data;
694
-};
302
+ return ret;
303
+}
304
696
-/*
697
- * Handle one reference in a do_for_each_ref*()-style iteration,
698
- * calling an each_ref_fn for each entry.
699
- */
700
-static int do_one_ref(struct ref_entry *entry, void *cb_data)
305
+int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
306
+ const char *prefix, void *cb_data)
307
{
702
- struct ref_entry_cb *data = cb_data;
703
- struct ref_entry *old_current_ref;
704
- int retval;
308
+ struct strbuf real_pattern = STRBUF_INIT;
309
+ struct ref_filter filter;
310
+ int ret;
311
706
- if (!starts_with(entry->name, data->base))
707
- return 0;
312
+ if (!prefix && !starts_with(pattern, "refs/"))
313
+ strbuf_addstr(&real_pattern, "refs/");
314
+ else if (prefix)
315
+ strbuf_addstr(&real_pattern, prefix);
316
+ strbuf_addstr(&real_pattern, pattern);
317
709
- if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
710
- !ref_resolves_to_object(entry))
711
- return 0;
318
+ if (!has_glob_specials(pattern)) {
319
+ /* Append implied '/' '*' if not present. */
320
+ strbuf_complete(&real_pattern, '/');
321
+ /* No need to check for '*', there is none. */
322
+ strbuf_addch(&real_pattern, '*');
323
+ }
324
+
325
+ filter.pattern = real_pattern.buf;
326
+ filter.fn = fn;
327
+ filter.cb_data = cb_data;
328
+ ret = for_each_ref(filter_refs, &filter);
329
713
- /* Store the old value, in case this is a recursive call: */
714
- old_current_ref = current_ref;
715
- current_ref = entry;
716
- retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
717
- entry->flag, data->cb_data);
718
- current_ref = old_current_ref;
719
- return retval;
330
+ strbuf_release(&real_pattern);
331
+ return ret;
332
}
333
722
-/*
723
- * Call fn for each reference in dir that has index in the range
724
- * offset <= index < dir->nr. Recurse into subdirectories that are in
725
- * that index range, sorting them before iterating. This function
726
- * does not sort dir itself; it should be sorted beforehand. fn is
727
- * called for all references, including broken ones.
728
- */
729
-static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
730
- each_ref_entry_fn fn, void *cb_data)
731
-{
732
- int i;
733
- assert(dir->sorted == dir->nr);
734
- for (i = offset; i < dir->nr; i++) {
735
- struct ref_entry *entry = dir->entries[i];
736
- int retval;
737
- if (entry->flag & REF_DIR) {
738
- struct ref_dir *subdir = get_ref_dir(entry);
739
- sort_ref_dir(subdir);
740
- retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
741
- } else {
742
- retval = fn(entry, cb_data);
743
- }
744
- if (retval)
745
- return retval;
746
- }
747
- return 0;
748
-}
749
-
750
-/*
751
- * Call fn for each reference in the union of dir1 and dir2, in order
752
- * by refname. Recurse into subdirectories. If a value entry appears
753
- * in both dir1 and dir2, then only process the version that is in
754
- * dir2. The input dirs must already be sorted, but subdirs will be
755
- * sorted as needed. fn is called for all references, including
756
- * broken ones.
757
- */
758
-static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
759
- struct ref_dir *dir2,
760
- each_ref_entry_fn fn, void *cb_data)
761
-{
762
- int retval;
763
- int i1 = 0, i2 = 0;
764
-
765
- assert(dir1->sorted == dir1->nr);
766
- assert(dir2->sorted == dir2->nr);
767
- while (1) {
768
- struct ref_entry *e1, *e2;
769
- int cmp;
770
- if (i1 == dir1->nr) {
771
- return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
772
- }
773
- if (i2 == dir2->nr) {
774
- return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
775
- }
776
- e1 = dir1->entries[i1];
777
- e2 = dir2->entries[i2];
778
- cmp = strcmp(e1->name, e2->name);
779
- if (cmp == 0) {
780
- if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
781
- /* Both are directories; descend them in parallel. */
782
- struct ref_dir *subdir1 = get_ref_dir(e1);
783
- struct ref_dir *subdir2 = get_ref_dir(e2);
784
- sort_ref_dir(subdir1);
785
- sort_ref_dir(subdir2);
786
- retval = do_for_each_entry_in_dirs(
787
- subdir1, subdir2, fn, cb_data);
788
- i1++;
789
- i2++;
790
- } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
791
- /* Both are references; ignore the one from dir1. */
792
- retval = fn(e2, cb_data);
793
- i1++;
794
- i2++;
795
- } else {
796
- die("conflict between reference and directory: %s",
797
- e1->name);
798
- }
799
- } else {
800
- struct ref_entry *e;
801
- if (cmp < 0) {
802
- e = e1;
803
- i1++;
804
- } else {
805
- e = e2;
806
- i2++;
807
- }
808
- if (e->flag & REF_DIR) {
809
- struct ref_dir *subdir = get_ref_dir(e);
810
- sort_ref_dir(subdir);
811
- retval = do_for_each_entry_in_dir(
812
- subdir, 0, fn, cb_data);
813
- } else {
814
- retval = fn(e, cb_data);
815
- }
816
- }
817
- if (retval)
818
- return retval;
819
- }
820
-}
821
-
822
-/*
823
- * Load all of the refs from the dir into our in-memory cache. The hard work
824
- * of loading loose refs is done by get_ref_dir(), so we just need to recurse
825
- * through all of the sub-directories. We do not even need to care about
826
- * sorting, as traversal order does not matter to us.
827
- */
828
-static void prime_ref_dir(struct ref_dir *dir)
829
-{
830
- int i;
831
- for (i = 0; i < dir->nr; i++) {
832
- struct ref_entry *entry = dir->entries[i];
833
- if (entry->flag & REF_DIR)
834
- prime_ref_dir(get_ref_dir(entry));
835
- }
836
-}
837
-
838
-struct nonmatching_ref_data {
839
- const struct string_list *skip;
840
- const char *conflicting_refname;
841
-};
842
-
843
-static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
844
-{
845
- struct nonmatching_ref_data *data = vdata;
846
-
847
- if (data->skip && string_list_has_string(data->skip, entry->name))
848
- return 0;
849
-
850
- data->conflicting_refname = entry->name;
851
- return 1;
852
-}
853
-
854
-/*
855
- * Return 0 if a reference named refname could be created without
856
- * conflicting with the name of an existing reference in dir.
857
- * See verify_refname_available for more information.
858
- */
859
-static int verify_refname_available_dir(const char *refname,
860
- const struct string_list *extras,
861
- const struct string_list *skip,
862
- struct ref_dir *dir,
863
- struct strbuf *err)
864
-{
865
- const char *slash;
866
- int pos;
867
- struct strbuf dirname = STRBUF_INIT;
868
- int ret = -1;
869
-
870
- /*
871
- * For the sake of comments in this function, suppose that
872
- * refname is "refs/foo/bar".
873
- */
874
-
875
- assert(err);
876
-
877
- strbuf_grow(&dirname, strlen(refname) + 1);
878
- for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
879
- /* Expand dirname to the new prefix, not including the trailing slash: */
880
- strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
881
-
882
- /*
883
- * We are still at a leading dir of the refname (e.g.,
884
- * "refs/foo"; if there is a reference with that name,
885
- * it is a conflict, *unless* it is in skip.
886
- */
887
- if (dir) {
888
- pos = search_ref_dir(dir, dirname.buf, dirname.len);
889
- if (pos >= 0 &&
890
- (!skip || !string_list_has_string(skip, dirname.buf))) {
891
- /*
892
- * We found a reference whose name is
893
- * a proper prefix of refname; e.g.,
894
- * "refs/foo", and is not in skip.
895
- */
896
- strbuf_addf(err, "'%s' exists; cannot create '%s'",
897
- dirname.buf, refname);
898
- goto cleanup;
899
- }
900
- }
901
-
902
- if (extras && string_list_has_string(extras, dirname.buf) &&
903
- (!skip || !string_list_has_string(skip, dirname.buf))) {
904
- strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
905
- refname, dirname.buf);
906
- goto cleanup;
907
- }
908
-
909
- /*
910
- * Otherwise, we can try to continue our search with
911
- * the next component. So try to look up the
912
- * directory, e.g., "refs/foo/". If we come up empty,
913
- * we know there is nothing under this whole prefix,
914
- * but even in that case we still have to continue the
915
- * search for conflicts with extras.
916
- */
917
- strbuf_addch(&dirname, '/');
918
- if (dir) {
919
- pos = search_ref_dir(dir, dirname.buf, dirname.len);
920
- if (pos < 0) {
921
- /*
922
- * There was no directory "refs/foo/",
923
- * so there is nothing under this
924
- * whole prefix. So there is no need
925
- * to continue looking for conflicting
926
- * references. But we need to continue
927
- * looking for conflicting extras.
928
- */
929
- dir = NULL;
930
- } else {
931
- dir = get_ref_dir(dir->entries[pos]);
932
- }
933
- }
934
- }
935
-
936
- /*
937
- * We are at the leaf of our refname (e.g., "refs/foo/bar").
938
- * There is no point in searching for a reference with that
939
- * name, because a refname isn't considered to conflict with
940
- * itself. But we still need to check for references whose
941
- * names are in the "refs/foo/bar/" namespace, because they
942
- * *do* conflict.
943
- */
944
- strbuf_addstr(&dirname, refname + dirname.len);
945
- strbuf_addch(&dirname, '/');
946
-
947
- if (dir) {
948
- pos = search_ref_dir(dir, dirname.buf, dirname.len);
949
-
950
- if (pos >= 0) {
951
- /*
952
- * We found a directory named "$refname/"
953
- * (e.g., "refs/foo/bar/"). It is a problem
954
- * iff it contains any ref that is not in
955
- * "skip".
956
- */
957
- struct nonmatching_ref_data data;
958
-
959
- data.skip = skip;
960
- data.conflicting_refname = NULL;
961
- dir = get_ref_dir(dir->entries[pos]);
962
- sort_ref_dir(dir);
963
- if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
964
- strbuf_addf(err, "'%s' exists; cannot create '%s'",
965
- data.conflicting_refname, refname);
966
- goto cleanup;
967
- }
968
- }
969
- }
970
-
971
- if (extras) {
972
- /*
973
- * Check for entries in extras that start with
974
- * "$refname/". We do that by looking for the place
975
- * where "$refname/" would be inserted in extras. If
976
- * there is an entry at that position that starts with
977
- * "$refname/" and is not in skip, then we have a
978
- * conflict.
979
- */
980
- for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
981
- pos < extras->nr; pos++) {
982
- const char *extra_refname = extras->items[pos].string;
983
-
984
- if (!starts_with(extra_refname, dirname.buf))
985
- break;
986
-
987
- if (!skip || !string_list_has_string(skip, extra_refname)) {
988
- strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
989
- refname, extra_refname);
990
- goto cleanup;
991
- }
992
- }
993
- }
994
-
995
- /* No conflicts were found */
996
- ret = 0;
997
-
998
-cleanup:
999
- strbuf_release(&dirname);
1000
- return ret;
1001
-}
1002
-
1003
-struct packed_ref_cache {
1004
- struct ref_entry *root;
1005
-
1006
- /*
1007
- * Count of references to the data structure in this instance,
1008
- * including the pointer from ref_cache::packed if any. The
1009
- * data will not be freed as long as the reference count is
1010
- * nonzero.
1011
- */
1012
- unsigned int referrers;
1013
-
1014
- /*
1015
- * Iff the packed-refs file associated with this instance is
1016
- * currently locked for writing, this points at the associated
1017
- * lock (which is owned by somebody else). The referrer count
1018
- * is also incremented when the file is locked and decremented
1019
- * when it is unlocked.
1020
- */
1021
- struct lock_file *lock;
1022
-
1023
- /* The metadata from when this packed-refs cache was read */
1024
- struct stat_validity validity;
1025
-};
1026
-
1027
-/*
1028
- * Future: need to be in "struct repository"
1029
- * when doing a full libification.
1030
- */
1031
-static struct ref_cache {
1032
- struct ref_cache *next;
1033
- struct ref_entry *loose;
1034
- struct packed_ref_cache *packed;
1035
- /*
1036
- * The submodule name, or "" for the main repo. We allocate
1037
- * length 1 rather than FLEX_ARRAY so that the main ref_cache
1038
- * is initialized correctly.
1039
- */
1040
- char name[1];
1041
-} ref_cache, *submodule_ref_caches;
1042
-
1043
-/* Lock used for the main packed-refs file: */
1044
-static struct lock_file packlock;
1045
-
1046
-/*
1047
- * Increment the reference count of *packed_refs.
1048
- */
1049
-static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1050
-{
1051
- packed_refs->referrers++;
1052
-}
1053
-
1054
-/*
1055
- * Decrease the reference count of *packed_refs. If it goes to zero,
1056
- * free *packed_refs and return true; otherwise return false.
1057
- */
1058
-static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1059
-{
1060
- if (!--packed_refs->referrers) {
1061
- free_ref_entry(packed_refs->root);
1062
- stat_validity_clear(&packed_refs->validity);
1063
- free(packed_refs);
1064
- return 1;
1065
- } else {
1066
- return 0;
1067
- }
1068
-}
1069
-
1070
-static void clear_packed_ref_cache(struct ref_cache *refs)
1071
-{
1072
- if (refs->packed) {
1073
- struct packed_ref_cache *packed_refs = refs->packed;
1074
-
1075
- if (packed_refs->lock)
1076
- die("internal error: packed-ref cache cleared while locked");
1077
- refs->packed = NULL;
1078
- release_packed_ref_cache(packed_refs);
1079
- }
1080
-}
1081
-
1082
-static void clear_loose_ref_cache(struct ref_cache *refs)
1083
-{
1084
- if (refs->loose) {
1085
- free_ref_entry(refs->loose);
1086
- refs->loose = NULL;
1087
- }
1088
-}
1089
-
1090
-static struct ref_cache *create_ref_cache(const char *submodule)
1091
-{
1092
- int len;
1093
- struct ref_cache *refs;
1094
- if (!submodule)
1095
- submodule = "";
1096
- len = strlen(submodule) + 1;
1097
- refs = xcalloc(1, sizeof(struct ref_cache) + len);
1098
- memcpy(refs->name, submodule, len);
1099
- return refs;
1100
-}
1101
-
1102
-/*
1103
- * Return a pointer to a ref_cache for the specified submodule. For
1104
- * the main repository, use submodule==NULL. The returned structure
1105
- * will be allocated and initialized but not necessarily populated; it
1106
- * should not be freed.
1107
- */
1108
-static struct ref_cache *get_ref_cache(const char *submodule)
1109
-{
1110
- struct ref_cache *refs;
1111
-
1112
- if (!submodule || !*submodule)
1113
- return &ref_cache;
1114
-
1115
- for (refs = submodule_ref_caches; refs; refs = refs->next)
1116
- if (!strcmp(submodule, refs->name))
1117
- return refs;
1118
-
1119
- refs = create_ref_cache(submodule);
1120
- refs->next = submodule_ref_caches;
1121
- submodule_ref_caches = refs;
1122
- return refs;
1123
-}
1124
-
1125
-/* The length of a peeled reference line in packed-refs, including EOL: */
1126
-#define PEELED_LINE_LENGTH 42
1127
-
1128
-/*
1129
- * The packed-refs header line that we write out. Perhaps other
1130
- * traits will be added later. The trailing space is required.
1131
- */
1132
-static const char PACKED_REFS_HEADER[] =
1133
- "# pack-refs with: peeled fully-peeled \n";
1134
-
1135
-/*
1136
- * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1137
- * Return a pointer to the refname within the line (null-terminated),
1138
- * or NULL if there was a problem.
1139
- */
1140
-static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1141
-{
1142
- const char *ref;
1143
-
1144
- /*
1145
- * 42: the answer to everything.
1146
- *
1147
- * In this case, it happens to be the answer to
1148
- * 40 (length of sha1 hex representation)
1149
- * +1 (space in between hex and name)
1150
- * +1 (newline at the end of the line)
1151
- */
1152
- if (line->len <= 42)
1153
- return NULL;
1154
-
1155
- if (get_sha1_hex(line->buf, sha1) < 0)
1156
- return NULL;
1157
- if (!isspace(line->buf[40]))
1158
- return NULL;
1159
-
1160
- ref = line->buf + 41;
1161
- if (isspace(*ref))
1162
- return NULL;
1163
-
1164
- if (line->buf[line->len - 1] != '\n')
1165
- return NULL;
1166
- line->buf[--line->len] = 0;
1167
-
1168
- return ref;
1169
-}
1170
-
1171
-/*
1172
- * Read f, which is a packed-refs file, into dir.
1173
- *
1174
- * A comment line of the form "# pack-refs with: " may contain zero or
1175
- * more traits. We interpret the traits as follows:
1176
- *
1177
- * No traits:
1178
- *
1179
- * Probably no references are peeled. But if the file contains a
1180
- * peeled value for a reference, we will use it.
1181
- *
1182
- * peeled:
1183
- *
1184
- * References under "refs/tags/", if they *can* be peeled, *are*
1185
- * peeled in this file. References outside of "refs/tags/" are
1186
- * probably not peeled even if they could have been, but if we find
1187
- * a peeled value for such a reference we will use it.
1188
- *
1189
- * fully-peeled:
1190
- *
1191
- * All references in the file that can be peeled are peeled.
1192
- * Inversely (and this is more important), any references in the
1193
- * file for which no peeled value is recorded is not peelable. This
1194
- * trait should typically be written alongside "peeled" for
1195
- * compatibility with older clients, but we do not require it
1196
- * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1197
- */
1198
-static void read_packed_refs(FILE *f, struct ref_dir *dir)
1199
-{
1200
- struct ref_entry *last = NULL;
1201
- struct strbuf line = STRBUF_INIT;
1202
- enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1203
-
1204
- while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1205
- unsigned char sha1[20];
1206
- const char *refname;
1207
- const char *traits;
1208
-
1209
- if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1210
- if (strstr(traits, " fully-peeled "))
1211
- peeled = PEELED_FULLY;
1212
- else if (strstr(traits, " peeled "))
1213
- peeled = PEELED_TAGS;
1214
- /* perhaps other traits later as well */
1215
- continue;
1216
- }
1217
-
1218
- refname = parse_ref_line(&line, sha1);
1219
- if (refname) {
1220
- int flag = REF_ISPACKED;
1221
-
1222
- if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1223
- if (!refname_is_safe(refname))
1224
- die("packed refname is dangerous: %s", refname);
1225
- hashclr(sha1);
1226
- flag |= REF_BAD_NAME | REF_ISBROKEN;
1227
- }
1228
- last = create_ref_entry(refname, sha1, flag, 0);
1229
- if (peeled == PEELED_FULLY ||
1230
- (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1231
- last->flag |= REF_KNOWS_PEELED;
1232
- add_ref(dir, last);
1233
- continue;
1234
- }
1235
- if (last &&
1236
- line.buf[0] == '^' &&
1237
- line.len == PEELED_LINE_LENGTH &&
1238
- line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1239
- !get_sha1_hex(line.buf + 1, sha1)) {
1240
- hashcpy(last->u.value.peeled.hash, sha1);
1241
- /*
1242
- * Regardless of what the file header said,
1243
- * we definitely know the value of *this*
1244
- * reference:
1245
- */
1246
- last->flag |= REF_KNOWS_PEELED;
1247
- }
1248
- }
1249
-
1250
- strbuf_release(&line);
1251
-}
1252
-
1253
-/*
1254
- * Get the packed_ref_cache for the specified ref_cache, creating it
1255
- * if necessary.
1256
- */
1257
-static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1258
-{
1259
- char *packed_refs_file;
1260
-
1261
- if (*refs->name)
1262
- packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1263
- else
1264
- packed_refs_file = git_pathdup("packed-refs");
1265
-
1266
- if (refs->packed &&
1267
- !stat_validity_check(&refs->packed->validity, packed_refs_file))
1268
- clear_packed_ref_cache(refs);
1269
-
1270
- if (!refs->packed) {
1271
- FILE *f;
1272
-
1273
- refs->packed = xcalloc(1, sizeof(*refs->packed));
1274
- acquire_packed_ref_cache(refs->packed);
1275
- refs->packed->root = create_dir_entry(refs, "", 0, 0);
1276
- f = fopen(packed_refs_file, "r");
1277
- if (f) {
1278
- stat_validity_update(&refs->packed->validity, fileno(f));
1279
- read_packed_refs(f, get_ref_dir(refs->packed->root));
1280
- fclose(f);
1281
- }
1282
- }
1283
- free(packed_refs_file);
1284
- return refs->packed;
1285
-}
1286
-
1287
-static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1288
-{
1289
- return get_ref_dir(packed_ref_cache->root);
1290
-}
1291
-
1292
-static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1293
-{
1294
- return get_packed_ref_dir(get_packed_ref_cache(refs));
1295
-}
1296
-
1297
-/*
1298
- * Add a reference to the in-memory packed reference cache. This may
1299
- * only be called while the packed-refs file is locked (see
1300
- * lock_packed_refs()). To actually write the packed-refs file, call
1301
- * commit_packed_refs().
1302
- */
1303
-static void add_packed_ref(const char *refname, const unsigned char *sha1)
1304
-{
1305
- struct packed_ref_cache *packed_ref_cache =
1306
- get_packed_ref_cache(&ref_cache);
1307
-
1308
- if (!packed_ref_cache->lock)
1309
- die("internal error: packed refs not locked");
1310
- add_ref(get_packed_ref_dir(packed_ref_cache),
1311
- create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1312
-}
1313
-
1314
-/*
1315
- * Read the loose references from the namespace dirname into dir
1316
- * (without recursing). dirname must end with '/'. dir must be the
1317
- * directory entry corresponding to dirname.
1318
- */
1319
-static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1320
-{
1321
- struct ref_cache *refs = dir->ref_cache;
1322
- DIR *d;
1323
- struct dirent *de;
1324
- int dirnamelen = strlen(dirname);
1325
- struct strbuf refname;
1326
- struct strbuf path = STRBUF_INIT;
1327
- size_t path_baselen;
1328
-
1329
- if (*refs->name)
1330
- strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1331
- else
1332
- strbuf_git_path(&path, "%s", dirname);
1333
- path_baselen = path.len;
1334
-
1335
- d = opendir(path.buf);
1336
- if (!d) {
1337
- strbuf_release(&path);
1338
- return;
1339
- }
1340
-
1341
- strbuf_init(&refname, dirnamelen + 257);
1342
- strbuf_add(&refname, dirname, dirnamelen);
1343
-
1344
- while ((de = readdir(d)) != NULL) {
1345
- unsigned char sha1[20];
1346
- struct stat st;
1347
- int flag;
1348
-
1349
- if (de->d_name[0] == '.')
1350
- continue;
1351
- if (ends_with(de->d_name, ".lock"))
1352
- continue;
1353
- strbuf_addstr(&refname, de->d_name);
1354
- strbuf_addstr(&path, de->d_name);
1355
- if (stat(path.buf, &st) < 0) {
1356
- ; /* silently ignore */
1357
- } else if (S_ISDIR(st.st_mode)) {
1358
- strbuf_addch(&refname, '/');
1359
- add_entry_to_dir(dir,
1360
- create_dir_entry(refs, refname.buf,
1361
- refname.len, 1));
1362
- } else {
1363
- int read_ok;
1364
-
1365
- if (*refs->name) {
1366
- hashclr(sha1);
1367
- flag = 0;
1368
- read_ok = !resolve_gitlink_ref(refs->name,
1369
- refname.buf, sha1);
1370
- } else {
1371
- read_ok = !read_ref_full(refname.buf,
1372
- RESOLVE_REF_READING,
1373
- sha1, &flag);
1374
- }
1375
-
1376
- if (!read_ok) {
1377
- hashclr(sha1);
1378
- flag |= REF_ISBROKEN;
1379
- } else if (is_null_sha1(sha1)) {
1380
- /*
1381
- * It is so astronomically unlikely
1382
- * that NULL_SHA1 is the SHA-1 of an
1383
- * actual object that we consider its
1384
- * appearance in a loose reference
1385
- * file to be repo corruption
1386
- * (probably due to a software bug).
1387
- */
1388
- flag |= REF_ISBROKEN;
1389
- }
1390
-
1391
- if (check_refname_format(refname.buf,
1392
- REFNAME_ALLOW_ONELEVEL)) {
1393
- if (!refname_is_safe(refname.buf))
1394
- die("loose refname is dangerous: %s", refname.buf);
1395
- hashclr(sha1);
1396
- flag |= REF_BAD_NAME | REF_ISBROKEN;
1397
- }
1398
- add_entry_to_dir(dir,
1399
- create_ref_entry(refname.buf, sha1, flag, 0));
1400
- }
1401
- strbuf_setlen(&refname, dirnamelen);
1402
- strbuf_setlen(&path, path_baselen);
1403
- }
1404
- strbuf_release(&refname);
1405
- strbuf_release(&path);
1406
- closedir(d);
1407
-}
1408
-
1409
-static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1410
-{
1411
- if (!refs->loose) {
1412
- /*
1413
- * Mark the top-level directory complete because we
1414
- * are about to read the only subdirectory that can
1415
- * hold references:
1416
- */
1417
- refs->loose = create_dir_entry(refs, "", 0, 0);
1418
- /*
1419
- * Create an incomplete entry for "refs/":
1420
- */
1421
- add_entry_to_dir(get_ref_dir(refs->loose),
1422
- create_dir_entry(refs, "refs/", 5, 1));
1423
- }
1424
- return get_ref_dir(refs->loose);
1425
-}
1426
-
1427
-/* We allow "recursive" symbolic refs. Only within reason, though */
1428
-#define MAXDEPTH 5
1429
-#define MAXREFLEN (1024)
1430
-
1431
-/*
1432
- * Called by resolve_gitlink_ref_recursive() after it failed to read
1433
- * from the loose refs in ref_cache refs. Find <refname> in the
1434
- * packed-refs file for the submodule.
1435
- */
1436
-static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1437
- const char *refname, unsigned char *sha1)
1438
-{
1439
- struct ref_entry *ref;
1440
- struct ref_dir *dir = get_packed_refs(refs);
1441
-
1442
- ref = find_ref(dir, refname);
1443
- if (ref == NULL)
1444
- return -1;
1445
-
1446
- hashcpy(sha1, ref->u.value.oid.hash);
1447
- return 0;
1448
-}
1449
-
1450
-static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1451
- const char *refname, unsigned char *sha1,
1452
- int recursion)
1453
-{
1454
- int fd, len;
1455
- char buffer[128], *p;
1456
- char *path;
1457
-
1458
- if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1459
- return -1;
1460
- path = *refs->name
1461
- ? git_pathdup_submodule(refs->name, "%s", refname)
1462
- : git_pathdup("%s", refname);
1463
- fd = open(path, O_RDONLY);
1464
- free(path);
1465
- if (fd < 0)
1466
- return resolve_gitlink_packed_ref(refs, refname, sha1);
1467
-
1468
- len = read(fd, buffer, sizeof(buffer)-1);
1469
- close(fd);
1470
- if (len < 0)
1471
- return -1;
1472
- while (len && isspace(buffer[len-1]))
1473
- len--;
1474
- buffer[len] = 0;
1475
-
1476
- /* Was it a detached head or an old-fashioned symlink? */
1477
- if (!get_sha1_hex(buffer, sha1))
1478
- return 0;
1479
-
1480
- /* Symref? */
1481
- if (strncmp(buffer, "ref:", 4))
1482
- return -1;
1483
- p = buffer + 4;
1484
- while (isspace(*p))
1485
- p++;
1486
-
1487
- return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1488
-}
1489
-
1490
-int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1491
-{
1492
- int len = strlen(path), retval;
1493
- char *submodule;
1494
- struct ref_cache *refs;
1495
-
1496
- while (len && path[len-1] == '/')
1497
- len--;
1498
- if (!len)
1499
- return -1;
1500
- submodule = xstrndup(path, len);
1501
- refs = get_ref_cache(submodule);
1502
- free(submodule);
1503
-
1504
- retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1505
- return retval;
1506
-}
1507
-
1508
-/*
1509
- * Return the ref_entry for the given refname from the packed
1510
- * references. If it does not exist, return NULL.
1511
- */
1512
-static struct ref_entry *get_packed_ref(const char *refname)
1513
-{
1514
- return find_ref(get_packed_refs(&ref_cache), refname);
1515
-}
1516
-
1517
-/*
1518
- * A loose ref file doesn't exist; check for a packed ref. The
1519
- * options are forwarded from resolve_safe_unsafe().
1520
- */
1521
-static int resolve_missing_loose_ref(const char *refname,
1522
- int resolve_flags,
1523
- unsigned char *sha1,
1524
- int *flags)
1525
-{
1526
- struct ref_entry *entry;
1527
-
1528
- /*
1529
- * The loose reference file does not exist; check for a packed
1530
- * reference.
1531
- */
1532
- entry = get_packed_ref(refname);
1533
- if (entry) {
1534
- hashcpy(sha1, entry->u.value.oid.hash);
1535
- if (flags)
1536
- *flags |= REF_ISPACKED;
1537
- return 0;
1538
- }
1539
- /* The reference is not a packed reference, either. */
1540
- if (resolve_flags & RESOLVE_REF_READING) {
1541
- errno = ENOENT;
1542
- return -1;
1543
- } else {
1544
- hashclr(sha1);
1545
- return 0;
1546
- }
1547
-}
1548
-
1549
-/* This function needs to return a meaningful errno on failure */
1550
-static const char *resolve_ref_1(const char *refname,
1551
- int resolve_flags,
1552
- unsigned char *sha1,
1553
- int *flags,
1554
- struct strbuf *sb_refname,
1555
- struct strbuf *sb_path,
1556
- struct strbuf *sb_contents)
1557
-{
1558
- int depth = MAXDEPTH;
1559
- int bad_name = 0;
1560
-
1561
- if (flags)
1562
- *flags = 0;
1563
-
1564
- if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1565
- if (flags)
1566
- *flags |= REF_BAD_NAME;
1567
-
1568
- if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1569
- !refname_is_safe(refname)) {
1570
- errno = EINVAL;
1571
- return NULL;
1572
- }
1573
- /*
1574
- * dwim_ref() uses REF_ISBROKEN to distinguish between
1575
- * missing refs and refs that were present but invalid,
1576
- * to complain about the latter to stderr.
1577
- *
1578
- * We don't know whether the ref exists, so don't set
1579
- * REF_ISBROKEN yet.
1580
- */
1581
- bad_name = 1;
1582
- }
1583
- for (;;) {
1584
- const char *path;
1585
- struct stat st;
1586
- char *buf;
1587
- int fd;
1588
-
1589
- if (--depth < 0) {
1590
- errno = ELOOP;
1591
- return NULL;
1592
- }
1593
-
1594
- strbuf_reset(sb_path);
1595
- strbuf_git_path(sb_path, "%s", refname);
1596
- path = sb_path->buf;
1597
-
1598
- /*
1599
- * We might have to loop back here to avoid a race
1600
- * condition: first we lstat() the file, then we try
1601
- * to read it as a link or as a file. But if somebody
1602
- * changes the type of the file (file <-> directory
1603
- * <-> symlink) between the lstat() and reading, then
1604
- * we don't want to report that as an error but rather
1605
- * try again starting with the lstat().
1606
- */
1607
- stat_ref:
1608
- if (lstat(path, &st) < 0) {
1609
- if (errno != ENOENT)
1610
- return NULL;
1611
- if (resolve_missing_loose_ref(refname, resolve_flags,
1612
- sha1, flags))
1613
- return NULL;
1614
- if (bad_name) {
1615
- hashclr(sha1);
1616
- if (flags)
1617
- *flags |= REF_ISBROKEN;
1618
- }
1619
- return refname;
1620
- }
1621
-
1622
- /* Follow "normalized" - ie "refs/.." symlinks by hand */
1623
- if (S_ISLNK(st.st_mode)) {
1624
- strbuf_reset(sb_contents);
1625
- if (strbuf_readlink(sb_contents, path, 0) < 0) {
1626
- if (errno == ENOENT || errno == EINVAL)
1627
- /* inconsistent with lstat; retry */
1628
- goto stat_ref;
1629
- else
1630
- return NULL;
1631
- }
1632
- if (starts_with(sb_contents->buf, "refs/") &&
1633
- !check_refname_format(sb_contents->buf, 0)) {
1634
- strbuf_swap(sb_refname, sb_contents);
1635
- refname = sb_refname->buf;
1636
- if (flags)
1637
- *flags |= REF_ISSYMREF;
1638
- if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1639
- hashclr(sha1);
1640
- return refname;
1641
- }
1642
- continue;
1643
- }
1644
- }
1645
-
1646
- /* Is it a directory? */
1647
- if (S_ISDIR(st.st_mode)) {
1648
- errno = EISDIR;
1649
- return NULL;
1650
- }
1651
-
1652
- /*
1653
- * Anything else, just open it and try to use it as
1654
- * a ref
1655
- */
1656
- fd = open(path, O_RDONLY);
1657
- if (fd < 0) {
1658
- if (errno == ENOENT)
1659
- /* inconsistent with lstat; retry */
1660
- goto stat_ref;
1661
- else
1662
- return NULL;
1663
- }
1664
- strbuf_reset(sb_contents);
1665
- if (strbuf_read(sb_contents, fd, 256) < 0) {
1666
- int save_errno = errno;
1667
- close(fd);
1668
- errno = save_errno;
1669
- return NULL;
1670
- }
1671
- close(fd);
1672
- strbuf_rtrim(sb_contents);
1673
-
1674
- /*
1675
- * Is it a symbolic ref?
1676
- */
1677
- if (!starts_with(sb_contents->buf, "ref:")) {
1678
- /*
1679
- * Please note that FETCH_HEAD has a second
1680
- * line containing other data.
1681
- */
1682
- if (get_sha1_hex(sb_contents->buf, sha1) ||
1683
- (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1684
- if (flags)
1685
- *flags |= REF_ISBROKEN;
1686
- errno = EINVAL;
1687
- return NULL;
1688
- }
1689
- if (bad_name) {
1690
- hashclr(sha1);
1691
- if (flags)
1692
- *flags |= REF_ISBROKEN;
1693
- }
1694
- return refname;
1695
- }
1696
- if (flags)
1697
- *flags |= REF_ISSYMREF;
1698
- buf = sb_contents->buf + 4;
1699
- while (isspace(*buf))
1700
- buf++;
1701
- strbuf_reset(sb_refname);
1702
- strbuf_addstr(sb_refname, buf);
1703
- refname = sb_refname->buf;
1704
- if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1705
- hashclr(sha1);
1706
- return refname;
1707
- }
1708
- if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1709
- if (flags)
1710
- *flags |= REF_ISBROKEN;
1711
-
1712
- if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1713
- !refname_is_safe(buf)) {
1714
- errno = EINVAL;
1715
- return NULL;
1716
- }
1717
- bad_name = 1;
1718
- }
1719
- }
1720
-}
1721
-
1722
-const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1723
- unsigned char *sha1, int *flags)
1724
-{
1725
- static struct strbuf sb_refname = STRBUF_INIT;
1726
- struct strbuf sb_contents = STRBUF_INIT;
1727
- struct strbuf sb_path = STRBUF_INIT;
1728
- const char *ret;
1729
-
1730
- ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1731
- &sb_refname, &sb_path, &sb_contents);
1732
- strbuf_release(&sb_path);
1733
- strbuf_release(&sb_contents);
1734
- return ret;
1735
-}
1736
-
1737
-char *resolve_refdup(const char *refname, int resolve_flags,
1738
- unsigned char *sha1, int *flags)
1739
-{
1740
- return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1741
- sha1, flags));
1742
-}
1743
-
1744
-/* The argument to filter_refs */
1745
-struct ref_filter {
1746
- const char *pattern;
1747
- each_ref_fn *fn;
1748
- void *cb_data;
1749
-};
1750
-
1751
-int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1752
-{
1753
- if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1754
- return 0;
1755
- return -1;
1756
-}
1757
-
1758
-int read_ref(const char *refname, unsigned char *sha1)
1759
-{
1760
- return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1761
-}
1762
-
1763
-int ref_exists(const char *refname)
1764
-{
1765
- unsigned char sha1[20];
1766
- return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1767
-}
1768
-
1769
-static int filter_refs(const char *refname, const struct object_id *oid,
1770
- int flags, void *data)
1771
-{
1772
- struct ref_filter *filter = (struct ref_filter *)data;
1773
-
1774
- if (wildmatch(filter->pattern, refname, 0, NULL))
1775
- return 0;
1776
- return filter->fn(refname, oid, flags, filter->cb_data);
1777
-}
1778
-
1779
-enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1780
-{
1781
- struct object *o = lookup_unknown_object(name);
1782
-
1783
- if (o->type == OBJ_NONE) {
1784
- int type = sha1_object_info(name, NULL);
1785
- if (type < 0 || !object_as_type(o, type, 0))
1786
- return PEEL_INVALID;
1787
- }
1788
-
1789
- if (o->type != OBJ_TAG)
1790
- return PEEL_NON_TAG;
1791
-
1792
- o = deref_tag_noverify(o);
1793
- if (!o)
1794
- return PEEL_INVALID;
1795
-
1796
- hashcpy(sha1, o->sha1);
1797
- return PEEL_PEELED;
1798
-}
1799
-
1800
-/*
1801
- * Peel the entry (if possible) and return its new peel_status. If
1802
- * repeel is true, re-peel the entry even if there is an old peeled
1803
- * value that is already stored in it.
1804
- *
1805
- * It is OK to call this function with a packed reference entry that
1806
- * might be stale and might even refer to an object that has since
1807
- * been garbage-collected. In such a case, if the entry has
1808
- * REF_KNOWS_PEELED then leave the status unchanged and return
1809
- * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1810
- */
1811
-static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1812
-{
1813
- enum peel_status status;
1814
-
1815
- if (entry->flag & REF_KNOWS_PEELED) {
1816
- if (repeel) {
1817
- entry->flag &= ~REF_KNOWS_PEELED;
1818
- oidclr(&entry->u.value.peeled);
1819
- } else {
1820
- return is_null_oid(&entry->u.value.peeled) ?
1821
- PEEL_NON_TAG : PEEL_PEELED;
1822
- }
1823
- }
1824
- if (entry->flag & REF_ISBROKEN)
1825
- return PEEL_BROKEN;
1826
- if (entry->flag & REF_ISSYMREF)
1827
- return PEEL_IS_SYMREF;
1828
-
1829
- status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1830
- if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1831
- entry->flag |= REF_KNOWS_PEELED;
1832
- return status;
1833
-}
1834
-
1835
-int peel_ref(const char *refname, unsigned char *sha1)
1836
-{
1837
- int flag;
1838
- unsigned char base[20];
1839
-
1840
- if (current_ref && (current_ref->name == refname
1841
- || !strcmp(current_ref->name, refname))) {
1842
- if (peel_entry(current_ref, 0))
1843
- return -1;
1844
- hashcpy(sha1, current_ref->u.value.peeled.hash);
1845
- return 0;
1846
- }
1847
-
1848
- if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1849
- return -1;
1850
-
1851
- /*
1852
- * If the reference is packed, read its ref_entry from the
1853
- * cache in the hope that we already know its peeled value.
1854
- * We only try this optimization on packed references because
1855
- * (a) forcing the filling of the loose reference cache could
1856
- * be expensive and (b) loose references anyway usually do not
1857
- * have REF_KNOWS_PEELED.
1858
- */
1859
- if (flag & REF_ISPACKED) {
1860
- struct ref_entry *r = get_packed_ref(refname);
1861
- if (r) {
1862
- if (peel_entry(r, 0))
1863
- return -1;
1864
- hashcpy(sha1, r->u.value.peeled.hash);
1865
- return 0;
1866
- }
1867
- }
1868
-
1869
- return peel_object(base, sha1);
1870
-}
1871
-
1872
-struct warn_if_dangling_data {
1873
- FILE *fp;
1874
- const char *refname;
1875
- const struct string_list *refnames;
1876
- const char *msg_fmt;
1877
-};
1878
-
1879
-static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1880
- int flags, void *cb_data)
1881
-{
1882
- struct warn_if_dangling_data *d = cb_data;
1883
- const char *resolves_to;
1884
- struct object_id junk;
1885
-
1886
- if (!(flags & REF_ISSYMREF))
1887
- return 0;
1888
-
1889
- resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1890
- if (!resolves_to
1891
- || (d->refname
1892
- ? strcmp(resolves_to, d->refname)
1893
- : !string_list_has_string(d->refnames, resolves_to))) {
1894
- return 0;
1895
- }
1896
-
1897
- fprintf(d->fp, d->msg_fmt, refname);
1898
- fputc('\n', d->fp);
1899
- return 0;
1900
-}
1901
-
1902
-void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1903
-{
1904
- struct warn_if_dangling_data data;
1905
-
1906
- data.fp = fp;
1907
- data.refname = refname;
1908
- data.refnames = NULL;
1909
- data.msg_fmt = msg_fmt;
1910
- for_each_rawref(warn_if_dangling_symref, &data);
1911
-}
1912
-
1913
-void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1914
-{
1915
- struct warn_if_dangling_data data;
1916
-
1917
- data.fp = fp;
1918
- data.refname = NULL;
1919
- data.refnames = refnames;
1920
- data.msg_fmt = msg_fmt;
1921
- for_each_rawref(warn_if_dangling_symref, &data);
1922
-}
1923
-
1924
-/*
1925
- * Call fn for each reference in the specified ref_cache, omitting
1926
- * references not in the containing_dir of base. fn is called for all
1927
- * references, including broken ones. If fn ever returns a non-zero
1928
- * value, stop the iteration and return that value; otherwise, return
1929
- * 0.
1930
- */
1931
-static int do_for_each_entry(struct ref_cache *refs, const char *base,
1932
- each_ref_entry_fn fn, void *cb_data)
1933
-{
1934
- struct packed_ref_cache *packed_ref_cache;
1935
- struct ref_dir *loose_dir;
1936
- struct ref_dir *packed_dir;
1937
- int retval = 0;
1938
-
1939
- /*
1940
- * We must make sure that all loose refs are read before accessing the
1941
- * packed-refs file; this avoids a race condition in which loose refs
1942
- * are migrated to the packed-refs file by a simultaneous process, but
1943
- * our in-memory view is from before the migration. get_packed_ref_cache()
1944
- * takes care of making sure our view is up to date with what is on
1945
- * disk.
1946
- */
1947
- loose_dir = get_loose_refs(refs);
1948
- if (base && *base) {
1949
- loose_dir = find_containing_dir(loose_dir, base, 0);
1950
- }
1951
- if (loose_dir)
1952
- prime_ref_dir(loose_dir);
1953
-
1954
- packed_ref_cache = get_packed_ref_cache(refs);
1955
- acquire_packed_ref_cache(packed_ref_cache);
1956
- packed_dir = get_packed_ref_dir(packed_ref_cache);
1957
- if (base && *base) {
1958
- packed_dir = find_containing_dir(packed_dir, base, 0);
1959
- }
1960
-
1961
- if (packed_dir && loose_dir) {
1962
- sort_ref_dir(packed_dir);
1963
- sort_ref_dir(loose_dir);
1964
- retval = do_for_each_entry_in_dirs(
1965
- packed_dir, loose_dir, fn, cb_data);
1966
- } else if (packed_dir) {
1967
- sort_ref_dir(packed_dir);
1968
- retval = do_for_each_entry_in_dir(
1969
- packed_dir, 0, fn, cb_data);
1970
- } else if (loose_dir) {
1971
- sort_ref_dir(loose_dir);
1972
- retval = do_for_each_entry_in_dir(
1973
- loose_dir, 0, fn, cb_data);
1974
- }
1975
-
1976
- release_packed_ref_cache(packed_ref_cache);
1977
- return retval;
1978
-}
1979
-
1980
-/*
1981
- * Call fn for each reference in the specified ref_cache for which the
1982
- * refname begins with base. If trim is non-zero, then trim that many
1983
- * characters off the beginning of each refname before passing the
1984
- * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1985
- * broken references in the iteration. If fn ever returns a non-zero
1986
- * value, stop the iteration and return that value; otherwise, return
1987
- * 0.
1988
- */
1989
-static int do_for_each_ref(struct ref_cache *refs, const char *base,
1990
- each_ref_fn fn, int trim, int flags, void *cb_data)
1991
-{
1992
- struct ref_entry_cb data;
1993
- data.base = base;
1994
- data.trim = trim;
1995
- data.flags = flags;
1996
- data.fn = fn;
1997
- data.cb_data = cb_data;
1998
-
1999
- if (ref_paranoia < 0)
2000
- ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2001
- if (ref_paranoia)
2002
- data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2003
-
2004
- return do_for_each_entry(refs, base, do_one_ref, &data);
2005
-}
2006
-
2007
-static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2008
-{
2009
- struct object_id oid;
2010
- int flag;
2011
-
2012
- if (submodule) {
2013
- if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2014
- return fn("HEAD", &oid, 0, cb_data);
2015
-
2016
- return 0;
2017
- }
2018
-
2019
- if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2020
- return fn("HEAD", &oid, flag, cb_data);
2021
-
2022
- return 0;
2023
-}
2024
-
2025
-int head_ref(each_ref_fn fn, void *cb_data)
2026
-{
2027
- return do_head_ref(NULL, fn, cb_data);
2028
-}
2029
-
2030
-int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2031
-{
2032
- return do_head_ref(submodule, fn, cb_data);
2033
-}
2034
-
2035
-int for_each_ref(each_ref_fn fn, void *cb_data)
2036
-{
2037
- return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2038
-}
2039
-
2040
-int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2041
-{
2042
- return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2043
-}
2044
-
2045
-int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2046
-{
2047
- return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2048
-}
2049
-
2050
-int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
2051
-{
2052
- unsigned int flag = 0;
2053
-
2054
- if (broken)
2055
- flag = DO_FOR_EACH_INCLUDE_BROKEN;
2056
- return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
2057
-}
2058
-
2059
-int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2060
- each_ref_fn fn, void *cb_data)
2061
-{
2062
- return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2063
-}
2064
-
2065
-int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2066
-{
2067
- return for_each_ref_in("refs/tags/", fn, cb_data);
2068
-}
2069
-
2070
-int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2071
-{
2072
- return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2073
-}
2074
-
2075
-int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2076
-{
2077
- return for_each_ref_in("refs/heads/", fn, cb_data);
2078
-}
2079
-
2080
-int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2081
-{
2082
- return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2083
-}
2084
-
2085
-int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2086
-{
2087
- return for_each_ref_in("refs/remotes/", fn, cb_data);
2088
-}
2089
-
2090
-int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2091
-{
2092
- return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2093
-}
2094
-
2095
-int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2096
-{
2097
- return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2098
- strlen(git_replace_ref_base), 0, cb_data);
2099
-}
2100
-
2101
-int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2102
-{
2103
- struct strbuf buf = STRBUF_INIT;
2104
- int ret = 0;
2105
- struct object_id oid;
2106
- int flag;
2107
-
2108
- strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2109
- if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2110
- ret = fn(buf.buf, &oid, flag, cb_data);
2111
- strbuf_release(&buf);
2112
-
2113
- return ret;
2114
-}
2115
-
2116
-int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2117
-{
2118
- struct strbuf buf = STRBUF_INIT;
2119
- int ret;
2120
- strbuf_addf(&buf, "%srefs/", get_git_namespace());
2121
- ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2122
- strbuf_release(&buf);
2123
- return ret;
2124
-}
2125
-
2126
-int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2127
- const char *prefix, void *cb_data)
2128
-{
2129
- struct strbuf real_pattern = STRBUF_INIT;
2130
- struct ref_filter filter;
2131
- int ret;
2132
-
2133
- if (!prefix && !starts_with(pattern, "refs/"))
2134
- strbuf_addstr(&real_pattern, "refs/");
2135
- else if (prefix)
2136
- strbuf_addstr(&real_pattern, prefix);
2137
- strbuf_addstr(&real_pattern, pattern);
2138
-
2139
- if (!has_glob_specials(pattern)) {
2140
- /* Append implied '/' '*' if not present. */
2141
- strbuf_complete(&real_pattern, '/');
2142
- /* No need to check for '*', there is none. */
2143
- strbuf_addch(&real_pattern, '*');
2144
- }
2145
-
2146
- filter.pattern = real_pattern.buf;
2147
- filter.fn = fn;
2148
- filter.cb_data = cb_data;
2149
- ret = for_each_ref(filter_refs, &filter);
2150
-
2151
- strbuf_release(&real_pattern);
2152
- return ret;
2153
-}
2154
-
2155
-int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
334
+int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
335
{
336
return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
337
}
338
2160
-int for_each_rawref(each_ref_fn fn, void *cb_data)
2161
-{
2162
- return do_for_each_ref(&ref_cache, "", fn, 0,
2163
- DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2164
-}
2165
-
339
const char *prettify_refname(const char *name)
340
{
341
return name + (
342
starts_with(name, "refs/heads/") ? 11 :
2170
- starts_with(name, "refs/tags/") ? 10 :
2171
- starts_with(name, "refs/remotes/") ? 13 :
2172
- 0);
2173
-}
2174
-
2175
-static const char *ref_rev_parse_rules[] = {
2176
- "%.*s",
2177
- "refs/%.*s",
2178
- "refs/tags/%.*s",
2179
- "refs/heads/%.*s",
2180
- "refs/remotes/%.*s",
2181
- "refs/remotes/%.*s/HEAD",
2182
- NULL
2183
-};
2184
-
2185
-int refname_match(const char *abbrev_name, const char *full_name)
2186
-{
2187
- const char **p;
2188
- const int abbrev_name_len = strlen(abbrev_name);
2189
-
2190
- for (p = ref_rev_parse_rules; *p; p++) {
2191
- if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2192
- return 1;
2193
- }
2194
- }
2195
-
2196
- return 0;
2197
-}
2198
-
2199
-static void unlock_ref(struct ref_lock *lock)
2200
-{
2201
- /* Do not free lock->lk -- atexit() still looks at them */
2202
- if (lock->lk)
2203
- rollback_lock_file(lock->lk);
2204
- free(lock->ref_name);
2205
- free(lock->orig_ref_name);
2206
- free(lock);
2207
-}
2208
-
2209
-/*
2210
- * Verify that the reference locked by lock has the value old_sha1.
2211
- * Fail if the reference doesn't exist and mustexist is set. Return 0
2212
- * on success. On error, write an error message to err, set errno, and
2213
- * return a negative value.
2214
- */
2215
-static int verify_lock(struct ref_lock *lock,
2216
- const unsigned char *old_sha1, int mustexist,
2217
- struct strbuf *err)
2218
-{
2219
- assert(err);
2220
-
2221
- if (read_ref_full(lock->ref_name,
2222
- mustexist ? RESOLVE_REF_READING : 0,
2223
- lock->old_oid.hash, NULL)) {
2224
- int save_errno = errno;
2225
- strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2226
- errno = save_errno;
2227
- return -1;
2228
- }
2229
- if (hashcmp(lock->old_oid.hash, old_sha1)) {
2230
- strbuf_addf(err, "ref %s is at %s but expected %s",
2231
- lock->ref_name,
2232
- sha1_to_hex(lock->old_oid.hash),
2233
- sha1_to_hex(old_sha1));
2234
- errno = EBUSY;
2235
- return -1;
2236
- }
2237
- return 0;
2238
-}
2239
-
2240
-static int remove_empty_directories(struct strbuf *path)
2241
-{
2242
- /*
2243
- * we want to create a file but there is a directory there;
2244
- * if that is an empty directory (or a directory that contains
2245
- * only empty directories), remove them.
2246
- */
2247
- return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
2248
-}
2249
-
2250
-/*
2251
- * *string and *len will only be substituted, and *string returned (for
2252
- * later free()ing) if the string passed in is a magic short-hand form
2253
- * to name a branch.
2254
- */
2255
-static char *substitute_branch_name(const char **string, int *len)
2256
-{
2257
- struct strbuf buf = STRBUF_INIT;
2258
- int ret = interpret_branch_name(*string, *len, &buf);
2259
-
2260
- if (ret == *len) {
2261
- size_t size;
2262
- *string = strbuf_detach(&buf, &size);
2263
- *len = size;
2264
- return (char *)*string;
2265
- }
2266
-
2267
- return NULL;
2268
-}
2269
-
2270
-int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2271
-{
2272
- char *last_branch = substitute_branch_name(&str, &len);
2273
- const char **p, *r;
2274
- int refs_found = 0;
2275
-
2276
- *ref = NULL;
2277
- for (p = ref_rev_parse_rules; *p; p++) {
2278
- char fullref[PATH_MAX];
2279
- unsigned char sha1_from_ref[20];
2280
- unsigned char *this_result;
2281
- int flag;
2282
-
2283
- this_result = refs_found ? sha1_from_ref : sha1;
2284
- mksnpath(fullref, sizeof(fullref), *p, len, str);
2285
- r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2286
- this_result, &flag);
2287
- if (r) {
2288
- if (!refs_found++)
2289
- *ref = xstrdup(r);
2290
- if (!warn_ambiguous_refs)
2291
- break;
2292
- } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2293
- warning("ignoring dangling symref %s.", fullref);
2294
- } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2295
- warning("ignoring broken ref %s.", fullref);
2296
- }
2297
- }
2298
- free(last_branch);
2299
- return refs_found;
2300
-}
2301
-
2302
-int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2303
-{
2304
- char *last_branch = substitute_branch_name(&str, &len);
2305
- const char **p;
2306
- int logs_found = 0;
2307
-
2308
- *log = NULL;
2309
- for (p = ref_rev_parse_rules; *p; p++) {
2310
- unsigned char hash[20];
2311
- char path[PATH_MAX];
2312
- const char *ref, *it;
2313
-
2314
- mksnpath(path, sizeof(path), *p, len, str);
2315
- ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2316
- hash, NULL);
2317
- if (!ref)
2318
- continue;
2319
- if (reflog_exists(path))
2320
- it = path;
2321
- else if (strcmp(ref, path) && reflog_exists(ref))
2322
- it = ref;
2323
- else
2324
- continue;
2325
- if (!logs_found++) {
2326
- *log = xstrdup(it);
2327
- hashcpy(sha1, hash);
2328
- }
2329
- if (!warn_ambiguous_refs)
2330
- break;
2331
- }
2332
- free(last_branch);
2333
- return logs_found;
2334
-}
2335
-
2336
-/*
2337
- * Locks a ref returning the lock on success and NULL on failure.
2338
- * On failure errno is set to something meaningful.
2339
- */
2340
-static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2341
- const unsigned char *old_sha1,
2342
- const struct string_list *extras,
2343
- const struct string_list *skip,
2344
- unsigned int flags, int *type_p,
2345
- struct strbuf *err)
2346
-{
2347
- struct strbuf ref_file = STRBUF_INIT;
2348
- struct strbuf orig_ref_file = STRBUF_INIT;
2349
- const char *orig_refname = refname;
2350
- struct ref_lock *lock;
2351
- int last_errno = 0;
2352
- int type, lflags;
2353
- int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2354
- int resolve_flags = 0;
2355
- int attempts_remaining = 3;
2356
-
2357
- assert(err);
2358
-
2359
- lock = xcalloc(1, sizeof(struct ref_lock));
2360
-
2361
- if (mustexist)
2362
- resolve_flags |= RESOLVE_REF_READING;
2363
- if (flags & REF_DELETING) {
2364
- resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2365
- if (flags & REF_NODEREF)
2366
- resolve_flags |= RESOLVE_REF_NO_RECURSE;
2367
- }
2368
-
2369
- refname = resolve_ref_unsafe(refname, resolve_flags,
2370
- lock->old_oid.hash, &type);
2371
- if (!refname && errno == EISDIR) {
2372
- /*
2373
- * we are trying to lock foo but we used to
2374
- * have foo/bar which now does not exist;
2375
- * it is normal for the empty directory 'foo'
2376
- * to remain.
2377
- */
2378
- strbuf_git_path(&orig_ref_file, "%s", orig_refname);
2379
- if (remove_empty_directories(&orig_ref_file)) {
2380
- last_errno = errno;
2381
- if (!verify_refname_available_dir(orig_refname, extras, skip,
2382
- get_loose_refs(&ref_cache), err))
2383
- strbuf_addf(err, "there are still refs under '%s'",
2384
- orig_refname);
2385
- goto error_return;
2386
- }
2387
- refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2388
- lock->old_oid.hash, &type);
2389
- }
2390
- if (type_p)
2391
- *type_p = type;
2392
- if (!refname) {
2393
- last_errno = errno;
2394
- if (last_errno != ENOTDIR ||
2395
- !verify_refname_available_dir(orig_refname, extras, skip,
2396
- get_loose_refs(&ref_cache), err))
2397
- strbuf_addf(err, "unable to resolve reference %s: %s",
2398
- orig_refname, strerror(last_errno));
2399
-
2400
- goto error_return;
2401
- }
2402
- /*
2403
- * If the ref did not exist and we are creating it, make sure
2404
- * there is no existing packed ref whose name begins with our
2405
- * refname, nor a packed ref whose name is a proper prefix of
2406
- * our refname.
2407
- */
2408
- if (is_null_oid(&lock->old_oid) &&
2409
- verify_refname_available_dir(refname, extras, skip,
2410
- get_packed_refs(&ref_cache), err)) {
2411
- last_errno = ENOTDIR;
2412
- goto error_return;
2413
- }
2414
-
2415
- lock->lk = xcalloc(1, sizeof(struct lock_file));
2416
-
2417
- lflags = 0;
2418
- if (flags & REF_NODEREF) {
2419
- refname = orig_refname;
2420
- lflags |= LOCK_NO_DEREF;
2421
- }
2422
- lock->ref_name = xstrdup(refname);
2423
- lock->orig_ref_name = xstrdup(orig_refname);
2424
- strbuf_git_path(&ref_file, "%s", refname);
2425
-
2426
- retry:
2427
- switch (safe_create_leading_directories_const(ref_file.buf)) {
2428
- case SCLD_OK:
2429
- break; /* success */
2430
- case SCLD_VANISHED:
2431
- if (--attempts_remaining > 0)
2432
- goto retry;
2433
- /* fall through */
2434
- default:
2435
- last_errno = errno;
2436
- strbuf_addf(err, "unable to create directory for %s",
2437
- ref_file.buf);
2438
- goto error_return;
2439
- }
2440
-
2441
- if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
2442
- last_errno = errno;
2443
- if (errno == ENOENT && --attempts_remaining > 0)
2444
- /*
2445
- * Maybe somebody just deleted one of the
2446
- * directories leading to ref_file. Try
2447
- * again:
2448
- */
2449
- goto retry;
2450
- else {
2451
- unable_to_lock_message(ref_file.buf, errno, err);
2452
- goto error_return;
2453
- }
2454
- }
2455
- if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2456
- last_errno = errno;
2457
- goto error_return;
2458
- }
2459
- goto out;
2460
-
2461
- error_return:
2462
- unlock_ref(lock);
2463
- lock = NULL;
2464
-
2465
- out:
2466
- strbuf_release(&ref_file);
2467
- strbuf_release(&orig_ref_file);
2468
- errno = last_errno;
2469
- return lock;
2470
-}
2471
-
2472
-/*
2473
- * Write an entry to the packed-refs file for the specified refname.
2474
- * If peeled is non-NULL, write it as the entry's peeled value.
2475
- */
2476
-static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2477
- unsigned char *peeled)
2478
-{
2479
- fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2480
- if (peeled)
2481
- fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2482
-}
2483
-
2484
-/*
2485
- * An each_ref_entry_fn that writes the entry to a packed-refs file.
2486
- */
2487
-static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2488
-{
2489
- enum peel_status peel_status = peel_entry(entry, 0);
2490
-
2491
- if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2492
- error("internal error: %s is not a valid packed reference!",
2493
- entry->name);
2494
- write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2495
- peel_status == PEEL_PEELED ?
2496
- entry->u.value.peeled.hash : NULL);
2497
- return 0;
2498
-}
2499
-
2500
-/*
2501
- * Lock the packed-refs file for writing. Flags is passed to
2502
- * hold_lock_file_for_update(). Return 0 on success. On errors, set
2503
- * errno appropriately and return a nonzero value.
2504
- */
2505
-static int lock_packed_refs(int flags)
2506
-{
2507
- static int timeout_configured = 0;
2508
- static int timeout_value = 1000;
2509
-
2510
- struct packed_ref_cache *packed_ref_cache;
2511
-
2512
- if (!timeout_configured) {
2513
- git_config_get_int("core.packedrefstimeout", &timeout_value);
2514
- timeout_configured = 1;
2515
- }
2516
-
2517
- if (hold_lock_file_for_update_timeout(
2518
- &packlock, git_path("packed-refs"),
2519
- flags, timeout_value) < 0)
2520
- return -1;
2521
- /*
2522
- * Get the current packed-refs while holding the lock. If the
2523
- * packed-refs file has been modified since we last read it,
2524
- * this will automatically invalidate the cache and re-read
2525
- * the packed-refs file.
2526
- */
2527
- packed_ref_cache = get_packed_ref_cache(&ref_cache);
2528
- packed_ref_cache->lock = &packlock;
2529
- /* Increment the reference count to prevent it from being freed: */
2530
- acquire_packed_ref_cache(packed_ref_cache);
2531
- return 0;
2532
-}
2533
-
2534
-/*
2535
- * Write the current version of the packed refs cache from memory to
2536
- * disk. The packed-refs file must already be locked for writing (see
2537
- * lock_packed_refs()). Return zero on success. On errors, set errno
2538
- * and return a nonzero value
2539
- */
2540
-static int commit_packed_refs(void)
2541
-{
2542
- struct packed_ref_cache *packed_ref_cache =
2543
- get_packed_ref_cache(&ref_cache);
2544
- int error = 0;
2545
- int save_errno = 0;
2546
- FILE *out;
2547
-
2548
- if (!packed_ref_cache->lock)
2549
- die("internal error: packed-refs not locked");
2550
-
2551
- out = fdopen_lock_file(packed_ref_cache->lock, "w");
2552
- if (!out)
2553
- die_errno("unable to fdopen packed-refs descriptor");
2554
-
2555
- fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2556
- do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2557
- 0, write_packed_entry_fn, out);
2558
-
2559
- if (commit_lock_file(packed_ref_cache->lock)) {
2560
- save_errno = errno;
2561
- error = -1;
2562
- }
2563
- packed_ref_cache->lock = NULL;
2564
- release_packed_ref_cache(packed_ref_cache);
2565
- errno = save_errno;
2566
- return error;
2567
-}
2568
-
2569
-/*
2570
- * Rollback the lockfile for the packed-refs file, and discard the
2571
- * in-memory packed reference cache. (The packed-refs file will be
2572
- * read anew if it is needed again after this function is called.)
2573
- */
2574
-static void rollback_packed_refs(void)
2575
-{
2576
- struct packed_ref_cache *packed_ref_cache =
2577
- get_packed_ref_cache(&ref_cache);
2578
-
2579
- if (!packed_ref_cache->lock)
2580
- die("internal error: packed-refs not locked");
2581
- rollback_lock_file(packed_ref_cache->lock);
2582
- packed_ref_cache->lock = NULL;
2583
- release_packed_ref_cache(packed_ref_cache);
2584
- clear_packed_ref_cache(&ref_cache);
343
+ starts_with(name, "refs/tags/") ? 10 :
344
+ starts_with(name, "refs/remotes/") ? 13 :
345
+ 0);
346
}
347
2587
-struct ref_to_prune {
2588
- struct ref_to_prune *next;
2589
- unsigned char sha1[20];
2590
- char name[FLEX_ARRAY];
2591
-};
2592
-
2593
-struct pack_refs_cb_data {
2594
- unsigned int flags;
2595
- struct ref_dir *packed_refs;
2596
- struct ref_to_prune *ref_to_prune;
348
+static const char *ref_rev_parse_rules[] = {
349
+ "%.*s",
350
+ "refs/%.*s",
351
+ "refs/tags/%.*s",
352
+ "refs/heads/%.*s",
353
+ "refs/remotes/%.*s",
354
+ "refs/remotes/%.*s/HEAD",
355
+ NULL
356
};
357
2599
-/*
2600
- * An each_ref_entry_fn that is run over loose references only. If
2601
- * the loose reference can be packed, add an entry in the packed ref
2602
- * cache. If the reference should be pruned, also add it to
2603
- * ref_to_prune in the pack_refs_cb_data.
2604
- */
2605
-static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
358
+int refname_match(const char *abbrev_name, const char *full_name)
359
{
2607
- struct pack_refs_cb_data *cb = cb_data;
2608
- enum peel_status peel_status;
2609
- struct ref_entry *packed_entry;
2610
- int is_tag_ref = starts_with(entry->name, "refs/tags/");
2611
-
2612
- /* Do not pack per-worktree refs: */
2613
- if (ref_type(entry->name) != REF_TYPE_NORMAL)
2614
- return 0;
2615
-
2616
- /* ALWAYS pack tags */
2617
- if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2618
- return 0;
2619
-
2620
- /* Do not pack symbolic or broken refs: */
2621
- if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2622
- return 0;
360
+ const char **p;
361
+ const int abbrev_name_len = strlen(abbrev_name);
362
2624
- /* Add a packed ref cache entry equivalent to the loose entry. */
2625
- peel_status = peel_entry(entry, 1);
2626
- if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2627
- die("internal error peeling reference %s (%s)",
2628
- entry->name, oid_to_hex(&entry->u.value.oid));
2629
- packed_entry = find_ref(cb->packed_refs, entry->name);
2630
- if (packed_entry) {
2631
- /* Overwrite existing packed entry with info from loose entry */
2632
- packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2633
- oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2634
- } else {
2635
- packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2636
- REF_ISPACKED | REF_KNOWS_PEELED, 0);
2637
- add_ref(cb->packed_refs, packed_entry);
2638
- }
2639
- oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2640
-
2641
- /* Schedule the loose reference for pruning if requested. */
2642
- if ((cb->flags & PACK_REFS_PRUNE)) {
2643
- int namelen = strlen(entry->name) + 1;
2644
- struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2645
- hashcpy(n->sha1, entry->u.value.oid.hash);
2646
- memcpy(n->name, entry->name, namelen); /* includes NUL */
2647
- n->next = cb->ref_to_prune;
2648
- cb->ref_to_prune = n;
363
+ for (p = ref_rev_parse_rules; *p; p++) {
364
+ if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
365
+ return 1;
366
+ }
367
}
368
+
369
return 0;
370
}
371
372
/*
2654
- * Remove empty parents, but spare refs/ and immediate subdirs.
2655
- * Note: munges *name.
373
+ * *string and *len will only be substituted, and *string returned (for
374
+ * later free()ing) if the string passed in is a magic short-hand form
375
+ * to name a branch.
376
*/
2657
-static void try_remove_empty_parents(char *name)
2658
-{
2659
- char *p, *q;
2660
- int i;
2661
- p = name;
2662
- for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2663
- while (*p && *p != '/')
2664
- p++;
2665
- /* tolerate duplicate slashes; see check_refname_format() */
2666
- while (*p == '/')
2667
- p++;
2668
- }
2669
- for (q = p; *q; q++)
2670
- ;
2671
- while (1) {
2672
- while (q > p && *q != '/')
2673
- q--;
2674
- while (q > p && *(q-1) == '/')
2675
- q--;
2676
- if (q == p)
2677
- break;
2678
- *q = '\0';
2679
- if (rmdir(git_path("%s", name)))
2680
- break;
2681
- }
2682
-}
2683
-
2684
-/* make sure nobody touched the ref, and unlink */
2685
-static void prune_ref(struct ref_to_prune *r)
377
+static char *substitute_branch_name(const char **string, int *len)
378
{
2687
- struct ref_transaction *transaction;
2688
- struct strbuf err = STRBUF_INIT;
2689
-
2690
- if (check_refname_format(r->name, 0))
2691
- return;
2692
-
2693
- transaction = ref_transaction_begin(&err);
2694
- if (!transaction ||
2695
- ref_transaction_delete(transaction, r->name, r->sha1,
2696
- REF_ISPRUNING, NULL, &err) ||
2697
- ref_transaction_commit(transaction, &err)) {
2698
- ref_transaction_free(transaction);
2699
- error("%s", err.buf);
2700
- strbuf_release(&err);
2701
- return;
2702
- }
2703
- ref_transaction_free(transaction);
2704
- strbuf_release(&err);
2705
- try_remove_empty_parents(r->name);
2706
-}
379
+ struct strbuf buf = STRBUF_INIT;
380
+ int ret = interpret_branch_name(*string, *len, &buf);
381
2708
-static void prune_refs(struct ref_to_prune *r)
2709
-{
2710
- while (r) {
2711
- prune_ref(r);
2712
- r = r->next;
382
+ if (ret == *len) {
383
+ size_t size;
384
+ *string = strbuf_detach(&buf, &size);
385
+ *len = size;
386
+ return (char *)*string;
387
}
2714
-}
2715
-
2716
-int pack_refs(unsigned int flags)
2717
-{
2718
- struct pack_refs_cb_data cbdata;
388
2720
- memset(&cbdata, 0, sizeof(cbdata));
2721
- cbdata.flags = flags;
2722
-
2723
- lock_packed_refs(LOCK_DIE_ON_ERROR);
2724
- cbdata.packed_refs = get_packed_refs(&ref_cache);
2725
-
2726
- do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2727
- pack_if_possible_fn, &cbdata);
2728
-
2729
- if (commit_packed_refs())
2730
- die_errno("unable to overwrite old ref-pack file");
2731
-
2732
- prune_refs(cbdata.ref_to_prune);
2733
- return 0;
389
+ return NULL;
390
}
391
2736
-/*
2737
- * Rewrite the packed-refs file, omitting any refs listed in
2738
- * 'refnames'. On error, leave packed-refs unchanged, write an error
2739
- * message to 'err', and return a nonzero value.
2740
- *
2741
- * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2742
- */
2743
-static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
392
+int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
393
{
2745
- struct ref_dir *packed;
2746
- struct string_list_item *refname;
2747
- int ret, needs_repacking = 0, removed = 0;
394
+ char *last_branch = substitute_branch_name(&str, &len);
395
+ const char **p, *r;
396
+ int refs_found = 0;
397
2749
- assert(err);
398
+ *ref = NULL;
399
+ for (p = ref_rev_parse_rules; *p; p++) {
400
+ char fullref[PATH_MAX];
401
+ unsigned char sha1_from_ref[20];
402
+ unsigned char *this_result;
403
+ int flag;
404
2751
- /* Look for a packed ref */
2752
- for_each_string_list_item(refname, refnames) {
2753
- if (get_packed_ref(refname->string)) {
2754
- needs_repacking = 1;
2755
- break;
405
+ this_result = refs_found ? sha1_from_ref : sha1;
406
+ mksnpath(fullref, sizeof(fullref), *p, len, str);
407
+ r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
408
+ this_result, &flag);
409
+ if (r) {
410
+ if (!refs_found++)
411
+ *ref = xstrdup(r);
412
+ if (!warn_ambiguous_refs)
413
+ break;
414
+ } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
415
+ warning("ignoring dangling symref %s.", fullref);
416
+ } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
417
+ warning("ignoring broken ref %s.", fullref);
418
}
419
}
2758
-
2759
- /* Avoid locking if we have nothing to do */
2760
- if (!needs_repacking)
2761
- return 0; /* no refname exists in packed refs */
2762
-
2763
- if (lock_packed_refs(0)) {
2764
- unable_to_lock_message(git_path("packed-refs"), errno, err);
2765
- return -1;
2766
- }
2767
- packed = get_packed_refs(&ref_cache);
2768
-
2769
- /* Remove refnames from the cache */
2770
- for_each_string_list_item(refname, refnames)
2771
- if (remove_entry(packed, refname->string) != -1)
2772
- removed = 1;
2773
- if (!removed) {
2774
- /*
2775
- * All packed entries disappeared while we were
2776
- * acquiring the lock.
2777
- */
2778
- rollback_packed_refs();
2779
- return 0;
2780
- }
2781
-
2782
- /* Write what remains */
2783
- ret = commit_packed_refs();
2784
- if (ret)
2785
- strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2786
- strerror(errno));
2787
- return ret;
420
+ free(last_branch);
421
+ return refs_found;
422
}
423
2790
-static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
424
+int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
425
{
2792
- assert(err);
426
+ char *last_branch = substitute_branch_name(&str, &len);
427
+ const char **p;
428
+ int logs_found = 0;
429
2794
- if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2795
- /*
2796
- * loose. The loose file name is the same as the
2797
- * lockfile name, minus ".lock":
2798
- */
2799
- char *loose_filename = get_locked_file_path(lock->lk);
2800
- int res = unlink_or_msg(loose_filename, err);
2801
- free(loose_filename);
2802
- if (res)
2803
- return 1;
430
+ *log = NULL;
431
+ for (p = ref_rev_parse_rules; *p; p++) {
432
+ unsigned char hash[20];
433
+ char path[PATH_MAX];
434
+ const char *ref, *it;
435
+
436
+ mksnpath(path, sizeof(path), *p, len, str);
437
+ ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
438
+ hash, NULL);
439
+ if (!ref)
440
+ continue;
441
+ if (reflog_exists(path))
442
+ it = path;
443
+ else if (strcmp(ref, path) && reflog_exists(ref))
444
+ it = ref;
445
+ else
446
+ continue;
447
+ if (!logs_found++) {
448
+ *log = xstrdup(it);
449
+ hashcpy(sha1, hash);
450
+ }
451
+ if (!warn_ambiguous_refs)
452
+ break;
453
}
2805
- return 0;
454
+ free(last_branch);
455
+ return logs_found;
456
}
457
458
static int is_per_worktree_ref(const char *refname)
@@ -2926,265 +576,9 @@ int delete_ref(const char *refname, const unsigned char *old_sha1,
576
ref_transaction_free(transaction);
577
strbuf_release(&err);
578
return 1;
2929
- }
2930
- ref_transaction_free(transaction);
2931
- strbuf_release(&err);
2932
- return 0;
2933
-}
2934
-
2935
-int delete_refs(struct string_list *refnames)
2936
-{
2937
- struct strbuf err = STRBUF_INIT;
2938
- int i, result = 0;
2939
-
2940
- if (!refnames->nr)
2941
- return 0;
2942
-
2943
- result = repack_without_refs(refnames, &err);
2944
- if (result) {
2945
- /*
2946
- * If we failed to rewrite the packed-refs file, then
2947
- * it is unsafe to try to remove loose refs, because
2948
- * doing so might expose an obsolete packed value for
2949
- * a reference that might even point at an object that
2950
- * has been garbage collected.
2951
- */
2952
- if (refnames->nr == 1)
2953
- error(_("could not delete reference %s: %s"),
2954
- refnames->items[0].string, err.buf);
2955
- else
2956
- error(_("could not delete references: %s"), err.buf);
2957
-
2958
- goto out;
2959
- }
2960
-
2961
- for (i = 0; i < refnames->nr; i++) {
2962
- const char *refname = refnames->items[i].string;
2963
-
2964
- if (delete_ref(refname, NULL, 0))
2965
- result |= error(_("could not remove reference %s"), refname);
2966
- }
2967
-
2968
-out:
2969
- strbuf_release(&err);
2970
- return result;
2971
-}
2972
-
2973
-/*
2974
- * People using contrib's git-new-workdir have .git/logs/refs ->
2975
- * /some/other/path/.git/logs/refs, and that may live on another device.
2976
- *
2977
- * IOW, to avoid cross device rename errors, the temporary renamed log must
2978
- * live into logs/refs.
2979
- */
2980
-#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2981
-
2982
-static int rename_tmp_log(const char *newrefname)
2983
-{
2984
- int attempts_remaining = 4;
2985
- struct strbuf path = STRBUF_INIT;
2986
- int ret = -1;
2987
-
2988
- retry:
2989
- strbuf_reset(&path);
2990
- strbuf_git_path(&path, "logs/%s", newrefname);
2991
- switch (safe_create_leading_directories_const(path.buf)) {
2992
- case SCLD_OK:
2993
- break; /* success */
2994
- case SCLD_VANISHED:
2995
- if (--attempts_remaining > 0)
2996
- goto retry;
2997
- /* fall through */
2998
- default:
2999
- error("unable to create directory for %s", newrefname);
3000
- goto out;
3001
- }
3002
-
3003
- if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
3004
- if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
3005
- /*
3006
- * rename(a, b) when b is an existing
3007
- * directory ought to result in ISDIR, but
3008
- * Solaris 5.8 gives ENOTDIR. Sheesh.
3009
- */
3010
- if (remove_empty_directories(&path)) {
3011
- error("Directory not empty: logs/%s", newrefname);
3012
- goto out;
3013
- }
3014
- goto retry;
3015
- } else if (errno == ENOENT && --attempts_remaining > 0) {
3016
- /*
3017
- * Maybe another process just deleted one of
3018
- * the directories in the path to newrefname.
3019
- * Try again from the beginning.
3020
- */
3021
- goto retry;
3022
- } else {
3023
- error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
3024
- newrefname, strerror(errno));
3025
- goto out;
3026
- }
3027
- }
3028
- ret = 0;
3029
-out:
3030
- strbuf_release(&path);
3031
- return ret;
3032
-}
3033
-
3034
-int verify_refname_available(const char *newname,
3035
- struct string_list *extras,
3036
- struct string_list *skip,
3037
- struct strbuf *err)
3038
-{
3039
- struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
3040
- struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
3041
-
3042
- if (verify_refname_available_dir(newname, extras, skip,
3043
- packed_refs, err) ||
3044
- verify_refname_available_dir(newname, extras, skip,
3045
- loose_refs, err))
3046
- return -1;
3047
-
3048
- return 0;
3049
-}
3050
-
3051
-static int rename_ref_available(const char *oldname, const char *newname)
3052
-{
3053
- struct string_list skip = STRING_LIST_INIT_NODUP;
3054
- struct strbuf err = STRBUF_INIT;
3055
- int ret;
3056
-
3057
- string_list_insert(&skip, oldname);
3058
- ret = !verify_refname_available(newname, NULL, &skip, &err);
3059
- if (!ret)
3060
- error("%s", err.buf);
3061
-
3062
- string_list_clear(&skip, 0);
3063
- strbuf_release(&err);
3064
- return ret;
3065
-}
3066
-
3067
-static int write_ref_to_lockfile(struct ref_lock *lock,
3068
- const unsigned char *sha1, struct strbuf *err);
3069
-static int commit_ref_update(struct ref_lock *lock,
3070
- const unsigned char *sha1, const char *logmsg,
3071
- int flags, struct strbuf *err);
3072
-
3073
-int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
3074
-{
3075
- unsigned char sha1[20], orig_sha1[20];
3076
- int flag = 0, logmoved = 0;
3077
- struct ref_lock *lock;
3078
- struct stat loginfo;
3079
- int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
3080
- const char *symref = NULL;
3081
- struct strbuf err = STRBUF_INIT;
3082
-
3083
- if (log && S_ISLNK(loginfo.st_mode))
3084
- return error("reflog for %s is a symlink", oldrefname);
3085
-
3086
- symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
3087
- orig_sha1, &flag);
3088
- if (flag & REF_ISSYMREF)
3089
- return error("refname %s is a symbolic ref, renaming it is not supported",
3090
- oldrefname);
3091
- if (!symref)
3092
- return error("refname %s not found", oldrefname);
3093
-
3094
- if (!rename_ref_available(oldrefname, newrefname))
3095
- return 1;
3096
-
3097
- if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3098
- return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3099
- oldrefname, strerror(errno));
3100
-
3101
- if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3102
- error("unable to delete old %s", oldrefname);
3103
- goto rollback;
3104
- }
3105
-
3106
- if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3107
- delete_ref(newrefname, sha1, REF_NODEREF)) {
3108
- if (errno==EISDIR) {
3109
- struct strbuf path = STRBUF_INIT;
3110
- int result;
3111
-
3112
- strbuf_git_path(&path, "%s", newrefname);
3113
- result = remove_empty_directories(&path);
3114
- strbuf_release(&path);
3115
-
3116
- if (result) {
3117
- error("Directory not empty: %s", newrefname);
3118
- goto rollback;
3119
- }
3120
- } else {
3121
- error("unable to delete existing %s", newrefname);
3122
- goto rollback;
3123
- }
3124
- }
3125
-
3126
- if (log && rename_tmp_log(newrefname))
3127
- goto rollback;
3128
-
3129
- logmoved = log;
3130
-
3131
- lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3132
- if (!lock) {
3133
- error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3134
- strbuf_release(&err);
3135
- goto rollback;
3136
- }
3137
- hashcpy(lock->old_oid.hash, orig_sha1);
3138
-
3139
- if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3140
- commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
3141
- error("unable to write current sha1 into %s: %s", newrefname, err.buf);
3142
- strbuf_release(&err);
3143
- goto rollback;
3144
- }
3145
-
3146
- return 0;
3147
-
3148
- rollback:
3149
- lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3150
- if (!lock) {
3151
- error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3152
- strbuf_release(&err);
3153
- goto rollbacklog;
3154
- }
3155
-
3156
- flag = log_all_ref_updates;
3157
- log_all_ref_updates = 0;
3158
- if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3159
- commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
3160
- error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
3161
- strbuf_release(&err);
3162
- }
3163
- log_all_ref_updates = flag;
3164
-
3165
- rollbacklog:
3166
- if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3167
- error("unable to restore logfile %s from %s: %s",
3168
- oldrefname, newrefname, strerror(errno));
3169
- if (!logmoved && log &&
3170
- rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3171
- error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3172
- oldrefname, strerror(errno));
3173
-
3174
- return 1;
3175
-}
3176
-
3177
-static int close_ref(struct ref_lock *lock)
3178
-{
3179
- if (close_lock_file(lock->lk))
3180
- return -1;
3181
- return 0;
3182
-}
3183
-
3184
-static int commit_ref(struct ref_lock *lock)
3185
-{
3186
- if (commit_lock_file(lock->lk))
3187
- return -1;
579
+ }
580
+ ref_transaction_free(transaction);
581
+ strbuf_release(&err);
582
return 0;
583
}
584
@@ -3219,305 +613,11 @@ int should_autocreate_reflog(const char *refname)
613
!strcmp(refname, "HEAD");
614
}
615
3222
-/*
3223
- * Create a reflog for a ref. If force_create = 0, the reflog will
3224
- * only be created for certain refs (those for which
3225
- * should_autocreate_reflog returns non-zero. Otherwise, create it
3226
- * regardless of the ref name. Fill in *err and return -1 on failure.
3227
- */
3228
-static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
3229
-{
3230
- int logfd, oflags = O_APPEND | O_WRONLY;
3231
-
3232
- strbuf_git_path(logfile, "logs/%s", refname);
3233
- if (force_create || should_autocreate_reflog(refname)) {
3234
- if (safe_create_leading_directories(logfile->buf) < 0) {
3235
- strbuf_addf(err, "unable to create directory for %s: "
3236
- "%s", logfile->buf, strerror(errno));
3237
- return -1;
3238
- }
3239
- oflags |= O_CREAT;
3240
- }
3241
-
3242
- logfd = open(logfile->buf, oflags, 0666);
3243
- if (logfd < 0) {
3244
- if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3245
- return 0;
3246
-
3247
- if (errno == EISDIR) {
3248
- if (remove_empty_directories(logfile)) {
3249
- strbuf_addf(err, "There are still logs under "
3250
- "'%s'", logfile->buf);
3251
- return -1;
3252
- }
3253
- logfd = open(logfile->buf, oflags, 0666);
3254
- }
3255
-
3256
- if (logfd < 0) {
3257
- strbuf_addf(err, "unable to append to %s: %s",
3258
- logfile->buf, strerror(errno));
3259
- return -1;
3260
- }
3261
- }
3262
-
3263
- adjust_shared_perm(logfile->buf);
3264
- close(logfd);
3265
- return 0;
3266
-}
3267
-
3268
-
3269
-int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
3270
-{
3271
- int ret;
3272
- struct strbuf sb = STRBUF_INIT;
3273
-
3274
- ret = log_ref_setup(refname, &sb, err, force_create);
3275
- strbuf_release(&sb);
3276
- return ret;
3277
-}
3278
-
3279
-static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3280
- const unsigned char *new_sha1,
3281
- const char *committer, const char *msg)
3282
-{
3283
- int msglen, written;
3284
- unsigned maxlen, len;
3285
- char *logrec;
3286
-
3287
- msglen = msg ? strlen(msg) : 0;
3288
- maxlen = strlen(committer) + msglen + 100;
3289
- logrec = xmalloc(maxlen);
3290
- len = xsnprintf(logrec, maxlen, "%s %s %s\n",
3291
- sha1_to_hex(old_sha1),
3292
- sha1_to_hex(new_sha1),
3293
- committer);
3294
- if (msglen)
3295
- len += copy_reflog_msg(logrec + len - 1, msg) - 1;
3296
-
3297
- written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3298
- free(logrec);
3299
- if (written != len)
3300
- return -1;
3301
-
3302
- return 0;
3303
-}
3304
-
3305
-static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3306
- const unsigned char *new_sha1, const char *msg,
3307
- struct strbuf *logfile, int flags,
3308
- struct strbuf *err)
3309
-{
3310
- int logfd, result, oflags = O_APPEND | O_WRONLY;
3311
-
3312
- if (log_all_ref_updates < 0)
3313
- log_all_ref_updates = !is_bare_repository();
3314
-
3315
- result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
3316
-
3317
- if (result)
3318
- return result;
3319
-
3320
- logfd = open(logfile->buf, oflags);
3321
- if (logfd < 0)
3322
- return 0;
3323
- result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3324
- git_committer_info(0), msg);
3325
- if (result) {
3326
- strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3327
- strerror(errno));
3328
- close(logfd);
3329
- return -1;
3330
- }
3331
- if (close(logfd)) {
3332
- strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3333
- strerror(errno));
3334
- return -1;
3335
- }
3336
- return 0;
3337
-}
3338
-
3339
-static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3340
- const unsigned char *new_sha1, const char *msg,
3341
- int flags, struct strbuf *err)
3342
-{
3343
- struct strbuf sb = STRBUF_INIT;
3344
- int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
3345
- err);
3346
- strbuf_release(&sb);
3347
- return ret;
3348
-}
3349
-
616
int is_branch(const char *refname)
617
{
618
return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
619
}
620
3355
-/*
3356
- * Write sha1 into the open lockfile, then close the lockfile. On
3357
- * errors, rollback the lockfile, fill in *err and
3358
- * return -1.
3359
- */
3360
-static int write_ref_to_lockfile(struct ref_lock *lock,
3361
- const unsigned char *sha1, struct strbuf *err)
3362
-{
3363
- static char term = '\n';
3364
- struct object *o;
3365
- int fd;
3366
-
3367
- o = parse_object(sha1);
3368
- if (!o) {
3369
- strbuf_addf(err,
3370
- "Trying to write ref %s with nonexistent object %s",
3371
- lock->ref_name, sha1_to_hex(sha1));
3372
- unlock_ref(lock);
3373
- return -1;
3374
- }
3375
- if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3376
- strbuf_addf(err,
3377
- "Trying to write non-commit object %s to branch %s",
3378
- sha1_to_hex(sha1), lock->ref_name);
3379
- unlock_ref(lock);
3380
- return -1;
3381
- }
3382
- fd = get_lock_file_fd(lock->lk);
3383
- if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
3384
- write_in_full(fd, &term, 1) != 1 ||
3385
- close_ref(lock) < 0) {
3386
- strbuf_addf(err,
3387
- "Couldn't write %s", get_lock_file_path(lock->lk));
3388
- unlock_ref(lock);
3389
- return -1;
3390
- }
3391
- return 0;
3392
-}
3393
-
3394
-/*
3395
- * Commit a change to a loose reference that has already been written
3396
- * to the loose reference lockfile. Also update the reflogs if
3397
- * necessary, using the specified lockmsg (which can be NULL).
3398
- */
3399
-static int commit_ref_update(struct ref_lock *lock,
3400
- const unsigned char *sha1, const char *logmsg,
3401
- int flags, struct strbuf *err)
3402
-{
3403
- clear_loose_ref_cache(&ref_cache);
3404
- if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
3405
- (strcmp(lock->ref_name, lock->orig_ref_name) &&
3406
- log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
3407
- char *old_msg = strbuf_detach(err, NULL);
3408
- strbuf_addf(err, "Cannot update the ref '%s': %s",
3409
- lock->ref_name, old_msg);
3410
- free(old_msg);
3411
- unlock_ref(lock);
3412
- return -1;
3413
- }
3414
- if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3415
- /*
3416
- * Special hack: If a branch is updated directly and HEAD
3417
- * points to it (may happen on the remote side of a push
3418
- * for example) then logically the HEAD reflog should be
3419
- * updated too.
3420
- * A generic solution implies reverse symref information,
3421
- * but finding all symrefs pointing to the given branch
3422
- * would be rather costly for this rare event (the direct
3423
- * update of a branch) to be worth it. So let's cheat and
3424
- * check with HEAD only which should cover 99% of all usage
3425
- * scenarios (even 100% of the default ones).
3426
- */
3427
- unsigned char head_sha1[20];
3428
- int head_flag;
3429
- const char *head_ref;
3430
- head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3431
- head_sha1, &head_flag);
3432
- if (head_ref && (head_flag & REF_ISSYMREF) &&
3433
- !strcmp(head_ref, lock->ref_name)) {
3434
- struct strbuf log_err = STRBUF_INIT;
3435
- if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
3436
- logmsg, 0, &log_err)) {
3437
- error("%s", log_err.buf);
3438
- strbuf_release(&log_err);
3439
- }
3440
- }
3441
- }
3442
- if (commit_ref(lock)) {
3443
- error("Couldn't set %s", lock->ref_name);
3444
- unlock_ref(lock);
3445
- return -1;
3446
- }
3447
-
3448
- unlock_ref(lock);
3449
- return 0;
3450
-}
3451
-
3452
-int create_symref(const char *ref_target, const char *refs_heads_master,
3453
- const char *logmsg)
3454
-{
3455
- char *lockpath = NULL;
3456
- char ref[1000];
3457
- int fd, len, written;
3458
- char *git_HEAD = git_pathdup("%s", ref_target);
3459
- unsigned char old_sha1[20], new_sha1[20];
3460
- struct strbuf err = STRBUF_INIT;
3461
-
3462
- if (logmsg && read_ref(ref_target, old_sha1))
3463
- hashclr(old_sha1);
3464
-
3465
- if (safe_create_leading_directories(git_HEAD) < 0)
3466
- return error("unable to create directory for %s", git_HEAD);
3467
-
3468
-#ifndef NO_SYMLINK_HEAD
3469
- if (prefer_symlink_refs) {
3470
- unlink(git_HEAD);
3471
- if (!symlink(refs_heads_master, git_HEAD))
3472
- goto done;
3473
- fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3474
- }
3475
-#endif
3476
-
3477
- len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3478
- if (sizeof(ref) <= len) {
3479
- error("refname too long: %s", refs_heads_master);
3480
- goto error_free_return;
3481
- }
3482
- lockpath = mkpathdup("%s.lock", git_HEAD);
3483
- fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3484
- if (fd < 0) {
3485
- error("Unable to open %s for writing", lockpath);
3486
- goto error_free_return;
3487
- }
3488
- written = write_in_full(fd, ref, len);
3489
- if (close(fd) != 0 || written != len) {
3490
- error("Unable to write to %s", lockpath);
3491
- goto error_unlink_return;
3492
- }
3493
- if (rename(lockpath, git_HEAD) < 0) {
3494
- error("Unable to create %s", git_HEAD);
3495
- goto error_unlink_return;
3496
- }
3497
- if (adjust_shared_perm(git_HEAD)) {
3498
- error("Unable to fix permissions on %s", lockpath);
3499
- error_unlink_return:
3500
- unlink_or_warn(lockpath);
3501
- error_free_return:
3502
- free(lockpath);
3503
- free(git_HEAD);
3504
- return -1;
3505
- }
3506
- free(lockpath);
3507
-
3508
-#ifndef NO_SYMLINK_HEAD
3509
- done:
3510
-#endif
3511
- if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
3512
- log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
3513
- error("%s", err.buf);
3514
- strbuf_release(&err);
3515
- }
3516
-
3517
- free(git_HEAD);
3518
- return 0;
3519
-}
3520
-
621
struct read_ref_at_cb {
622
const char *refname;
623
unsigned long at_time;
@@ -3636,232 +736,6 @@ int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time,
736
return 1;
737
}
738
3639
-int reflog_exists(const char *refname)
3640
-{
3641
- struct stat st;
3642
-
3643
- return !lstat(git_path("logs/%s", refname), &st) &&
3644
- S_ISREG(st.st_mode);
3645
-}
3646
-
3647
-int delete_reflog(const char *refname)
3648
-{
3649
- return remove_path(git_path("logs/%s", refname));
3650
-}
3651
-
3652
-static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3653
-{
3654
- unsigned char osha1[20], nsha1[20];
3655
- char *email_end, *message;
3656
- unsigned long timestamp;
3657
- int tz;
3658
-
3659
- /* old SP new SP name <email> SP time TAB msg LF */
3660
- if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3661
- get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3662
- get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3663
- !(email_end = strchr(sb->buf + 82, '>')) ||
3664
- email_end[1] != ' ' ||
3665
- !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3666
- !message || message[0] != ' ' ||
3667
- (message[1] != '+' && message[1] != '-') ||
3668
- !isdigit(message[2]) || !isdigit(message[3]) ||
3669
- !isdigit(message[4]) || !isdigit(message[5]))
3670
- return 0; /* corrupt? */
3671
- email_end[1] = '\0';
3672
- tz = strtol(message + 1, NULL, 10);
3673
- if (message[6] != '\t')
3674
- message += 6;
3675
- else
3676
- message += 7;
3677
- return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3678
-}
3679
-
3680
-static char *find_beginning_of_line(char *bob, char *scan)
3681
-{
3682
- while (bob < scan && *(--scan) != '\n')
3683
- ; /* keep scanning backwards */
3684
- /*
3685
- * Return either beginning of the buffer, or LF at the end of
3686
- * the previous line.
3687
- */
3688
- return scan;
3689
-}
3690
-
3691
-int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3692
-{
3693
- struct strbuf sb = STRBUF_INIT;
3694
- FILE *logfp;
3695
- long pos;
3696
- int ret = 0, at_tail = 1;
3697
-
3698
- logfp = fopen(git_path("logs/%s", refname), "r");
3699
- if (!logfp)
3700
- return -1;
3701
-
3702
- /* Jump to the end */
3703
- if (fseek(logfp, 0, SEEK_END) < 0)
3704
- return error("cannot seek back reflog for %s: %s",
3705
- refname, strerror(errno));
3706
- pos = ftell(logfp);
3707
- while (!ret && 0 < pos) {
3708
- int cnt;
3709
- size_t nread;
3710
- char buf[BUFSIZ];
3711
- char *endp, *scanp;
3712
-
3713
- /* Fill next block from the end */
3714
- cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3715
- if (fseek(logfp, pos - cnt, SEEK_SET))
3716
- return error("cannot seek back reflog for %s: %s",
3717
- refname, strerror(errno));
3718
- nread = fread(buf, cnt, 1, logfp);
3719
- if (nread != 1)
3720
- return error("cannot read %d bytes from reflog for %s: %s",
3721
- cnt, refname, strerror(errno));
3722
- pos -= cnt;
3723
-
3724
- scanp = endp = buf + cnt;
3725
- if (at_tail && scanp[-1] == '\n')
3726
- /* Looking at the final LF at the end of the file */
3727
- scanp--;
3728
- at_tail = 0;
3729
-
3730
- while (buf < scanp) {
3731
- /*
3732
- * terminating LF of the previous line, or the beginning
3733
- * of the buffer.
3734
- */
3735
- char *bp;
3736
-
3737
- bp = find_beginning_of_line(buf, scanp);
3738
-
3739
- if (*bp == '\n') {
3740
- /*
3741
- * The newline is the end of the previous line,
3742
- * so we know we have complete line starting
3743
- * at (bp + 1). Prefix it onto any prior data
3744
- * we collected for the line and process it.
3745
- */
3746
- strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3747
- scanp = bp;
3748
- endp = bp + 1;
3749
- ret = show_one_reflog_ent(&sb, fn, cb_data);
3750
- strbuf_reset(&sb);
3751
- if (ret)
3752
- break;
3753
- } else if (!pos) {
3754
- /*
3755
- * We are at the start of the buffer, and the
3756
- * start of the file; there is no previous
3757
- * line, and we have everything for this one.
3758
- * Process it, and we can end the loop.
3759
- */
3760
- strbuf_splice(&sb, 0, 0, buf, endp - buf);
3761
- ret = show_one_reflog_ent(&sb, fn, cb_data);
3762
- strbuf_reset(&sb);
3763
- break;
3764
- }
3765
-
3766
- if (bp == buf) {
3767
- /*
3768
- * We are at the start of the buffer, and there
3769
- * is more file to read backwards. Which means
3770
- * we are in the middle of a line. Note that we
3771
- * may get here even if *bp was a newline; that
3772
- * just means we are at the exact end of the
3773
- * previous line, rather than some spot in the
3774
- * middle.
3775
- *
3776
- * Save away what we have to be combined with
3777
- * the data from the next read.
3778
- */
3779
- strbuf_splice(&sb, 0, 0, buf, endp - buf);
3780
- break;
3781
- }
3782
- }
3783
-
3784
- }
3785
- if (!ret && sb.len)
3786
- die("BUG: reverse reflog parser had leftover data");
3787
-
3788
- fclose(logfp);
3789
- strbuf_release(&sb);
3790
- return ret;
3791
-}
3792
-
3793
-int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3794
-{
3795
- FILE *logfp;
3796
- struct strbuf sb = STRBUF_INIT;
3797
- int ret = 0;
3798
-
3799
- logfp = fopen(git_path("logs/%s", refname), "r");
3800
- if (!logfp)
3801
- return -1;
3802
-
3803
- while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3804
- ret = show_one_reflog_ent(&sb, fn, cb_data);
3805
- fclose(logfp);
3806
- strbuf_release(&sb);
3807
- return ret;
3808
-}
3809
-/*
3810
- * Call fn for each reflog in the namespace indicated by name. name
3811
- * must be empty or end with '/'. Name will be used as a scratch
3812
- * space, but its contents will be restored before return.
3813
- */
3814
-static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3815
-{
3816
- DIR *d = opendir(git_path("logs/%s", name->buf));
3817
- int retval = 0;
3818
- struct dirent *de;
3819
- int oldlen = name->len;
3820
-
3821
- if (!d)
3822
- return name->len ? errno : 0;
3823
-
3824
- while ((de = readdir(d)) != NULL) {
3825
- struct stat st;
3826
-
3827
- if (de->d_name[0] == '.')
3828
- continue;
3829
- if (ends_with(de->d_name, ".lock"))
3830
- continue;
3831
- strbuf_addstr(name, de->d_name);
3832
- if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3833
- ; /* silently ignore */
3834
- } else {
3835
- if (S_ISDIR(st.st_mode)) {
3836
- strbuf_addch(name, '/');
3837
- retval = do_for_each_reflog(name, fn, cb_data);
3838
- } else {
3839
- struct object_id oid;
3840
-
3841
- if (read_ref_full(name->buf, 0, oid.hash, NULL))
3842
- retval = error("bad ref for %s", name->buf);
3843
- else
3844
- retval = fn(name->buf, &oid, 0, cb_data);
3845
- }
3846
- if (retval)
3847
- break;
3848
- }
3849
- strbuf_setlen(name, oldlen);
3850
- }
3851
- closedir(d);
3852
- return retval;
3853
-}
3854
-
3855
-int for_each_reflog(each_ref_fn fn, void *cb_data)
3856
-{
3857
- int retval;
3858
- struct strbuf name;
3859
- strbuf_init(&name, PATH_MAX);
3860
- retval = do_for_each_reflog(&name, fn, cb_data);
3861
- strbuf_release(&name);
3862
- return retval;
3863
-}
3864
-
739
struct ref_transaction *ref_transaction_begin(struct strbuf *err)
740
{
741
assert(err);
@@ -4012,269 +886,6 @@ int update_ref(const char *msg, const char *refname,
886
return 0;
887
}
888
4015
-static int ref_update_reject_duplicates(struct string_list *refnames,
4016
- struct strbuf *err)
4017
-{
4018
- int i, n = refnames->nr;
4019
-
4020
- assert(err);
4021
-
4022
- for (i = 1; i < n; i++)
4023
- if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
4024
- strbuf_addf(err,
4025
- "Multiple updates for ref '%s' not allowed.",
4026
- refnames->items[i].string);
4027
- return 1;
4028
- }
4029
- return 0;
4030
-}
4031
-
4032
-int ref_transaction_commit(struct ref_transaction *transaction,
4033
- struct strbuf *err)
4034
-{
4035
- int ret = 0, i;
4036
- int n = transaction->nr;
4037
- struct ref_update **updates = transaction->updates;
4038
- struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
4039
- struct string_list_item *ref_to_delete;
4040
- struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4041
-
4042
- assert(err);
4043
-
4044
- if (transaction->state != REF_TRANSACTION_OPEN)
4045
- die("BUG: commit called for transaction that is not open");
4046
-
4047
- if (!n) {
4048
- transaction->state = REF_TRANSACTION_CLOSED;
4049
- return 0;
4050
- }
4051
-
4052
- /* Fail if a refname appears more than once in the transaction: */
4053
- for (i = 0; i < n; i++)
4054
- string_list_append(&affected_refnames, updates[i]->refname);
4055
- string_list_sort(&affected_refnames);
4056
- if (ref_update_reject_duplicates(&affected_refnames, err)) {
4057
- ret = TRANSACTION_GENERIC_ERROR;
4058
- goto cleanup;
4059
- }
4060
-
4061
- /*
4062
- * Acquire all locks, verify old values if provided, check
4063
- * that new values are valid, and write new values to the
4064
- * lockfiles, ready to be activated. Only keep one lockfile
4065
- * open at a time to avoid running out of file descriptors.
4066
- */
4067
- for (i = 0; i < n; i++) {
4068
- struct ref_update *update = updates[i];
4069
-
4070
- if ((update->flags & REF_HAVE_NEW) &&
4071
- is_null_sha1(update->new_sha1))
4072
- update->flags |= REF_DELETING;
4073
- update->lock = lock_ref_sha1_basic(
4074
- update->refname,
4075
- ((update->flags & REF_HAVE_OLD) ?
4076
- update->old_sha1 : NULL),
4077
- &affected_refnames, NULL,
4078
- update->flags,
4079
- &update->type,
4080
- err);
4081
- if (!update->lock) {
4082
- char *reason;
4083
-
4084
- ret = (errno == ENOTDIR)
4085
- ? TRANSACTION_NAME_CONFLICT
4086
- : TRANSACTION_GENERIC_ERROR;
4087
- reason = strbuf_detach(err, NULL);
4088
- strbuf_addf(err, "cannot lock ref '%s': %s",
4089
- update->refname, reason);
4090
- free(reason);
4091
- goto cleanup;
4092
- }
4093
- if ((update->flags & REF_HAVE_NEW) &&
4094
- !(update->flags & REF_DELETING)) {
4095
- int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4096
- (update->flags & REF_NODEREF));
4097
-
4098
- if (!overwriting_symref &&
4099
- !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4100
- /*
4101
- * The reference already has the desired
4102
- * value, so we don't need to write it.
4103
- */
4104
- } else if (write_ref_to_lockfile(update->lock,
4105
- update->new_sha1,
4106
- err)) {
4107
- char *write_err = strbuf_detach(err, NULL);
4108
-
4109
- /*
4110
- * The lock was freed upon failure of
4111
- * write_ref_to_lockfile():
4112
- */
4113
- update->lock = NULL;
4114
- strbuf_addf(err,
4115
- "cannot update the ref '%s': %s",
4116
- update->refname, write_err);
4117
- free(write_err);
4118
- ret = TRANSACTION_GENERIC_ERROR;
4119
- goto cleanup;
4120
- } else {
4121
- update->flags |= REF_NEEDS_COMMIT;
4122
- }
4123
- }
4124
- if (!(update->flags & REF_NEEDS_COMMIT)) {
4125
- /*
4126
- * We didn't have to write anything to the lockfile.
4127
- * Close it to free up the file descriptor:
4128
- */
4129
- if (close_ref(update->lock)) {
4130
- strbuf_addf(err, "Couldn't close %s.lock",
4131
- update->refname);
4132
- goto cleanup;
4133
- }
4134
- }
4135
- }
4136
-
4137
- /* Perform updates first so live commits remain referenced */
4138
- for (i = 0; i < n; i++) {
4139
- struct ref_update *update = updates[i];
4140
-
4141
- if (update->flags & REF_NEEDS_COMMIT) {
4142
- if (commit_ref_update(update->lock,
4143
- update->new_sha1, update->msg,
4144
- update->flags, err)) {
4145
- /* freed by commit_ref_update(): */
4146
- update->lock = NULL;
4147
- ret = TRANSACTION_GENERIC_ERROR;
4148
- goto cleanup;
4149
- } else {
4150
- /* freed by commit_ref_update(): */
4151
- update->lock = NULL;
4152
- }
4153
- }
4154
- }
4155
-
4156
- /* Perform deletes now that updates are safely completed */
4157
- for (i = 0; i < n; i++) {
4158
- struct ref_update *update = updates[i];
4159
-
4160
- if (update->flags & REF_DELETING) {
4161
- if (delete_ref_loose(update->lock, update->type, err)) {
4162
- ret = TRANSACTION_GENERIC_ERROR;
4163
- goto cleanup;
4164
- }
4165
-
4166
- if (!(update->flags & REF_ISPRUNING))
4167
- string_list_append(&refs_to_delete,
4168
- update->lock->ref_name);
4169
- }
4170
- }
4171
-
4172
- if (repack_without_refs(&refs_to_delete, err)) {
4173
- ret = TRANSACTION_GENERIC_ERROR;
4174
- goto cleanup;
4175
- }
4176
- for_each_string_list_item(ref_to_delete, &refs_to_delete)
4177
- unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4178
- clear_loose_ref_cache(&ref_cache);
4179
-
4180
-cleanup:
4181
- transaction->state = REF_TRANSACTION_CLOSED;
4182
-
4183
- for (i = 0; i < n; i++)
4184
- if (updates[i]->lock)
4185
- unlock_ref(updates[i]->lock);
4186
- string_list_clear(&refs_to_delete, 0);
4187
- string_list_clear(&affected_refnames, 0);
4188
- return ret;
4189
-}
4190
-
4191
-static int ref_present(const char *refname,
4192
- const struct object_id *oid, int flags, void *cb_data)
4193
-{
4194
- struct string_list *affected_refnames = cb_data;
4195
-
4196
- return string_list_has_string(affected_refnames, refname);
4197
-}
4198
-
4199
-int initial_ref_transaction_commit(struct ref_transaction *transaction,
4200
- struct strbuf *err)
4201
-{
4202
- int ret = 0, i;
4203
- int n = transaction->nr;
4204
- struct ref_update **updates = transaction->updates;
4205
- struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4206
-
4207
- assert(err);
4208
-
4209
- if (transaction->state != REF_TRANSACTION_OPEN)
4210
- die("BUG: commit called for transaction that is not open");
4211
-
4212
- /* Fail if a refname appears more than once in the transaction: */
4213
- for (i = 0; i < n; i++)
4214
- string_list_append(&affected_refnames, updates[i]->refname);
4215
- string_list_sort(&affected_refnames);
4216
- if (ref_update_reject_duplicates(&affected_refnames, err)) {
4217
- ret = TRANSACTION_GENERIC_ERROR;
4218
- goto cleanup;
4219
- }
4220
-
4221
- /*
4222
- * It's really undefined to call this function in an active
4223
- * repository or when there are existing references: we are
4224
- * only locking and changing packed-refs, so (1) any
4225
- * simultaneous processes might try to change a reference at
4226
- * the same time we do, and (2) any existing loose versions of
4227
- * the references that we are setting would have precedence
4228
- * over our values. But some remote helpers create the remote
4229
- * "HEAD" and "master" branches before calling this function,
4230
- * so here we really only check that none of the references
4231
- * that we are creating already exists.
4232
- */
4233
- if (for_each_rawref(ref_present, &affected_refnames))
4234
- die("BUG: initial ref transaction called with existing refs");
4235
-
4236
- for (i = 0; i < n; i++) {
4237
- struct ref_update *update = updates[i];
4238
-
4239
- if ((update->flags & REF_HAVE_OLD) &&
4240
- !is_null_sha1(update->old_sha1))
4241
- die("BUG: initial ref transaction with old_sha1 set");
4242
- if (verify_refname_available(update->refname,
4243
- &affected_refnames, NULL,
4244
- err)) {
4245
- ret = TRANSACTION_NAME_CONFLICT;
4246
- goto cleanup;
4247
- }
4248
- }
4249
-
4250
- if (lock_packed_refs(0)) {
4251
- strbuf_addf(err, "unable to lock packed-refs file: %s",
4252
- strerror(errno));
4253
- ret = TRANSACTION_GENERIC_ERROR;
4254
- goto cleanup;
4255
- }
4256
-
4257
- for (i = 0; i < n; i++) {
4258
- struct ref_update *update = updates[i];
4259
-
4260
- if ((update->flags & REF_HAVE_NEW) &&
4261
- !is_null_sha1(update->new_sha1))
4262
- add_packed_ref(update->refname, update->new_sha1);
4263
- }
4264
-
4265
- if (commit_packed_refs()) {
4266
- strbuf_addf(err, "unable to commit packed-refs file: %s",
4267
- strerror(errno));
4268
- ret = TRANSACTION_GENERIC_ERROR;
4269
- goto cleanup;
4270
- }
4271
-
4272
-cleanup:
4273
- transaction->state = REF_TRANSACTION_CLOSED;
4274
- string_list_clear(&affected_refnames, 0);
4275
- return ret;
4276
-}
4277
-
889
char *shorten_unambiguous_ref(const char *refname, int strict)
890
{
891
int i;
@@ -4418,145 +1029,3 @@ int ref_is_hidden(const char *refname)
1029
}
1030
return 0;
1031
}
4421
-
4422
-struct expire_reflog_cb {
4423
- unsigned int flags;
4424
- reflog_expiry_should_prune_fn *should_prune_fn;
4425
- void *policy_cb;
4426
- FILE *newlog;
4427
- unsigned char last_kept_sha1[20];
4428
-};
4429
-
4430
-static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4431
- const char *email, unsigned long timestamp, int tz,
4432
- const char *message, void *cb_data)
4433
-{
4434
- struct expire_reflog_cb *cb = cb_data;
4435
- struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4436
-
4437
- if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4438
- osha1 = cb->last_kept_sha1;
4439
-
4440
- if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4441
- message, policy_cb)) {
4442
- if (!cb->newlog)
4443
- printf("would prune %s", message);
4444
- else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4445
- printf("prune %s", message);
4446
- } else {
4447
- if (cb->newlog) {
4448
- fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4449
- sha1_to_hex(osha1), sha1_to_hex(nsha1),
4450
- email, timestamp, tz, message);
4451
- hashcpy(cb->last_kept_sha1, nsha1);
4452
- }
4453
- if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4454
- printf("keep %s", message);
4455
- }
4456
- return 0;
4457
-}
4458
-
4459
-int reflog_expire(const char *refname, const unsigned char *sha1,
4460
- unsigned int flags,
4461
- reflog_expiry_prepare_fn prepare_fn,
4462
- reflog_expiry_should_prune_fn should_prune_fn,
4463
- reflog_expiry_cleanup_fn cleanup_fn,
4464
- void *policy_cb_data)
4465
-{
4466
- static struct lock_file reflog_lock;
4467
- struct expire_reflog_cb cb;
4468
- struct ref_lock *lock;
4469
- char *log_file;
4470
- int status = 0;
4471
- int type;
4472
- struct strbuf err = STRBUF_INIT;
4473
-
4474
- memset(&cb, 0, sizeof(cb));
4475
- cb.flags = flags;
4476
- cb.policy_cb = policy_cb_data;
4477
- cb.should_prune_fn = should_prune_fn;
4478
-
4479
- /*
4480
- * The reflog file is locked by holding the lock on the
4481
- * reference itself, plus we might need to update the
4482
- * reference if --updateref was specified:
4483
- */
4484
- lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4485
- if (!lock) {
4486
- error("cannot lock ref '%s': %s", refname, err.buf);
4487
- strbuf_release(&err);
4488
- return -1;
4489
- }
4490
- if (!reflog_exists(refname)) {
4491
- unlock_ref(lock);
4492
- return 0;
4493
- }
4494
-
4495
- log_file = git_pathdup("logs/%s", refname);
4496
- if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4497
- /*
4498
- * Even though holding $GIT_DIR/logs/$reflog.lock has
4499
- * no locking implications, we use the lock_file
4500
- * machinery here anyway because it does a lot of the
4501
- * work we need, including cleaning up if the program
4502
- * exits unexpectedly.
4503
- */
4504
- if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4505
- struct strbuf err = STRBUF_INIT;
4506
- unable_to_lock_message(log_file, errno, &err);
4507
- error("%s", err.buf);
4508
- strbuf_release(&err);
4509
- goto failure;
4510
- }
4511
- cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4512
- if (!cb.newlog) {
4513
- error("cannot fdopen %s (%s)",
4514
- get_lock_file_path(&reflog_lock), strerror(errno));
4515
- goto failure;
4516
- }
4517
- }
4518
-
4519
- (*prepare_fn)(refname, sha1, cb.policy_cb);
4520
- for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4521
- (*cleanup_fn)(cb.policy_cb);
4522
-
4523
- if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4524
- /*
4525
- * It doesn't make sense to adjust a reference pointed
4526
- * to by a symbolic ref based on expiring entries in
4527
- * the symbolic reference's reflog. Nor can we update
4528
- * a reference if there are no remaining reflog
4529
- * entries.
4530
- */
4531
- int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4532
- !(type & REF_ISSYMREF) &&
4533
- !is_null_sha1(cb.last_kept_sha1);
4534
-
4535
- if (close_lock_file(&reflog_lock)) {
4536
- status |= error("couldn't write %s: %s", log_file,
4537
- strerror(errno));
4538
- } else if (update &&
4539
- (write_in_full(get_lock_file_fd(lock->lk),
4540
- sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4541
- write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
4542
- close_ref(lock) < 0)) {
4543
- status |= error("couldn't write %s",
4544
- get_lock_file_path(lock->lk));
4545
- rollback_lock_file(&reflog_lock);
4546
- } else if (commit_lock_file(&reflog_lock)) {
4547
- status |= error("unable to commit reflog '%s' (%s)",
4548
- log_file, strerror(errno));
4549
- } else if (update && commit_ref(lock)) {
4550
- status |= error("couldn't set %s", lock->ref_name);
4551
- }
4552
- }
4553
- free(log_file);
4554
- unlock_ref(lock);
4555
- return status;
4556
-
4557
- failure:
4558
- rollback_lock_file(&reflog_lock);
4559
- free(log_file);
4560
- unlock_ref(lock);
4561
- return -1;
4562
-}
refs/files-backend.c
new
+3539
@@ -0,0 +1,3539 @@
1
+#include "../cache.h"
2
+#include "../refs.h"
3
+#include "refs-internal.h"
4
+#include "../lockfile.h"
5
+#include "../object.h"
6
+#include "../dir.h"
7
+
8
+struct ref_lock {
9
+ char *ref_name;
10
+ char *orig_ref_name;
11
+ struct lock_file *lk;
12
+ struct object_id old_oid;
13
+};
14
+
15
+struct ref_entry;
16
+
17
+/*
18
+ * Information used (along with the information in ref_entry) to
19
+ * describe a single cached reference. This data structure only
20
+ * occurs embedded in a union in struct ref_entry, and only when
21
+ * (ref_entry->flag & REF_DIR) is zero.
22
+ */
23
+struct ref_value {
24
+ /*
25
+ * The name of the object to which this reference resolves
26
+ * (which may be a tag object). If REF_ISBROKEN, this is
27
+ * null. If REF_ISSYMREF, then this is the name of the object
28
+ * referred to by the last reference in the symlink chain.
29
+ */
30
+ struct object_id oid;
31
+
32
+ /*
33
+ * If REF_KNOWS_PEELED, then this field holds the peeled value
34
+ * of this reference, or null if the reference is known not to
35
+ * be peelable. See the documentation for peel_ref() for an
36
+ * exact definition of "peelable".
37
+ */
38
+ struct object_id peeled;
39
+};
40
+
41
+struct ref_cache;
42
+
43
+/*
44
+ * Information used (along with the information in ref_entry) to
45
+ * describe a level in the hierarchy of references. This data
46
+ * structure only occurs embedded in a union in struct ref_entry, and
47
+ * only when (ref_entry.flag & REF_DIR) is set. In that case,
48
+ * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
49
+ * in the directory have already been read:
50
+ *
51
+ * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
52
+ * or packed references, already read.
53
+ *
54
+ * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
55
+ * references that hasn't been read yet (nor has any of its
56
+ * subdirectories).
57
+ *
58
+ * Entries within a directory are stored within a growable array of
59
+ * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
60
+ * sorted are sorted by their component name in strcmp() order and the
61
+ * remaining entries are unsorted.
62
+ *
63
+ * Loose references are read lazily, one directory at a time. When a
64
+ * directory of loose references is read, then all of the references
65
+ * in that directory are stored, and REF_INCOMPLETE stubs are created
66
+ * for any subdirectories, but the subdirectories themselves are not
67
+ * read. The reading is triggered by get_ref_dir().
68
+ */
69
+struct ref_dir {
70
+ int nr, alloc;
71
+
72
+ /*
73
+ * Entries with index 0 <= i < sorted are sorted by name. New
74
+ * entries are appended to the list unsorted, and are sorted
75
+ * only when required; thus we avoid the need to sort the list
76
+ * after the addition of every reference.
77
+ */
78
+ int sorted;
79
+
80
+ /* A pointer to the ref_cache that contains this ref_dir. */
81
+ struct ref_cache *ref_cache;
82
+
83
+ struct ref_entry **entries;
84
+};
85
+
86
+/*
87
+ * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
88
+ * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
89
+ * public values; see refs.h.
90
+ */
91
+
92
+/*
93
+ * The field ref_entry->u.value.peeled of this value entry contains
94
+ * the correct peeled value for the reference, which might be
95
+ * null_sha1 if the reference is not a tag or if it is broken.
96
+ */
97
+#define REF_KNOWS_PEELED 0x10
98
+
99
+/* ref_entry represents a directory of references */
100
+#define REF_DIR 0x20
101
+
102
+/*
103
+ * Entry has not yet been read from disk (used only for REF_DIR
104
+ * entries representing loose references)
105
+ */
106
+#define REF_INCOMPLETE 0x40
107
+
108
+/*
109
+ * A ref_entry represents either a reference or a "subdirectory" of
110
+ * references.
111
+ *
112
+ * Each directory in the reference namespace is represented by a
113
+ * ref_entry with (flags & REF_DIR) set and containing a subdir member
114
+ * that holds the entries in that directory that have been read so
115
+ * far. If (flags & REF_INCOMPLETE) is set, then the directory and
116
+ * its subdirectories haven't been read yet. REF_INCOMPLETE is only
117
+ * used for loose reference directories.
118
+ *
119
+ * References are represented by a ref_entry with (flags & REF_DIR)
120
+ * unset and a value member that describes the reference's value. The
121
+ * flag member is at the ref_entry level, but it is also needed to
122
+ * interpret the contents of the value field (in other words, a
123
+ * ref_value object is not very much use without the enclosing
124
+ * ref_entry).
125
+ *
126
+ * Reference names cannot end with slash and directories' names are
127
+ * always stored with a trailing slash (except for the top-level
128
+ * directory, which is always denoted by ""). This has two nice
129
+ * consequences: (1) when the entries in each subdir are sorted
130
+ * lexicographically by name (as they usually are), the references in
131
+ * a whole tree can be generated in lexicographic order by traversing
132
+ * the tree in left-to-right, depth-first order; (2) the names of
133
+ * references and subdirectories cannot conflict, and therefore the
134
+ * presence of an empty subdirectory does not block the creation of a
135
+ * similarly-named reference. (The fact that reference names with the
136
+ * same leading components can conflict *with each other* is a
137
+ * separate issue that is regulated by verify_refname_available().)
138
+ *
139
+ * Please note that the name field contains the fully-qualified
140
+ * reference (or subdirectory) name. Space could be saved by only
141
+ * storing the relative names. But that would require the full names
142
+ * to be generated on the fly when iterating in do_for_each_ref(), and
143
+ * would break callback functions, who have always been able to assume
144
+ * that the name strings that they are passed will not be freed during
145
+ * the iteration.
146
+ */
147
+struct ref_entry {
148
+ unsigned char flag; /* ISSYMREF? ISPACKED? */
149
+ union {
150
+ struct ref_value value; /* if not (flags&REF_DIR) */
151
+ struct ref_dir subdir; /* if (flags&REF_DIR) */
152
+ } u;
153
+ /*
154
+ * The full name of the reference (e.g., "refs/heads/master")
155
+ * or the full name of the directory with a trailing slash
156
+ * (e.g., "refs/heads/"):
157
+ */
158
+ char name[FLEX_ARRAY];
159
+};
160
+
161
+static void read_loose_refs(const char *dirname, struct ref_dir *dir);
162
+static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
163
+static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
164
+ const char *dirname, size_t len,
165
+ int incomplete);
166
+static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
167
+
168
+static struct ref_dir *get_ref_dir(struct ref_entry *entry)
169
+{
170
+ struct ref_dir *dir;
171
+ assert(entry->flag & REF_DIR);
172
+ dir = &entry->u.subdir;
173
+ if (entry->flag & REF_INCOMPLETE) {
174
+ read_loose_refs(entry->name, dir);
175
+
176
+ /*
177
+ * Manually add refs/bisect, which, being
178
+ * per-worktree, might not appear in the directory
179
+ * listing for refs/ in the main repo.
180
+ */
181
+ if (!strcmp(entry->name, "refs/")) {
182
+ int pos = search_ref_dir(dir, "refs/bisect/", 12);
183
+ if (pos < 0) {
184
+ struct ref_entry *child_entry;
185
+ child_entry = create_dir_entry(dir->ref_cache,
186
+ "refs/bisect/",
187
+ 12, 1);
188
+ add_entry_to_dir(dir, child_entry);
189
+ read_loose_refs("refs/bisect",
190
+ &child_entry->u.subdir);
191
+ }
192
+ }
193
+ entry->flag &= ~REF_INCOMPLETE;
194
+ }
195
+ return dir;
196
+}
197
+
198
+static struct ref_entry *create_ref_entry(const char *refname,
199
+ const unsigned char *sha1, int flag,
200
+ int check_name)
201
+{
202
+ int len;
203
+ struct ref_entry *ref;
204
+
205
+ if (check_name &&
206
+ check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
207
+ die("Reference has invalid format: '%s'", refname);
208
+ len = strlen(refname) + 1;
209
+ ref = xmalloc(sizeof(struct ref_entry) + len);
210
+ hashcpy(ref->u.value.oid.hash, sha1);
211
+ oidclr(&ref->u.value.peeled);
212
+ memcpy(ref->name, refname, len);
213
+ ref->flag = flag;
214
+ return ref;
215
+}
216
+
217
+static void clear_ref_dir(struct ref_dir *dir);
218
+
219
+static void free_ref_entry(struct ref_entry *entry)
220
+{
221
+ if (entry->flag & REF_DIR) {
222
+ /*
223
+ * Do not use get_ref_dir() here, as that might
224
+ * trigger the reading of loose refs.
225
+ */
226
+ clear_ref_dir(&entry->u.subdir);
227
+ }
228
+ free(entry);
229
+}
230
+
231
+/*
232
+ * Add a ref_entry to the end of dir (unsorted). Entry is always
233
+ * stored directly in dir; no recursion into subdirectories is
234
+ * done.
235
+ */
236
+static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
237
+{
238
+ ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
239
+ dir->entries[dir->nr++] = entry;
240
+ /* optimize for the case that entries are added in order */
241
+ if (dir->nr == 1 ||
242
+ (dir->nr == dir->sorted + 1 &&
243
+ strcmp(dir->entries[dir->nr - 2]->name,
244
+ dir->entries[dir->nr - 1]->name) < 0))
245
+ dir->sorted = dir->nr;
246
+}
247
+
248
+/*
249
+ * Clear and free all entries in dir, recursively.
250
+ */
251
+static void clear_ref_dir(struct ref_dir *dir)
252
+{
253
+ int i;
254
+ for (i = 0; i < dir->nr; i++)
255
+ free_ref_entry(dir->entries[i]);
256
+ free(dir->entries);
257
+ dir->sorted = dir->nr = dir->alloc = 0;
258
+ dir->entries = NULL;
259
+}
260
+
261
+/*
262
+ * Create a struct ref_entry object for the specified dirname.
263
+ * dirname is the name of the directory with a trailing slash (e.g.,
264
+ * "refs/heads/") or "" for the top-level directory.
265
+ */
266
+static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
267
+ const char *dirname, size_t len,
268
+ int incomplete)
269
+{
270
+ struct ref_entry *direntry;
271
+ direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
272
+ memcpy(direntry->name, dirname, len);
273
+ direntry->name[len] = '\0';
274
+ direntry->u.subdir.ref_cache = ref_cache;
275
+ direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
276
+ return direntry;
277
+}
278
+
279
+static int ref_entry_cmp(const void *a, const void *b)
280
+{
281
+ struct ref_entry *one = *(struct ref_entry **)a;
282
+ struct ref_entry *two = *(struct ref_entry **)b;
283
+ return strcmp(one->name, two->name);
284
+}
285
+
286
+static void sort_ref_dir(struct ref_dir *dir);
287
+
288
+struct string_slice {
289
+ size_t len;
290
+ const char *str;
291
+};
292
+
293
+static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
294
+{
295
+ const struct string_slice *key = key_;
296
+ const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
297
+ int cmp = strncmp(key->str, ent->name, key->len);
298
+ if (cmp)
299
+ return cmp;
300
+ return '\0' - (unsigned char)ent->name[key->len];
301
+}
302
+
303
+/*
304
+ * Return the index of the entry with the given refname from the
305
+ * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
306
+ * no such entry is found. dir must already be complete.
307
+ */
308
+static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
309
+{
310
+ struct ref_entry **r;
311
+ struct string_slice key;
312
+
313
+ if (refname == NULL || !dir->nr)
314
+ return -1;
315
+
316
+ sort_ref_dir(dir);
317
+ key.len = len;
318
+ key.str = refname;
319
+ r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
320
+ ref_entry_cmp_sslice);
321
+
322
+ if (r == NULL)
323
+ return -1;
324
+
325
+ return r - dir->entries;
326
+}
327
+
328
+/*
329
+ * Search for a directory entry directly within dir (without
330
+ * recursing). Sort dir if necessary. subdirname must be a directory
331
+ * name (i.e., end in '/'). If mkdir is set, then create the
332
+ * directory if it is missing; otherwise, return NULL if the desired
333
+ * directory cannot be found. dir must already be complete.
334
+ */
335
+static struct ref_dir *search_for_subdir(struct ref_dir *dir,
336
+ const char *subdirname, size_t len,
337
+ int mkdir)
338
+{
339
+ int entry_index = search_ref_dir(dir, subdirname, len);
340
+ struct ref_entry *entry;
341
+ if (entry_index == -1) {
342
+ if (!mkdir)
343
+ return NULL;
344
+ /*
345
+ * Since dir is complete, the absence of a subdir
346
+ * means that the subdir really doesn't exist;
347
+ * therefore, create an empty record for it but mark
348
+ * the record complete.
349
+ */
350
+ entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
351
+ add_entry_to_dir(dir, entry);
352
+ } else {
353
+ entry = dir->entries[entry_index];
354
+ }
355
+ return get_ref_dir(entry);
356
+}
357
+
358
+/*
359
+ * If refname is a reference name, find the ref_dir within the dir
360
+ * tree that should hold refname. If refname is a directory name
361
+ * (i.e., ends in '/'), then return that ref_dir itself. dir must
362
+ * represent the top-level directory and must already be complete.
363
+ * Sort ref_dirs and recurse into subdirectories as necessary. If
364
+ * mkdir is set, then create any missing directories; otherwise,
365
+ * return NULL if the desired directory cannot be found.
366
+ */
367
+static struct ref_dir *find_containing_dir(struct ref_dir *dir,
368
+ const char *refname, int mkdir)
369
+{
370
+ const char *slash;
371
+ for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
372
+ size_t dirnamelen = slash - refname + 1;
373
+ struct ref_dir *subdir;
374
+ subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
375
+ if (!subdir) {
376
+ dir = NULL;
377
+ break;
378
+ }
379
+ dir = subdir;
380
+ }
381
+
382
+ return dir;
383
+}
384
+
385
+/*
386
+ * Find the value entry with the given name in dir, sorting ref_dirs
387
+ * and recursing into subdirectories as necessary. If the name is not
388
+ * found or it corresponds to a directory entry, return NULL.
389
+ */
390
+static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
391
+{
392
+ int entry_index;
393
+ struct ref_entry *entry;
394
+ dir = find_containing_dir(dir, refname, 0);
395
+ if (!dir)
396
+ return NULL;
397
+ entry_index = search_ref_dir(dir, refname, strlen(refname));
398
+ if (entry_index == -1)
399
+ return NULL;
400
+ entry = dir->entries[entry_index];
401
+ return (entry->flag & REF_DIR) ? NULL : entry;
402
+}
403
+
404
+/*
405
+ * Remove the entry with the given name from dir, recursing into
406
+ * subdirectories as necessary. If refname is the name of a directory
407
+ * (i.e., ends with '/'), then remove the directory and its contents.
408
+ * If the removal was successful, return the number of entries
409
+ * remaining in the directory entry that contained the deleted entry.
410
+ * If the name was not found, return -1. Please note that this
411
+ * function only deletes the entry from the cache; it does not delete
412
+ * it from the filesystem or ensure that other cache entries (which
413
+ * might be symbolic references to the removed entry) are updated.
414
+ * Nor does it remove any containing dir entries that might be made
415
+ * empty by the removal. dir must represent the top-level directory
416
+ * and must already be complete.
417
+ */
418
+static int remove_entry(struct ref_dir *dir, const char *refname)
419
+{
420
+ int refname_len = strlen(refname);
421
+ int entry_index;
422
+ struct ref_entry *entry;
423
+ int is_dir = refname[refname_len - 1] == '/';
424
+ if (is_dir) {
425
+ /*
426
+ * refname represents a reference directory. Remove
427
+ * the trailing slash; otherwise we will get the
428
+ * directory *representing* refname rather than the
429
+ * one *containing* it.
430
+ */
431
+ char *dirname = xmemdupz(refname, refname_len - 1);
432
+ dir = find_containing_dir(dir, dirname, 0);
433
+ free(dirname);
434
+ } else {
435
+ dir = find_containing_dir(dir, refname, 0);
436
+ }
437
+ if (!dir)
438
+ return -1;
439
+ entry_index = search_ref_dir(dir, refname, refname_len);
440
+ if (entry_index == -1)
441
+ return -1;
442
+ entry = dir->entries[entry_index];
443
+
444
+ memmove(&dir->entries[entry_index],
445
+ &dir->entries[entry_index + 1],
446
+ (dir->nr - entry_index - 1) * sizeof(*dir->entries)
447
+ );
448
+ dir->nr--;
449
+ if (dir->sorted > entry_index)
450
+ dir->sorted--;
451
+ free_ref_entry(entry);
452
+ return dir->nr;
453
+}
454
+
455
+/*
456
+ * Add a ref_entry to the ref_dir (unsorted), recursing into
457
+ * subdirectories as necessary. dir must represent the top-level
458
+ * directory. Return 0 on success.
459
+ */
460
+static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
461
+{
462
+ dir = find_containing_dir(dir, ref->name, 1);
463
+ if (!dir)
464
+ return -1;
465
+ add_entry_to_dir(dir, ref);
466
+ return 0;
467
+}
468
+
469
+/*
470
+ * Emit a warning and return true iff ref1 and ref2 have the same name
471
+ * and the same sha1. Die if they have the same name but different
472
+ * sha1s.
473
+ */
474
+static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
475
+{
476
+ if (strcmp(ref1->name, ref2->name))
477
+ return 0;
478
+
479
+ /* Duplicate name; make sure that they don't conflict: */
480
+
481
+ if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
482
+ /* This is impossible by construction */
483
+ die("Reference directory conflict: %s", ref1->name);
484
+
485
+ if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
486
+ die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
487
+
488
+ warning("Duplicated ref: %s", ref1->name);
489
+ return 1;
490
+}
491
+
492
+/*
493
+ * Sort the entries in dir non-recursively (if they are not already
494
+ * sorted) and remove any duplicate entries.
495
+ */
496
+static void sort_ref_dir(struct ref_dir *dir)
497
+{
498
+ int i, j;
499
+ struct ref_entry *last = NULL;
500
+
501
+ /*
502
+ * This check also prevents passing a zero-length array to qsort(),
503
+ * which is a problem on some platforms.
504
+ */
505
+ if (dir->sorted == dir->nr)
506
+ return;
507
+
508
+ qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
509
+
510
+ /* Remove any duplicates: */
511
+ for (i = 0, j = 0; j < dir->nr; j++) {
512
+ struct ref_entry *entry = dir->entries[j];
513
+ if (last && is_dup_ref(last, entry))
514
+ free_ref_entry(entry);
515
+ else
516
+ last = dir->entries[i++] = entry;
517
+ }
518
+ dir->sorted = dir->nr = i;
519
+}
520
+
521
+/* Include broken references in a do_for_each_ref*() iteration: */
522
+#define DO_FOR_EACH_INCLUDE_BROKEN 0x01
523
+
524
+/*
525
+ * Return true iff the reference described by entry can be resolved to
526
+ * an object in the database. Emit a warning if the referred-to
527
+ * object does not exist.
528
+ */
529
+static int ref_resolves_to_object(struct ref_entry *entry)
530
+{
531
+ if (entry->flag & REF_ISBROKEN)
532
+ return 0;
533
+ if (!has_sha1_file(entry->u.value.oid.hash)) {
534
+ error("%s does not point to a valid object!", entry->name);
535
+ return 0;
536
+ }
537
+ return 1;
538
+}
539
+
540
+/*
541
+ * current_ref is a performance hack: when iterating over references
542
+ * using the for_each_ref*() functions, current_ref is set to the
543
+ * current reference's entry before calling the callback function. If
544
+ * the callback function calls peel_ref(), then peel_ref() first
545
+ * checks whether the reference to be peeled is the current reference
546
+ * (it usually is) and if so, returns that reference's peeled version
547
+ * if it is available. This avoids a refname lookup in a common case.
548
+ */
549
+static struct ref_entry *current_ref;
550
+
551
+typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
552
+
553
+struct ref_entry_cb {
554
+ const char *base;
555
+ int trim;
556
+ int flags;
557
+ each_ref_fn *fn;
558
+ void *cb_data;
559
+};
560
+
561
+/*
562
+ * Handle one reference in a do_for_each_ref*()-style iteration,
563
+ * calling an each_ref_fn for each entry.
564
+ */
565
+static int do_one_ref(struct ref_entry *entry, void *cb_data)
566
+{
567
+ struct ref_entry_cb *data = cb_data;
568
+ struct ref_entry *old_current_ref;
569
+ int retval;
570
+
571
+ if (!starts_with(entry->name, data->base))
572
+ return 0;
573
+
574
+ if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
575
+ !ref_resolves_to_object(entry))
576
+ return 0;
577
+
578
+ /* Store the old value, in case this is a recursive call: */
579
+ old_current_ref = current_ref;
580
+ current_ref = entry;
581
+ retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
582
+ entry->flag, data->cb_data);
583
+ current_ref = old_current_ref;
584
+ return retval;
585
+}
586
+
587
+/*
588
+ * Call fn for each reference in dir that has index in the range
589
+ * offset <= index < dir->nr. Recurse into subdirectories that are in
590
+ * that index range, sorting them before iterating. This function
591
+ * does not sort dir itself; it should be sorted beforehand. fn is
592
+ * called for all references, including broken ones.
593
+ */
594
+static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
595
+ each_ref_entry_fn fn, void *cb_data)
596
+{
597
+ int i;
598
+ assert(dir->sorted == dir->nr);
599
+ for (i = offset; i < dir->nr; i++) {
600
+ struct ref_entry *entry = dir->entries[i];
601
+ int retval;
602
+ if (entry->flag & REF_DIR) {
603
+ struct ref_dir *subdir = get_ref_dir(entry);
604
+ sort_ref_dir(subdir);
605
+ retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
606
+ } else {
607
+ retval = fn(entry, cb_data);
608
+ }
609
+ if (retval)
610
+ return retval;
611
+ }
612
+ return 0;
613
+}
614
+
615
+/*
616
+ * Call fn for each reference in the union of dir1 and dir2, in order
617
+ * by refname. Recurse into subdirectories. If a value entry appears
618
+ * in both dir1 and dir2, then only process the version that is in
619
+ * dir2. The input dirs must already be sorted, but subdirs will be
620
+ * sorted as needed. fn is called for all references, including
621
+ * broken ones.
622
+ */
623
+static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
624
+ struct ref_dir *dir2,
625
+ each_ref_entry_fn fn, void *cb_data)
626
+{
627
+ int retval;
628
+ int i1 = 0, i2 = 0;
629
+
630
+ assert(dir1->sorted == dir1->nr);
631
+ assert(dir2->sorted == dir2->nr);
632
+ while (1) {
633
+ struct ref_entry *e1, *e2;
634
+ int cmp;
635
+ if (i1 == dir1->nr) {
636
+ return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
637
+ }
638
+ if (i2 == dir2->nr) {
639
+ return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
640
+ }
641
+ e1 = dir1->entries[i1];
642
+ e2 = dir2->entries[i2];
643
+ cmp = strcmp(e1->name, e2->name);
644
+ if (cmp == 0) {
645
+ if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
646
+ /* Both are directories; descend them in parallel. */
647
+ struct ref_dir *subdir1 = get_ref_dir(e1);
648
+ struct ref_dir *subdir2 = get_ref_dir(e2);
649
+ sort_ref_dir(subdir1);
650
+ sort_ref_dir(subdir2);
651
+ retval = do_for_each_entry_in_dirs(
652
+ subdir1, subdir2, fn, cb_data);
653
+ i1++;
654
+ i2++;
655
+ } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
656
+ /* Both are references; ignore the one from dir1. */
657
+ retval = fn(e2, cb_data);
658
+ i1++;
659
+ i2++;
660
+ } else {
661
+ die("conflict between reference and directory: %s",
662
+ e1->name);
663
+ }
664
+ } else {
665
+ struct ref_entry *e;
666
+ if (cmp < 0) {
667
+ e = e1;
668
+ i1++;
669
+ } else {
670
+ e = e2;
671
+ i2++;
672
+ }
673
+ if (e->flag & REF_DIR) {
674
+ struct ref_dir *subdir = get_ref_dir(e);
675
+ sort_ref_dir(subdir);
676
+ retval = do_for_each_entry_in_dir(
677
+ subdir, 0, fn, cb_data);
678
+ } else {
679
+ retval = fn(e, cb_data);
680
+ }
681
+ }
682
+ if (retval)
683
+ return retval;
684
+ }
685
+}
686
+
687
+/*
688
+ * Load all of the refs from the dir into our in-memory cache. The hard work
689
+ * of loading loose refs is done by get_ref_dir(), so we just need to recurse
690
+ * through all of the sub-directories. We do not even need to care about
691
+ * sorting, as traversal order does not matter to us.
692
+ */
693
+static void prime_ref_dir(struct ref_dir *dir)
694
+{
695
+ int i;
696
+ for (i = 0; i < dir->nr; i++) {
697
+ struct ref_entry *entry = dir->entries[i];
698
+ if (entry->flag & REF_DIR)
699
+ prime_ref_dir(get_ref_dir(entry));
700
+ }
701
+}
702
+
703
+struct nonmatching_ref_data {
704
+ const struct string_list *skip;
705
+ const char *conflicting_refname;
706
+};
707
+
708
+static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
709
+{
710
+ struct nonmatching_ref_data *data = vdata;
711
+
712
+ if (data->skip && string_list_has_string(data->skip, entry->name))
713
+ return 0;
714
+
715
+ data->conflicting_refname = entry->name;
716
+ return 1;
717
+}
718
+
719
+/*
720
+ * Return 0 if a reference named refname could be created without
721
+ * conflicting with the name of an existing reference in dir.
722
+ * See verify_refname_available for more information.
723
+ */
724
+static int verify_refname_available_dir(const char *refname,
725
+ const struct string_list *extras,
726
+ const struct string_list *skip,
727
+ struct ref_dir *dir,
728
+ struct strbuf *err)
729
+{
730
+ const char *slash;
731
+ int pos;
732
+ struct strbuf dirname = STRBUF_INIT;
733
+ int ret = -1;
734
+
735
+ /*
736
+ * For the sake of comments in this function, suppose that
737
+ * refname is "refs/foo/bar".
738
+ */
739
+
740
+ assert(err);
741
+
742
+ strbuf_grow(&dirname, strlen(refname) + 1);
743
+ for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
744
+ /* Expand dirname to the new prefix, not including the trailing slash: */
745
+ strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
746
+
747
+ /*
748
+ * We are still at a leading dir of the refname (e.g.,
749
+ * "refs/foo"; if there is a reference with that name,
750
+ * it is a conflict, *unless* it is in skip.
751
+ */
752
+ if (dir) {
753
+ pos = search_ref_dir(dir, dirname.buf, dirname.len);
754
+ if (pos >= 0 &&
755
+ (!skip || !string_list_has_string(skip, dirname.buf))) {
756
+ /*
757
+ * We found a reference whose name is
758
+ * a proper prefix of refname; e.g.,
759
+ * "refs/foo", and is not in skip.
760
+ */
761
+ strbuf_addf(err, "'%s' exists; cannot create '%s'",
762
+ dirname.buf, refname);
763
+ goto cleanup;
764
+ }
765
+ }
766
+
767
+ if (extras && string_list_has_string(extras, dirname.buf) &&
768
+ (!skip || !string_list_has_string(skip, dirname.buf))) {
769
+ strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
770
+ refname, dirname.buf);
771
+ goto cleanup;
772
+ }
773
+
774
+ /*
775
+ * Otherwise, we can try to continue our search with
776
+ * the next component. So try to look up the
777
+ * directory, e.g., "refs/foo/". If we come up empty,
778
+ * we know there is nothing under this whole prefix,
779
+ * but even in that case we still have to continue the
780
+ * search for conflicts with extras.
781
+ */
782
+ strbuf_addch(&dirname, '/');
783
+ if (dir) {
784
+ pos = search_ref_dir(dir, dirname.buf, dirname.len);
785
+ if (pos < 0) {
786
+ /*
787
+ * There was no directory "refs/foo/",
788
+ * so there is nothing under this
789
+ * whole prefix. So there is no need
790
+ * to continue looking for conflicting
791
+ * references. But we need to continue
792
+ * looking for conflicting extras.
793
+ */
794
+ dir = NULL;
795
+ } else {
796
+ dir = get_ref_dir(dir->entries[pos]);
797
+ }
798
+ }
799
+ }
800
+
801
+ /*
802
+ * We are at the leaf of our refname (e.g., "refs/foo/bar").
803
+ * There is no point in searching for a reference with that
804
+ * name, because a refname isn't considered to conflict with
805
+ * itself. But we still need to check for references whose
806
+ * names are in the "refs/foo/bar/" namespace, because they
807
+ * *do* conflict.
808
+ */
809
+ strbuf_addstr(&dirname, refname + dirname.len);
810
+ strbuf_addch(&dirname, '/');
811
+
812
+ if (dir) {
813
+ pos = search_ref_dir(dir, dirname.buf, dirname.len);
814
+
815
+ if (pos >= 0) {
816
+ /*
817
+ * We found a directory named "$refname/"
818
+ * (e.g., "refs/foo/bar/"). It is a problem
819
+ * iff it contains any ref that is not in
820
+ * "skip".
821
+ */
822
+ struct nonmatching_ref_data data;
823
+
824
+ data.skip = skip;
825
+ data.conflicting_refname = NULL;
826
+ dir = get_ref_dir(dir->entries[pos]);
827
+ sort_ref_dir(dir);
828
+ if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
829
+ strbuf_addf(err, "'%s' exists; cannot create '%s'",
830
+ data.conflicting_refname, refname);
831
+ goto cleanup;
832
+ }
833
+ }
834
+ }
835
+
836
+ if (extras) {
837
+ /*
838
+ * Check for entries in extras that start with
839
+ * "$refname/". We do that by looking for the place
840
+ * where "$refname/" would be inserted in extras. If
841
+ * there is an entry at that position that starts with
842
+ * "$refname/" and is not in skip, then we have a
843
+ * conflict.
844
+ */
845
+ for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
846
+ pos < extras->nr; pos++) {
847
+ const char *extra_refname = extras->items[pos].string;
848
+
849
+ if (!starts_with(extra_refname, dirname.buf))
850
+ break;
851
+
852
+ if (!skip || !string_list_has_string(skip, extra_refname)) {
853
+ strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
854
+ refname, extra_refname);
855
+ goto cleanup;
856
+ }
857
+ }
858
+ }
859
+
860
+ /* No conflicts were found */
861
+ ret = 0;
862
+
863
+cleanup:
864
+ strbuf_release(&dirname);
865
+ return ret;
866
+}
867
+
868
+struct packed_ref_cache {
869
+ struct ref_entry *root;
870
+
871
+ /*
872
+ * Count of references to the data structure in this instance,
873
+ * including the pointer from ref_cache::packed if any. The
874
+ * data will not be freed as long as the reference count is
875
+ * nonzero.
876
+ */
877
+ unsigned int referrers;
878
+
879
+ /*
880
+ * Iff the packed-refs file associated with this instance is
881
+ * currently locked for writing, this points at the associated
882
+ * lock (which is owned by somebody else). The referrer count
883
+ * is also incremented when the file is locked and decremented
884
+ * when it is unlocked.
885
+ */
886
+ struct lock_file *lock;
887
+
888
+ /* The metadata from when this packed-refs cache was read */
889
+ struct stat_validity validity;
890
+};
891
+
892
+/*
893
+ * Future: need to be in "struct repository"
894
+ * when doing a full libification.
895
+ */
896
+static struct ref_cache {
897
+ struct ref_cache *next;
898
+ struct ref_entry *loose;
899
+ struct packed_ref_cache *packed;
900
+ /*
901
+ * The submodule name, or "" for the main repo. We allocate
902
+ * length 1 rather than FLEX_ARRAY so that the main ref_cache
903
+ * is initialized correctly.
904
+ */
905
+ char name[1];
906
+} ref_cache, *submodule_ref_caches;
907
+
908
+/* Lock used for the main packed-refs file: */
909
+static struct lock_file packlock;
910
+
911
+/*
912
+ * Increment the reference count of *packed_refs.
913
+ */
914
+static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
915
+{
916
+ packed_refs->referrers++;
917
+}
918
+
919
+/*
920
+ * Decrease the reference count of *packed_refs. If it goes to zero,
921
+ * free *packed_refs and return true; otherwise return false.
922
+ */
923
+static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
924
+{
925
+ if (!--packed_refs->referrers) {
926
+ free_ref_entry(packed_refs->root);
927
+ stat_validity_clear(&packed_refs->validity);
928
+ free(packed_refs);
929
+ return 1;
930
+ } else {
931
+ return 0;
932
+ }
933
+}
934
+
935
+static void clear_packed_ref_cache(struct ref_cache *refs)
936
+{
937
+ if (refs->packed) {
938
+ struct packed_ref_cache *packed_refs = refs->packed;
939
+
940
+ if (packed_refs->lock)
941
+ die("internal error: packed-ref cache cleared while locked");
942
+ refs->packed = NULL;
943
+ release_packed_ref_cache(packed_refs);
944
+ }
945
+}
946
+
947
+static void clear_loose_ref_cache(struct ref_cache *refs)
948
+{
949
+ if (refs->loose) {
950
+ free_ref_entry(refs->loose);
951
+ refs->loose = NULL;
952
+ }
953
+}
954
+
955
+static struct ref_cache *create_ref_cache(const char *submodule)
956
+{
957
+ int len;
958
+ struct ref_cache *refs;
959
+ if (!submodule)
960
+ submodule = "";
961
+ len = strlen(submodule) + 1;
962
+ refs = xcalloc(1, sizeof(struct ref_cache) + len);
963
+ memcpy(refs->name, submodule, len);
964
+ return refs;
965
+}
966
+
967
+/*
968
+ * Return a pointer to a ref_cache for the specified submodule. For
969
+ * the main repository, use submodule==NULL. The returned structure
970
+ * will be allocated and initialized but not necessarily populated; it
971
+ * should not be freed.
972
+ */
973
+static struct ref_cache *get_ref_cache(const char *submodule)
974
+{
975
+ struct ref_cache *refs;
976
+
977
+ if (!submodule || !*submodule)
978
+ return &ref_cache;
979
+
980
+ for (refs = submodule_ref_caches; refs; refs = refs->next)
981
+ if (!strcmp(submodule, refs->name))
982
+ return refs;
983
+
984
+ refs = create_ref_cache(submodule);
985
+ refs->next = submodule_ref_caches;
986
+ submodule_ref_caches = refs;
987
+ return refs;
988
+}
989
+
990
+/* The length of a peeled reference line in packed-refs, including EOL: */
991
+#define PEELED_LINE_LENGTH 42
992
+
993
+/*
994
+ * The packed-refs header line that we write out. Perhaps other
995
+ * traits will be added later. The trailing space is required.
996
+ */
997
+static const char PACKED_REFS_HEADER[] =
998
+ "# pack-refs with: peeled fully-peeled \n";
999
+
1000
+/*
1001
+ * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1002
+ * Return a pointer to the refname within the line (null-terminated),
1003
+ * or NULL if there was a problem.
1004
+ */
1005
+static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1006
+{
1007
+ const char *ref;
1008
+
1009
+ /*
1010
+ * 42: the answer to everything.
1011
+ *
1012
+ * In this case, it happens to be the answer to
1013
+ * 40 (length of sha1 hex representation)
1014
+ * +1 (space in between hex and name)
1015
+ * +1 (newline at the end of the line)
1016
+ */
1017
+ if (line->len <= 42)
1018
+ return NULL;
1019
+
1020
+ if (get_sha1_hex(line->buf, sha1) < 0)
1021
+ return NULL;
1022
+ if (!isspace(line->buf[40]))
1023
+ return NULL;
1024
+
1025
+ ref = line->buf + 41;
1026
+ if (isspace(*ref))
1027
+ return NULL;
1028
+
1029
+ if (line->buf[line->len - 1] != '\n')
1030
+ return NULL;
1031
+ line->buf[--line->len] = 0;
1032
+
1033
+ return ref;
1034
+}
1035
+
1036
+/*
1037
+ * Read f, which is a packed-refs file, into dir.
1038
+ *
1039
+ * A comment line of the form "# pack-refs with: " may contain zero or
1040
+ * more traits. We interpret the traits as follows:
1041
+ *
1042
+ * No traits:
1043
+ *
1044
+ * Probably no references are peeled. But if the file contains a
1045
+ * peeled value for a reference, we will use it.
1046
+ *
1047
+ * peeled:
1048
+ *
1049
+ * References under "refs/tags/", if they *can* be peeled, *are*
1050
+ * peeled in this file. References outside of "refs/tags/" are
1051
+ * probably not peeled even if they could have been, but if we find
1052
+ * a peeled value for such a reference we will use it.
1053
+ *
1054
+ * fully-peeled:
1055
+ *
1056
+ * All references in the file that can be peeled are peeled.
1057
+ * Inversely (and this is more important), any references in the
1058
+ * file for which no peeled value is recorded is not peelable. This
1059
+ * trait should typically be written alongside "peeled" for
1060
+ * compatibility with older clients, but we do not require it
1061
+ * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1062
+ */
1063
+static void read_packed_refs(FILE *f, struct ref_dir *dir)
1064
+{
1065
+ struct ref_entry *last = NULL;
1066
+ struct strbuf line = STRBUF_INIT;
1067
+ enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1068
+
1069
+ while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1070
+ unsigned char sha1[20];
1071
+ const char *refname;
1072
+ const char *traits;
1073
+
1074
+ if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1075
+ if (strstr(traits, " fully-peeled "))
1076
+ peeled = PEELED_FULLY;
1077
+ else if (strstr(traits, " peeled "))
1078
+ peeled = PEELED_TAGS;
1079
+ /* perhaps other traits later as well */
1080
+ continue;
1081
+ }
1082
+
1083
+ refname = parse_ref_line(&line, sha1);
1084
+ if (refname) {
1085
+ int flag = REF_ISPACKED;
1086
+
1087
+ if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1088
+ if (!refname_is_safe(refname))
1089
+ die("packed refname is dangerous: %s", refname);
1090
+ hashclr(sha1);
1091
+ flag |= REF_BAD_NAME | REF_ISBROKEN;
1092
+ }
1093
+ last = create_ref_entry(refname, sha1, flag, 0);
1094
+ if (peeled == PEELED_FULLY ||
1095
+ (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1096
+ last->flag |= REF_KNOWS_PEELED;
1097
+ add_ref(dir, last);
1098
+ continue;
1099
+ }
1100
+ if (last &&
1101
+ line.buf[0] == '^' &&
1102
+ line.len == PEELED_LINE_LENGTH &&
1103
+ line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1104
+ !get_sha1_hex(line.buf + 1, sha1)) {
1105
+ hashcpy(last->u.value.peeled.hash, sha1);
1106
+ /*
1107
+ * Regardless of what the file header said,
1108
+ * we definitely know the value of *this*
1109
+ * reference:
1110
+ */
1111
+ last->flag |= REF_KNOWS_PEELED;
1112
+ }
1113
+ }
1114
+
1115
+ strbuf_release(&line);
1116
+}
1117
+
1118
+/*
1119
+ * Get the packed_ref_cache for the specified ref_cache, creating it
1120
+ * if necessary.
1121
+ */
1122
+static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1123
+{
1124
+ char *packed_refs_file;
1125
+
1126
+ if (*refs->name)
1127
+ packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1128
+ else
1129
+ packed_refs_file = git_pathdup("packed-refs");
1130
+
1131
+ if (refs->packed &&
1132
+ !stat_validity_check(&refs->packed->validity, packed_refs_file))
1133
+ clear_packed_ref_cache(refs);
1134
+
1135
+ if (!refs->packed) {
1136
+ FILE *f;
1137
+
1138
+ refs->packed = xcalloc(1, sizeof(*refs->packed));
1139
+ acquire_packed_ref_cache(refs->packed);
1140
+ refs->packed->root = create_dir_entry(refs, "", 0, 0);
1141
+ f = fopen(packed_refs_file, "r");
1142
+ if (f) {
1143
+ stat_validity_update(&refs->packed->validity, fileno(f));
1144
+ read_packed_refs(f, get_ref_dir(refs->packed->root));
1145
+ fclose(f);
1146
+ }
1147
+ }
1148
+ free(packed_refs_file);
1149
+ return refs->packed;
1150
+}
1151
+
1152
+static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1153
+{
1154
+ return get_ref_dir(packed_ref_cache->root);
1155
+}
1156
+
1157
+static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1158
+{
1159
+ return get_packed_ref_dir(get_packed_ref_cache(refs));
1160
+}
1161
+
1162
+/*
1163
+ * Add a reference to the in-memory packed reference cache. This may
1164
+ * only be called while the packed-refs file is locked (see
1165
+ * lock_packed_refs()). To actually write the packed-refs file, call
1166
+ * commit_packed_refs().
1167
+ */
1168
+static void add_packed_ref(const char *refname, const unsigned char *sha1)
1169
+{
1170
+ struct packed_ref_cache *packed_ref_cache =
1171
+ get_packed_ref_cache(&ref_cache);
1172
+
1173
+ if (!packed_ref_cache->lock)
1174
+ die("internal error: packed refs not locked");
1175
+ add_ref(get_packed_ref_dir(packed_ref_cache),
1176
+ create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1177
+}
1178
+
1179
+/*
1180
+ * Read the loose references from the namespace dirname into dir
1181
+ * (without recursing). dirname must end with '/'. dir must be the
1182
+ * directory entry corresponding to dirname.
1183
+ */
1184
+static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1185
+{
1186
+ struct ref_cache *refs = dir->ref_cache;
1187
+ DIR *d;
1188
+ struct dirent *de;
1189
+ int dirnamelen = strlen(dirname);
1190
+ struct strbuf refname;
1191
+ struct strbuf path = STRBUF_INIT;
1192
+ size_t path_baselen;
1193
+
1194
+ if (*refs->name)
1195
+ strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1196
+ else
1197
+ strbuf_git_path(&path, "%s", dirname);
1198
+ path_baselen = path.len;
1199
+
1200
+ d = opendir(path.buf);
1201
+ if (!d) {
1202
+ strbuf_release(&path);
1203
+ return;
1204
+ }
1205
+
1206
+ strbuf_init(&refname, dirnamelen + 257);
1207
+ strbuf_add(&refname, dirname, dirnamelen);
1208
+
1209
+ while ((de = readdir(d)) != NULL) {
1210
+ unsigned char sha1[20];
1211
+ struct stat st;
1212
+ int flag;
1213
+
1214
+ if (de->d_name[0] == '.')
1215
+ continue;
1216
+ if (ends_with(de->d_name, ".lock"))
1217
+ continue;
1218
+ strbuf_addstr(&refname, de->d_name);
1219
+ strbuf_addstr(&path, de->d_name);
1220
+ if (stat(path.buf, &st) < 0) {
1221
+ ; /* silently ignore */
1222
+ } else if (S_ISDIR(st.st_mode)) {
1223
+ strbuf_addch(&refname, '/');
1224
+ add_entry_to_dir(dir,
1225
+ create_dir_entry(refs, refname.buf,
1226
+ refname.len, 1));
1227
+ } else {
1228
+ int read_ok;
1229
+
1230
+ if (*refs->name) {
1231
+ hashclr(sha1);
1232
+ flag = 0;
1233
+ read_ok = !resolve_gitlink_ref(refs->name,
1234
+ refname.buf, sha1);
1235
+ } else {
1236
+ read_ok = !read_ref_full(refname.buf,
1237
+ RESOLVE_REF_READING,
1238
+ sha1, &flag);
1239
+ }
1240
+
1241
+ if (!read_ok) {
1242
+ hashclr(sha1);
1243
+ flag |= REF_ISBROKEN;
1244
+ } else if (is_null_sha1(sha1)) {
1245
+ /*
1246
+ * It is so astronomically unlikely
1247
+ * that NULL_SHA1 is the SHA-1 of an
1248
+ * actual object that we consider its
1249
+ * appearance in a loose reference
1250
+ * file to be repo corruption
1251
+ * (probably due to a software bug).
1252
+ */
1253
+ flag |= REF_ISBROKEN;
1254
+ }
1255
+
1256
+ if (check_refname_format(refname.buf,
1257
+ REFNAME_ALLOW_ONELEVEL)) {
1258
+ if (!refname_is_safe(refname.buf))
1259
+ die("loose refname is dangerous: %s", refname.buf);
1260
+ hashclr(sha1);
1261
+ flag |= REF_BAD_NAME | REF_ISBROKEN;
1262
+ }
1263
+ add_entry_to_dir(dir,
1264
+ create_ref_entry(refname.buf, sha1, flag, 0));
1265
+ }
1266
+ strbuf_setlen(&refname, dirnamelen);
1267
+ strbuf_setlen(&path, path_baselen);
1268
+ }
1269
+ strbuf_release(&refname);
1270
+ strbuf_release(&path);
1271
+ closedir(d);
1272
+}
1273
+
1274
+static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1275
+{
1276
+ if (!refs->loose) {
1277
+ /*
1278
+ * Mark the top-level directory complete because we
1279
+ * are about to read the only subdirectory that can
1280
+ * hold references:
1281
+ */
1282
+ refs->loose = create_dir_entry(refs, "", 0, 0);
1283
+ /*
1284
+ * Create an incomplete entry for "refs/":
1285
+ */
1286
+ add_entry_to_dir(get_ref_dir(refs->loose),
1287
+ create_dir_entry(refs, "refs/", 5, 1));
1288
+ }
1289
+ return get_ref_dir(refs->loose);
1290
+}
1291
+
1292
+/* We allow "recursive" symbolic refs. Only within reason, though */
1293
+#define MAXDEPTH 5
1294
+#define MAXREFLEN (1024)
1295
+
1296
+/*
1297
+ * Called by resolve_gitlink_ref_recursive() after it failed to read
1298
+ * from the loose refs in ref_cache refs. Find <refname> in the
1299
+ * packed-refs file for the submodule.
1300
+ */
1301
+static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1302
+ const char *refname, unsigned char *sha1)
1303
+{
1304
+ struct ref_entry *ref;
1305
+ struct ref_dir *dir = get_packed_refs(refs);
1306
+
1307
+ ref = find_ref(dir, refname);
1308
+ if (ref == NULL)
1309
+ return -1;
1310
+
1311
+ hashcpy(sha1, ref->u.value.oid.hash);
1312
+ return 0;
1313
+}
1314
+
1315
+static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1316
+ const char *refname, unsigned char *sha1,
1317
+ int recursion)
1318
+{
1319
+ int fd, len;
1320
+ char buffer[128], *p;
1321
+ char *path;
1322
+
1323
+ if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1324
+ return -1;
1325
+ path = *refs->name
1326
+ ? git_pathdup_submodule(refs->name, "%s", refname)
1327
+ : git_pathdup("%s", refname);
1328
+ fd = open(path, O_RDONLY);
1329
+ free(path);
1330
+ if (fd < 0)
1331
+ return resolve_gitlink_packed_ref(refs, refname, sha1);
1332
+
1333
+ len = read(fd, buffer, sizeof(buffer)-1);
1334
+ close(fd);
1335
+ if (len < 0)
1336
+ return -1;
1337
+ while (len && isspace(buffer[len-1]))
1338
+ len--;
1339
+ buffer[len] = 0;
1340
+
1341
+ /* Was it a detached head or an old-fashioned symlink? */
1342
+ if (!get_sha1_hex(buffer, sha1))
1343
+ return 0;
1344
+
1345
+ /* Symref? */
1346
+ if (strncmp(buffer, "ref:", 4))
1347
+ return -1;
1348
+ p = buffer + 4;
1349
+ while (isspace(*p))
1350
+ p++;
1351
+
1352
+ return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1353
+}
1354
+
1355
+int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1356
+{
1357
+ int len = strlen(path), retval;
1358
+ char *submodule;
1359
+ struct ref_cache *refs;
1360
+
1361
+ while (len && path[len-1] == '/')
1362
+ len--;
1363
+ if (!len)
1364
+ return -1;
1365
+ submodule = xstrndup(path, len);
1366
+ refs = get_ref_cache(submodule);
1367
+ free(submodule);
1368
+
1369
+ retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1370
+ return retval;
1371
+}
1372
+
1373
+/*
1374
+ * Return the ref_entry for the given refname from the packed
1375
+ * references. If it does not exist, return NULL.
1376
+ */
1377
+static struct ref_entry *get_packed_ref(const char *refname)
1378
+{
1379
+ return find_ref(get_packed_refs(&ref_cache), refname);
1380
+}
1381
+
1382
+/*
1383
+ * A loose ref file doesn't exist; check for a packed ref. The
1384
+ * options are forwarded from resolve_safe_unsafe().
1385
+ */
1386
+static int resolve_missing_loose_ref(const char *refname,
1387
+ int resolve_flags,
1388
+ unsigned char *sha1,
1389
+ int *flags)
1390
+{
1391
+ struct ref_entry *entry;
1392
+
1393
+ /*
1394
+ * The loose reference file does not exist; check for a packed
1395
+ * reference.
1396
+ */
1397
+ entry = get_packed_ref(refname);
1398
+ if (entry) {
1399
+ hashcpy(sha1, entry->u.value.oid.hash);
1400
+ if (flags)
1401
+ *flags |= REF_ISPACKED;
1402
+ return 0;
1403
+ }
1404
+ /* The reference is not a packed reference, either. */
1405
+ if (resolve_flags & RESOLVE_REF_READING) {
1406
+ errno = ENOENT;
1407
+ return -1;
1408
+ } else {
1409
+ hashclr(sha1);
1410
+ return 0;
1411
+ }
1412
+}
1413
+
1414
+/* This function needs to return a meaningful errno on failure */
1415
+static const char *resolve_ref_1(const char *refname,
1416
+ int resolve_flags,
1417
+ unsigned char *sha1,
1418
+ int *flags,
1419
+ struct strbuf *sb_refname,
1420
+ struct strbuf *sb_path,
1421
+ struct strbuf *sb_contents)
1422
+{
1423
+ int depth = MAXDEPTH;
1424
+ int bad_name = 0;
1425
+
1426
+ if (flags)
1427
+ *flags = 0;
1428
+
1429
+ if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1430
+ if (flags)
1431
+ *flags |= REF_BAD_NAME;
1432
+
1433
+ if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1434
+ !refname_is_safe(refname)) {
1435
+ errno = EINVAL;
1436
+ return NULL;
1437
+ }
1438
+ /*
1439
+ * dwim_ref() uses REF_ISBROKEN to distinguish between
1440
+ * missing refs and refs that were present but invalid,
1441
+ * to complain about the latter to stderr.
1442
+ *
1443
+ * We don't know whether the ref exists, so don't set
1444
+ * REF_ISBROKEN yet.
1445
+ */
1446
+ bad_name = 1;
1447
+ }
1448
+ for (;;) {
1449
+ const char *path;
1450
+ struct stat st;
1451
+ char *buf;
1452
+ int fd;
1453
+
1454
+ if (--depth < 0) {
1455
+ errno = ELOOP;
1456
+ return NULL;
1457
+ }
1458
+
1459
+ strbuf_reset(sb_path);
1460
+ strbuf_git_path(sb_path, "%s", refname);
1461
+ path = sb_path->buf;
1462
+
1463
+ /*
1464
+ * We might have to loop back here to avoid a race
1465
+ * condition: first we lstat() the file, then we try
1466
+ * to read it as a link or as a file. But if somebody
1467
+ * changes the type of the file (file <-> directory
1468
+ * <-> symlink) between the lstat() and reading, then
1469
+ * we don't want to report that as an error but rather
1470
+ * try again starting with the lstat().
1471
+ */
1472
+ stat_ref:
1473
+ if (lstat(path, &st) < 0) {
1474
+ if (errno != ENOENT)
1475
+ return NULL;
1476
+ if (resolve_missing_loose_ref(refname, resolve_flags,
1477
+ sha1, flags))
1478
+ return NULL;
1479
+ if (bad_name) {
1480
+ hashclr(sha1);
1481
+ if (flags)
1482
+ *flags |= REF_ISBROKEN;
1483
+ }
1484
+ return refname;
1485
+ }
1486
+
1487
+ /* Follow "normalized" - ie "refs/.." symlinks by hand */
1488
+ if (S_ISLNK(st.st_mode)) {
1489
+ strbuf_reset(sb_contents);
1490
+ if (strbuf_readlink(sb_contents, path, 0) < 0) {
1491
+ if (errno == ENOENT || errno == EINVAL)
1492
+ /* inconsistent with lstat; retry */
1493
+ goto stat_ref;
1494
+ else
1495
+ return NULL;
1496
+ }
1497
+ if (starts_with(sb_contents->buf, "refs/") &&
1498
+ !check_refname_format(sb_contents->buf, 0)) {
1499
+ strbuf_swap(sb_refname, sb_contents);
1500
+ refname = sb_refname->buf;
1501
+ if (flags)
1502
+ *flags |= REF_ISSYMREF;
1503
+ if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1504
+ hashclr(sha1);
1505
+ return refname;
1506
+ }
1507
+ continue;
1508
+ }
1509
+ }
1510
+
1511
+ /* Is it a directory? */
1512
+ if (S_ISDIR(st.st_mode)) {
1513
+ errno = EISDIR;
1514
+ return NULL;
1515
+ }
1516
+
1517
+ /*
1518
+ * Anything else, just open it and try to use it as
1519
+ * a ref
1520
+ */
1521
+ fd = open(path, O_RDONLY);
1522
+ if (fd < 0) {
1523
+ if (errno == ENOENT)
1524
+ /* inconsistent with lstat; retry */
1525
+ goto stat_ref;
1526
+ else
1527
+ return NULL;
1528
+ }
1529
+ strbuf_reset(sb_contents);
1530
+ if (strbuf_read(sb_contents, fd, 256) < 0) {
1531
+ int save_errno = errno;
1532
+ close(fd);
1533
+ errno = save_errno;
1534
+ return NULL;
1535
+ }
1536
+ close(fd);
1537
+ strbuf_rtrim(sb_contents);
1538
+
1539
+ /*
1540
+ * Is it a symbolic ref?
1541
+ */
1542
+ if (!starts_with(sb_contents->buf, "ref:")) {
1543
+ /*
1544
+ * Please note that FETCH_HEAD has a second
1545
+ * line containing other data.
1546
+ */
1547
+ if (get_sha1_hex(sb_contents->buf, sha1) ||
1548
+ (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1549
+ if (flags)
1550
+ *flags |= REF_ISBROKEN;
1551
+ errno = EINVAL;
1552
+ return NULL;
1553
+ }
1554
+ if (bad_name) {
1555
+ hashclr(sha1);
1556
+ if (flags)
1557
+ *flags |= REF_ISBROKEN;
1558
+ }
1559
+ return refname;
1560
+ }
1561
+ if (flags)
1562
+ *flags |= REF_ISSYMREF;
1563
+ buf = sb_contents->buf + 4;
1564
+ while (isspace(*buf))
1565
+ buf++;
1566
+ strbuf_reset(sb_refname);
1567
+ strbuf_addstr(sb_refname, buf);
1568
+ refname = sb_refname->buf;
1569
+ if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1570
+ hashclr(sha1);
1571
+ return refname;
1572
+ }
1573
+ if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1574
+ if (flags)
1575
+ *flags |= REF_ISBROKEN;
1576
+
1577
+ if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1578
+ !refname_is_safe(buf)) {
1579
+ errno = EINVAL;
1580
+ return NULL;
1581
+ }
1582
+ bad_name = 1;
1583
+ }
1584
+ }
1585
+}
1586
+
1587
+const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1588
+ unsigned char *sha1, int *flags)
1589
+{
1590
+ static struct strbuf sb_refname = STRBUF_INIT;
1591
+ struct strbuf sb_contents = STRBUF_INIT;
1592
+ struct strbuf sb_path = STRBUF_INIT;
1593
+ const char *ret;
1594
+
1595
+ ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1596
+ &sb_refname, &sb_path, &sb_contents);
1597
+ strbuf_release(&sb_path);
1598
+ strbuf_release(&sb_contents);
1599
+ return ret;
1600
+}
1601
+
1602
+/*
1603
+ * Peel the entry (if possible) and return its new peel_status. If
1604
+ * repeel is true, re-peel the entry even if there is an old peeled
1605
+ * value that is already stored in it.
1606
+ *
1607
+ * It is OK to call this function with a packed reference entry that
1608
+ * might be stale and might even refer to an object that has since
1609
+ * been garbage-collected. In such a case, if the entry has
1610
+ * REF_KNOWS_PEELED then leave the status unchanged and return
1611
+ * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1612
+ */
1613
+static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1614
+{
1615
+ enum peel_status status;
1616
+
1617
+ if (entry->flag & REF_KNOWS_PEELED) {
1618
+ if (repeel) {
1619
+ entry->flag &= ~REF_KNOWS_PEELED;
1620
+ oidclr(&entry->u.value.peeled);
1621
+ } else {
1622
+ return is_null_oid(&entry->u.value.peeled) ?
1623
+ PEEL_NON_TAG : PEEL_PEELED;
1624
+ }
1625
+ }
1626
+ if (entry->flag & REF_ISBROKEN)
1627
+ return PEEL_BROKEN;
1628
+ if (entry->flag & REF_ISSYMREF)
1629
+ return PEEL_IS_SYMREF;
1630
+
1631
+ status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1632
+ if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1633
+ entry->flag |= REF_KNOWS_PEELED;
1634
+ return status;
1635
+}
1636
+
1637
+int peel_ref(const char *refname, unsigned char *sha1)
1638
+{
1639
+ int flag;
1640
+ unsigned char base[20];
1641
+
1642
+ if (current_ref && (current_ref->name == refname
1643
+ || !strcmp(current_ref->name, refname))) {
1644
+ if (peel_entry(current_ref, 0))
1645
+ return -1;
1646
+ hashcpy(sha1, current_ref->u.value.peeled.hash);
1647
+ return 0;
1648
+ }
1649
+
1650
+ if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1651
+ return -1;
1652
+
1653
+ /*
1654
+ * If the reference is packed, read its ref_entry from the
1655
+ * cache in the hope that we already know its peeled value.
1656
+ * We only try this optimization on packed references because
1657
+ * (a) forcing the filling of the loose reference cache could
1658
+ * be expensive and (b) loose references anyway usually do not
1659
+ * have REF_KNOWS_PEELED.
1660
+ */
1661
+ if (flag & REF_ISPACKED) {
1662
+ struct ref_entry *r = get_packed_ref(refname);
1663
+ if (r) {
1664
+ if (peel_entry(r, 0))
1665
+ return -1;
1666
+ hashcpy(sha1, r->u.value.peeled.hash);
1667
+ return 0;
1668
+ }
1669
+ }
1670
+
1671
+ return peel_object(base, sha1);
1672
+}
1673
+
1674
+/*
1675
+ * Call fn for each reference in the specified ref_cache, omitting
1676
+ * references not in the containing_dir of base. fn is called for all
1677
+ * references, including broken ones. If fn ever returns a non-zero
1678
+ * value, stop the iteration and return that value; otherwise, return
1679
+ * 0.
1680
+ */
1681
+static int do_for_each_entry(struct ref_cache *refs, const char *base,
1682
+ each_ref_entry_fn fn, void *cb_data)
1683
+{
1684
+ struct packed_ref_cache *packed_ref_cache;
1685
+ struct ref_dir *loose_dir;
1686
+ struct ref_dir *packed_dir;
1687
+ int retval = 0;
1688
+
1689
+ /*
1690
+ * We must make sure that all loose refs are read before accessing the
1691
+ * packed-refs file; this avoids a race condition in which loose refs
1692
+ * are migrated to the packed-refs file by a simultaneous process, but
1693
+ * our in-memory view is from before the migration. get_packed_ref_cache()
1694
+ * takes care of making sure our view is up to date with what is on
1695
+ * disk.
1696
+ */
1697
+ loose_dir = get_loose_refs(refs);
1698
+ if (base && *base) {
1699
+ loose_dir = find_containing_dir(loose_dir, base, 0);
1700
+ }
1701
+ if (loose_dir)
1702
+ prime_ref_dir(loose_dir);
1703
+
1704
+ packed_ref_cache = get_packed_ref_cache(refs);
1705
+ acquire_packed_ref_cache(packed_ref_cache);
1706
+ packed_dir = get_packed_ref_dir(packed_ref_cache);
1707
+ if (base && *base) {
1708
+ packed_dir = find_containing_dir(packed_dir, base, 0);
1709
+ }
1710
+
1711
+ if (packed_dir && loose_dir) {
1712
+ sort_ref_dir(packed_dir);
1713
+ sort_ref_dir(loose_dir);
1714
+ retval = do_for_each_entry_in_dirs(
1715
+ packed_dir, loose_dir, fn, cb_data);
1716
+ } else if (packed_dir) {
1717
+ sort_ref_dir(packed_dir);
1718
+ retval = do_for_each_entry_in_dir(
1719
+ packed_dir, 0, fn, cb_data);
1720
+ } else if (loose_dir) {
1721
+ sort_ref_dir(loose_dir);
1722
+ retval = do_for_each_entry_in_dir(
1723
+ loose_dir, 0, fn, cb_data);
1724
+ }
1725
+
1726
+ release_packed_ref_cache(packed_ref_cache);
1727
+ return retval;
1728
+}
1729
+
1730
+/*
1731
+ * Call fn for each reference in the specified ref_cache for which the
1732
+ * refname begins with base. If trim is non-zero, then trim that many
1733
+ * characters off the beginning of each refname before passing the
1734
+ * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1735
+ * broken references in the iteration. If fn ever returns a non-zero
1736
+ * value, stop the iteration and return that value; otherwise, return
1737
+ * 0.
1738
+ */
1739
+static int do_for_each_ref(struct ref_cache *refs, const char *base,
1740
+ each_ref_fn fn, int trim, int flags, void *cb_data)
1741
+{
1742
+ struct ref_entry_cb data;
1743
+ data.base = base;
1744
+ data.trim = trim;
1745
+ data.flags = flags;
1746
+ data.fn = fn;
1747
+ data.cb_data = cb_data;
1748
+
1749
+ if (ref_paranoia < 0)
1750
+ ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1751
+ if (ref_paranoia)
1752
+ data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1753
+
1754
+ return do_for_each_entry(refs, base, do_one_ref, &data);
1755
+}
1756
+
1757
+static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1758
+{
1759
+ struct object_id oid;
1760
+ int flag;
1761
+
1762
+ if (submodule) {
1763
+ if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1764
+ return fn("HEAD", &oid, 0, cb_data);
1765
+
1766
+ return 0;
1767
+ }
1768
+
1769
+ if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1770
+ return fn("HEAD", &oid, flag, cb_data);
1771
+
1772
+ return 0;
1773
+}
1774
+
1775
+int head_ref(each_ref_fn fn, void *cb_data)
1776
+{
1777
+ return do_head_ref(NULL, fn, cb_data);
1778
+}
1779
+
1780
+int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1781
+{
1782
+ return do_head_ref(submodule, fn, cb_data);
1783
+}
1784
+
1785
+int for_each_ref(each_ref_fn fn, void *cb_data)
1786
+{
1787
+ return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1788
+}
1789
+
1790
+int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1791
+{
1792
+ return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1793
+}
1794
+
1795
+int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1796
+{
1797
+ return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1798
+}
1799
+
1800
+int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1801
+{
1802
+ unsigned int flag = 0;
1803
+
1804
+ if (broken)
1805
+ flag = DO_FOR_EACH_INCLUDE_BROKEN;
1806
+ return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
1807
+}
1808
+
1809
+int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1810
+ each_ref_fn fn, void *cb_data)
1811
+{
1812
+ return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1813
+}
1814
+
1815
+int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1816
+{
1817
+ return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
1818
+ strlen(git_replace_ref_base), 0, cb_data);
1819
+}
1820
+
1821
+int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1822
+{
1823
+ struct strbuf buf = STRBUF_INIT;
1824
+ int ret;
1825
+ strbuf_addf(&buf, "%srefs/", get_git_namespace());
1826
+ ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1827
+ strbuf_release(&buf);
1828
+ return ret;
1829
+}
1830
+
1831
+int for_each_rawref(each_ref_fn fn, void *cb_data)
1832
+{
1833
+ return do_for_each_ref(&ref_cache, "", fn, 0,
1834
+ DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1835
+}
1836
+
1837
+static void unlock_ref(struct ref_lock *lock)
1838
+{
1839
+ /* Do not free lock->lk -- atexit() still looks at them */
1840
+ if (lock->lk)
1841
+ rollback_lock_file(lock->lk);
1842
+ free(lock->ref_name);
1843
+ free(lock->orig_ref_name);
1844
+ free(lock);
1845
+}
1846
+
1847
+/*
1848
+ * Verify that the reference locked by lock has the value old_sha1.
1849
+ * Fail if the reference doesn't exist and mustexist is set. Return 0
1850
+ * on success. On error, write an error message to err, set errno, and
1851
+ * return a negative value.
1852
+ */
1853
+static int verify_lock(struct ref_lock *lock,
1854
+ const unsigned char *old_sha1, int mustexist,
1855
+ struct strbuf *err)
1856
+{
1857
+ assert(err);
1858
+
1859
+ if (read_ref_full(lock->ref_name,
1860
+ mustexist ? RESOLVE_REF_READING : 0,
1861
+ lock->old_oid.hash, NULL)) {
1862
+ int save_errno = errno;
1863
+ strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1864
+ errno = save_errno;
1865
+ return -1;
1866
+ }
1867
+ if (hashcmp(lock->old_oid.hash, old_sha1)) {
1868
+ strbuf_addf(err, "ref %s is at %s but expected %s",
1869
+ lock->ref_name,
1870
+ sha1_to_hex(lock->old_oid.hash),
1871
+ sha1_to_hex(old_sha1));
1872
+ errno = EBUSY;
1873
+ return -1;
1874
+ }
1875
+ return 0;
1876
+}
1877
+
1878
+static int remove_empty_directories(struct strbuf *path)
1879
+{
1880
+ /*
1881
+ * we want to create a file but there is a directory there;
1882
+ * if that is an empty directory (or a directory that contains
1883
+ * only empty directories), remove them.
1884
+ */
1885
+ return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1886
+}
1887
+
1888
+/*
1889
+ * Locks a ref returning the lock on success and NULL on failure.
1890
+ * On failure errno is set to something meaningful.
1891
+ */
1892
+static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1893
+ const unsigned char *old_sha1,
1894
+ const struct string_list *extras,
1895
+ const struct string_list *skip,
1896
+ unsigned int flags, int *type_p,
1897
+ struct strbuf *err)
1898
+{
1899
+ struct strbuf ref_file = STRBUF_INIT;
1900
+ struct strbuf orig_ref_file = STRBUF_INIT;
1901
+ const char *orig_refname = refname;
1902
+ struct ref_lock *lock;
1903
+ int last_errno = 0;
1904
+ int type, lflags;
1905
+ int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1906
+ int resolve_flags = 0;
1907
+ int attempts_remaining = 3;
1908
+
1909
+ assert(err);
1910
+
1911
+ lock = xcalloc(1, sizeof(struct ref_lock));
1912
+
1913
+ if (mustexist)
1914
+ resolve_flags |= RESOLVE_REF_READING;
1915
+ if (flags & REF_DELETING) {
1916
+ resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1917
+ if (flags & REF_NODEREF)
1918
+ resolve_flags |= RESOLVE_REF_NO_RECURSE;
1919
+ }
1920
+
1921
+ refname = resolve_ref_unsafe(refname, resolve_flags,
1922
+ lock->old_oid.hash, &type);
1923
+ if (!refname && errno == EISDIR) {
1924
+ /*
1925
+ * we are trying to lock foo but we used to
1926
+ * have foo/bar which now does not exist;
1927
+ * it is normal for the empty directory 'foo'
1928
+ * to remain.
1929
+ */
1930
+ strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1931
+ if (remove_empty_directories(&orig_ref_file)) {
1932
+ last_errno = errno;
1933
+ if (!verify_refname_available_dir(orig_refname, extras, skip,
1934
+ get_loose_refs(&ref_cache), err))
1935
+ strbuf_addf(err, "there are still refs under '%s'",
1936
+ orig_refname);
1937
+ goto error_return;
1938
+ }
1939
+ refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1940
+ lock->old_oid.hash, &type);
1941
+ }
1942
+ if (type_p)
1943
+ *type_p = type;
1944
+ if (!refname) {
1945
+ last_errno = errno;
1946
+ if (last_errno != ENOTDIR ||
1947
+ !verify_refname_available_dir(orig_refname, extras, skip,
1948
+ get_loose_refs(&ref_cache), err))
1949
+ strbuf_addf(err, "unable to resolve reference %s: %s",
1950
+ orig_refname, strerror(last_errno));
1951
+
1952
+ goto error_return;
1953
+ }
1954
+ /*
1955
+ * If the ref did not exist and we are creating it, make sure
1956
+ * there is no existing packed ref whose name begins with our
1957
+ * refname, nor a packed ref whose name is a proper prefix of
1958
+ * our refname.
1959
+ */
1960
+ if (is_null_oid(&lock->old_oid) &&
1961
+ verify_refname_available_dir(refname, extras, skip,
1962
+ get_packed_refs(&ref_cache), err)) {
1963
+ last_errno = ENOTDIR;
1964
+ goto error_return;
1965
+ }
1966
+
1967
+ lock->lk = xcalloc(1, sizeof(struct lock_file));
1968
+
1969
+ lflags = 0;
1970
+ if (flags & REF_NODEREF) {
1971
+ refname = orig_refname;
1972
+ lflags |= LOCK_NO_DEREF;
1973
+ }
1974
+ lock->ref_name = xstrdup(refname);
1975
+ lock->orig_ref_name = xstrdup(orig_refname);
1976
+ strbuf_git_path(&ref_file, "%s", refname);
1977
+
1978
+ retry:
1979
+ switch (safe_create_leading_directories_const(ref_file.buf)) {
1980
+ case SCLD_OK:
1981
+ break; /* success */
1982
+ case SCLD_VANISHED:
1983
+ if (--attempts_remaining > 0)
1984
+ goto retry;
1985
+ /* fall through */
1986
+ default:
1987
+ last_errno = errno;
1988
+ strbuf_addf(err, "unable to create directory for %s",
1989
+ ref_file.buf);
1990
+ goto error_return;
1991
+ }
1992
+
1993
+ if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1994
+ last_errno = errno;
1995
+ if (errno == ENOENT && --attempts_remaining > 0)
1996
+ /*
1997
+ * Maybe somebody just deleted one of the
1998
+ * directories leading to ref_file. Try
1999
+ * again:
2000
+ */
2001
+ goto retry;
2002
+ else {
2003
+ unable_to_lock_message(ref_file.buf, errno, err);
2004
+ goto error_return;
2005
+ }
2006
+ }
2007
+ if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2008
+ last_errno = errno;
2009
+ goto error_return;
2010
+ }
2011
+ goto out;
2012
+
2013
+ error_return:
2014
+ unlock_ref(lock);
2015
+ lock = NULL;
2016
+
2017
+ out:
2018
+ strbuf_release(&ref_file);
2019
+ strbuf_release(&orig_ref_file);
2020
+ errno = last_errno;
2021
+ return lock;
2022
+}
2023
+
2024
+/*
2025
+ * Write an entry to the packed-refs file for the specified refname.
2026
+ * If peeled is non-NULL, write it as the entry's peeled value.
2027
+ */
2028
+static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2029
+ unsigned char *peeled)
2030
+{
2031
+ fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2032
+ if (peeled)
2033
+ fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2034
+}
2035
+
2036
+/*
2037
+ * An each_ref_entry_fn that writes the entry to a packed-refs file.
2038
+ */
2039
+static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2040
+{
2041
+ enum peel_status peel_status = peel_entry(entry, 0);
2042
+
2043
+ if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2044
+ error("internal error: %s is not a valid packed reference!",
2045
+ entry->name);
2046
+ write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2047
+ peel_status == PEEL_PEELED ?
2048
+ entry->u.value.peeled.hash : NULL);
2049
+ return 0;
2050
+}
2051
+
2052
+/*
2053
+ * Lock the packed-refs file for writing. Flags is passed to
2054
+ * hold_lock_file_for_update(). Return 0 on success. On errors, set
2055
+ * errno appropriately and return a nonzero value.
2056
+ */
2057
+static int lock_packed_refs(int flags)
2058
+{
2059
+ static int timeout_configured = 0;
2060
+ static int timeout_value = 1000;
2061
+
2062
+ struct packed_ref_cache *packed_ref_cache;
2063
+
2064
+ if (!timeout_configured) {
2065
+ git_config_get_int("core.packedrefstimeout", &timeout_value);
2066
+ timeout_configured = 1;
2067
+ }
2068
+
2069
+ if (hold_lock_file_for_update_timeout(
2070
+ &packlock, git_path("packed-refs"),
2071
+ flags, timeout_value) < 0)
2072
+ return -1;
2073
+ /*
2074
+ * Get the current packed-refs while holding the lock. If the
2075
+ * packed-refs file has been modified since we last read it,
2076
+ * this will automatically invalidate the cache and re-read
2077
+ * the packed-refs file.
2078
+ */
2079
+ packed_ref_cache = get_packed_ref_cache(&ref_cache);
2080
+ packed_ref_cache->lock = &packlock;
2081
+ /* Increment the reference count to prevent it from being freed: */
2082
+ acquire_packed_ref_cache(packed_ref_cache);
2083
+ return 0;
2084
+}
2085
+
2086
+/*
2087
+ * Write the current version of the packed refs cache from memory to
2088
+ * disk. The packed-refs file must already be locked for writing (see
2089
+ * lock_packed_refs()). Return zero on success. On errors, set errno
2090
+ * and return a nonzero value
2091
+ */
2092
+static int commit_packed_refs(void)
2093
+{
2094
+ struct packed_ref_cache *packed_ref_cache =
2095
+ get_packed_ref_cache(&ref_cache);
2096
+ int error = 0;
2097
+ int save_errno = 0;
2098
+ FILE *out;
2099
+
2100
+ if (!packed_ref_cache->lock)
2101
+ die("internal error: packed-refs not locked");
2102
+
2103
+ out = fdopen_lock_file(packed_ref_cache->lock, "w");
2104
+ if (!out)
2105
+ die_errno("unable to fdopen packed-refs descriptor");
2106
+
2107
+ fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2108
+ do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2109
+ 0, write_packed_entry_fn, out);
2110
+
2111
+ if (commit_lock_file(packed_ref_cache->lock)) {
2112
+ save_errno = errno;
2113
+ error = -1;
2114
+ }
2115
+ packed_ref_cache->lock = NULL;
2116
+ release_packed_ref_cache(packed_ref_cache);
2117
+ errno = save_errno;
2118
+ return error;
2119
+}
2120
+
2121
+/*
2122
+ * Rollback the lockfile for the packed-refs file, and discard the
2123
+ * in-memory packed reference cache. (The packed-refs file will be
2124
+ * read anew if it is needed again after this function is called.)
2125
+ */
2126
+static void rollback_packed_refs(void)
2127
+{
2128
+ struct packed_ref_cache *packed_ref_cache =
2129
+ get_packed_ref_cache(&ref_cache);
2130
+
2131
+ if (!packed_ref_cache->lock)
2132
+ die("internal error: packed-refs not locked");
2133
+ rollback_lock_file(packed_ref_cache->lock);
2134
+ packed_ref_cache->lock = NULL;
2135
+ release_packed_ref_cache(packed_ref_cache);
2136
+ clear_packed_ref_cache(&ref_cache);
2137
+}
2138
+
2139
+struct ref_to_prune {
2140
+ struct ref_to_prune *next;
2141
+ unsigned char sha1[20];
2142
+ char name[FLEX_ARRAY];
2143
+};
2144
+
2145
+struct pack_refs_cb_data {
2146
+ unsigned int flags;
2147
+ struct ref_dir *packed_refs;
2148
+ struct ref_to_prune *ref_to_prune;
2149
+};
2150
+
2151
+/*
2152
+ * An each_ref_entry_fn that is run over loose references only. If
2153
+ * the loose reference can be packed, add an entry in the packed ref
2154
+ * cache. If the reference should be pruned, also add it to
2155
+ * ref_to_prune in the pack_refs_cb_data.
2156
+ */
2157
+static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2158
+{
2159
+ struct pack_refs_cb_data *cb = cb_data;
2160
+ enum peel_status peel_status;
2161
+ struct ref_entry *packed_entry;
2162
+ int is_tag_ref = starts_with(entry->name, "refs/tags/");
2163
+
2164
+ /* Do not pack per-worktree refs: */
2165
+ if (ref_type(entry->name) != REF_TYPE_NORMAL)
2166
+ return 0;
2167
+
2168
+ /* ALWAYS pack tags */
2169
+ if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2170
+ return 0;
2171
+
2172
+ /* Do not pack symbolic or broken refs: */
2173
+ if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2174
+ return 0;
2175
+
2176
+ /* Add a packed ref cache entry equivalent to the loose entry. */
2177
+ peel_status = peel_entry(entry, 1);
2178
+ if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2179
+ die("internal error peeling reference %s (%s)",
2180
+ entry->name, oid_to_hex(&entry->u.value.oid));
2181
+ packed_entry = find_ref(cb->packed_refs, entry->name);
2182
+ if (packed_entry) {
2183
+ /* Overwrite existing packed entry with info from loose entry */
2184
+ packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2185
+ oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2186
+ } else {
2187
+ packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2188
+ REF_ISPACKED | REF_KNOWS_PEELED, 0);
2189
+ add_ref(cb->packed_refs, packed_entry);
2190
+ }
2191
+ oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2192
+
2193
+ /* Schedule the loose reference for pruning if requested. */
2194
+ if ((cb->flags & PACK_REFS_PRUNE)) {
2195
+ int namelen = strlen(entry->name) + 1;
2196
+ struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2197
+ hashcpy(n->sha1, entry->u.value.oid.hash);
2198
+ memcpy(n->name, entry->name, namelen); /* includes NUL */
2199
+ n->next = cb->ref_to_prune;
2200
+ cb->ref_to_prune = n;
2201
+ }
2202
+ return 0;
2203
+}
2204
+
2205
+/*
2206
+ * Remove empty parents, but spare refs/ and immediate subdirs.
2207
+ * Note: munges *name.
2208
+ */
2209
+static void try_remove_empty_parents(char *name)
2210
+{
2211
+ char *p, *q;
2212
+ int i;
2213
+ p = name;
2214
+ for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2215
+ while (*p && *p != '/')
2216
+ p++;
2217
+ /* tolerate duplicate slashes; see check_refname_format() */
2218
+ while (*p == '/')
2219
+ p++;
2220
+ }
2221
+ for (q = p; *q; q++)
2222
+ ;
2223
+ while (1) {
2224
+ while (q > p && *q != '/')
2225
+ q--;
2226
+ while (q > p && *(q-1) == '/')
2227
+ q--;
2228
+ if (q == p)
2229
+ break;
2230
+ *q = '\0';
2231
+ if (rmdir(git_path("%s", name)))
2232
+ break;
2233
+ }
2234
+}
2235
+
2236
+/* make sure nobody touched the ref, and unlink */
2237
+static void prune_ref(struct ref_to_prune *r)
2238
+{
2239
+ struct ref_transaction *transaction;
2240
+ struct strbuf err = STRBUF_INIT;
2241
+
2242
+ if (check_refname_format(r->name, 0))
2243
+ return;
2244
+
2245
+ transaction = ref_transaction_begin(&err);
2246
+ if (!transaction ||
2247
+ ref_transaction_delete(transaction, r->name, r->sha1,
2248
+ REF_ISPRUNING, NULL, &err) ||
2249
+ ref_transaction_commit(transaction, &err)) {
2250
+ ref_transaction_free(transaction);
2251
+ error("%s", err.buf);
2252
+ strbuf_release(&err);
2253
+ return;
2254
+ }
2255
+ ref_transaction_free(transaction);
2256
+ strbuf_release(&err);
2257
+ try_remove_empty_parents(r->name);
2258
+}
2259
+
2260
+static void prune_refs(struct ref_to_prune *r)
2261
+{
2262
+ while (r) {
2263
+ prune_ref(r);
2264
+ r = r->next;
2265
+ }
2266
+}
2267
+
2268
+int pack_refs(unsigned int flags)
2269
+{
2270
+ struct pack_refs_cb_data cbdata;
2271
+
2272
+ memset(&cbdata, 0, sizeof(cbdata));
2273
+ cbdata.flags = flags;
2274
+
2275
+ lock_packed_refs(LOCK_DIE_ON_ERROR);
2276
+ cbdata.packed_refs = get_packed_refs(&ref_cache);
2277
+
2278
+ do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2279
+ pack_if_possible_fn, &cbdata);
2280
+
2281
+ if (commit_packed_refs())
2282
+ die_errno("unable to overwrite old ref-pack file");
2283
+
2284
+ prune_refs(cbdata.ref_to_prune);
2285
+ return 0;
2286
+}
2287
+
2288
+/*
2289
+ * Rewrite the packed-refs file, omitting any refs listed in
2290
+ * 'refnames'. On error, leave packed-refs unchanged, write an error
2291
+ * message to 'err', and return a nonzero value.
2292
+ *
2293
+ * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2294
+ */
2295
+static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2296
+{
2297
+ struct ref_dir *packed;
2298
+ struct string_list_item *refname;
2299
+ int ret, needs_repacking = 0, removed = 0;
2300
+
2301
+ assert(err);
2302
+
2303
+ /* Look for a packed ref */
2304
+ for_each_string_list_item(refname, refnames) {
2305
+ if (get_packed_ref(refname->string)) {
2306
+ needs_repacking = 1;
2307
+ break;
2308
+ }
2309
+ }
2310
+
2311
+ /* Avoid locking if we have nothing to do */
2312
+ if (!needs_repacking)
2313
+ return 0; /* no refname exists in packed refs */
2314
+
2315
+ if (lock_packed_refs(0)) {
2316
+ unable_to_lock_message(git_path("packed-refs"), errno, err);
2317
+ return -1;
2318
+ }
2319
+ packed = get_packed_refs(&ref_cache);
2320
+
2321
+ /* Remove refnames from the cache */
2322
+ for_each_string_list_item(refname, refnames)
2323
+ if (remove_entry(packed, refname->string) != -1)
2324
+ removed = 1;
2325
+ if (!removed) {
2326
+ /*
2327
+ * All packed entries disappeared while we were
2328
+ * acquiring the lock.
2329
+ */
2330
+ rollback_packed_refs();
2331
+ return 0;
2332
+ }
2333
+
2334
+ /* Write what remains */
2335
+ ret = commit_packed_refs();
2336
+ if (ret)
2337
+ strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2338
+ strerror(errno));
2339
+ return ret;
2340
+}
2341
+
2342
+static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2343
+{
2344
+ assert(err);
2345
+
2346
+ if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2347
+ /*
2348
+ * loose. The loose file name is the same as the
2349
+ * lockfile name, minus ".lock":
2350
+ */
2351
+ char *loose_filename = get_locked_file_path(lock->lk);
2352
+ int res = unlink_or_msg(loose_filename, err);
2353
+ free(loose_filename);
2354
+ if (res)
2355
+ return 1;
2356
+ }
2357
+ return 0;
2358
+}
2359
+
2360
+int delete_refs(struct string_list *refnames)
2361
+{
2362
+ struct strbuf err = STRBUF_INIT;
2363
+ int i, result = 0;
2364
+
2365
+ if (!refnames->nr)
2366
+ return 0;
2367
+
2368
+ result = repack_without_refs(refnames, &err);
2369
+ if (result) {
2370
+ /*
2371
+ * If we failed to rewrite the packed-refs file, then
2372
+ * it is unsafe to try to remove loose refs, because
2373
+ * doing so might expose an obsolete packed value for
2374
+ * a reference that might even point at an object that
2375
+ * has been garbage collected.
2376
+ */
2377
+ if (refnames->nr == 1)
2378
+ error(_("could not delete reference %s: %s"),
2379
+ refnames->items[0].string, err.buf);
2380
+ else
2381
+ error(_("could not delete references: %s"), err.buf);
2382
+
2383
+ goto out;
2384
+ }
2385
+
2386
+ for (i = 0; i < refnames->nr; i++) {
2387
+ const char *refname = refnames->items[i].string;
2388
+
2389
+ if (delete_ref(refname, NULL, 0))
2390
+ result |= error(_("could not remove reference %s"), refname);
2391
+ }
2392
+
2393
+out:
2394
+ strbuf_release(&err);
2395
+ return result;
2396
+}
2397
+
2398
+/*
2399
+ * People using contrib's git-new-workdir have .git/logs/refs ->
2400
+ * /some/other/path/.git/logs/refs, and that may live on another device.
2401
+ *
2402
+ * IOW, to avoid cross device rename errors, the temporary renamed log must
2403
+ * live into logs/refs.
2404
+ */
2405
+#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2406
+
2407
+static int rename_tmp_log(const char *newrefname)
2408
+{
2409
+ int attempts_remaining = 4;
2410
+ struct strbuf path = STRBUF_INIT;
2411
+ int ret = -1;
2412
+
2413
+ retry:
2414
+ strbuf_reset(&path);
2415
+ strbuf_git_path(&path, "logs/%s", newrefname);
2416
+ switch (safe_create_leading_directories_const(path.buf)) {
2417
+ case SCLD_OK:
2418
+ break; /* success */
2419
+ case SCLD_VANISHED:
2420
+ if (--attempts_remaining > 0)
2421
+ goto retry;
2422
+ /* fall through */
2423
+ default:
2424
+ error("unable to create directory for %s", newrefname);
2425
+ goto out;
2426
+ }
2427
+
2428
+ if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2429
+ if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2430
+ /*
2431
+ * rename(a, b) when b is an existing
2432
+ * directory ought to result in ISDIR, but
2433
+ * Solaris 5.8 gives ENOTDIR. Sheesh.
2434
+ */
2435
+ if (remove_empty_directories(&path)) {
2436
+ error("Directory not empty: logs/%s", newrefname);
2437
+ goto out;
2438
+ }
2439
+ goto retry;
2440
+ } else if (errno == ENOENT && --attempts_remaining > 0) {
2441
+ /*
2442
+ * Maybe another process just deleted one of
2443
+ * the directories in the path to newrefname.
2444
+ * Try again from the beginning.
2445
+ */
2446
+ goto retry;
2447
+ } else {
2448
+ error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2449
+ newrefname, strerror(errno));
2450
+ goto out;
2451
+ }
2452
+ }
2453
+ ret = 0;
2454
+out:
2455
+ strbuf_release(&path);
2456
+ return ret;
2457
+}
2458
+
2459
+int verify_refname_available(const char *newname,
2460
+ struct string_list *extras,
2461
+ struct string_list *skip,
2462
+ struct strbuf *err)
2463
+{
2464
+ struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2465
+ struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2466
+
2467
+ if (verify_refname_available_dir(newname, extras, skip,
2468
+ packed_refs, err) ||
2469
+ verify_refname_available_dir(newname, extras, skip,
2470
+ loose_refs, err))
2471
+ return -1;
2472
+
2473
+ return 0;
2474
+}
2475
+
2476
+static int rename_ref_available(const char *oldname, const char *newname)
2477
+{
2478
+ struct string_list skip = STRING_LIST_INIT_NODUP;
2479
+ struct strbuf err = STRBUF_INIT;
2480
+ int ret;
2481
+
2482
+ string_list_insert(&skip, oldname);
2483
+ ret = !verify_refname_available(newname, NULL, &skip, &err);
2484
+ if (!ret)
2485
+ error("%s", err.buf);
2486
+
2487
+ string_list_clear(&skip, 0);
2488
+ strbuf_release(&err);
2489
+ return ret;
2490
+}
2491
+
2492
+static int write_ref_to_lockfile(struct ref_lock *lock,
2493
+ const unsigned char *sha1, struct strbuf *err);
2494
+static int commit_ref_update(struct ref_lock *lock,
2495
+ const unsigned char *sha1, const char *logmsg,
2496
+ int flags, struct strbuf *err);
2497
+
2498
+int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2499
+{
2500
+ unsigned char sha1[20], orig_sha1[20];
2501
+ int flag = 0, logmoved = 0;
2502
+ struct ref_lock *lock;
2503
+ struct stat loginfo;
2504
+ int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2505
+ const char *symref = NULL;
2506
+ struct strbuf err = STRBUF_INIT;
2507
+
2508
+ if (log && S_ISLNK(loginfo.st_mode))
2509
+ return error("reflog for %s is a symlink", oldrefname);
2510
+
2511
+ symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2512
+ orig_sha1, &flag);
2513
+ if (flag & REF_ISSYMREF)
2514
+ return error("refname %s is a symbolic ref, renaming it is not supported",
2515
+ oldrefname);
2516
+ if (!symref)
2517
+ return error("refname %s not found", oldrefname);
2518
+
2519
+ if (!rename_ref_available(oldrefname, newrefname))
2520
+ return 1;
2521
+
2522
+ if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2523
+ return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2524
+ oldrefname, strerror(errno));
2525
+
2526
+ if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2527
+ error("unable to delete old %s", oldrefname);
2528
+ goto rollback;
2529
+ }
2530
+
2531
+ if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2532
+ delete_ref(newrefname, sha1, REF_NODEREF)) {
2533
+ if (errno==EISDIR) {
2534
+ struct strbuf path = STRBUF_INIT;
2535
+ int result;
2536
+
2537
+ strbuf_git_path(&path, "%s", newrefname);
2538
+ result = remove_empty_directories(&path);
2539
+ strbuf_release(&path);
2540
+
2541
+ if (result) {
2542
+ error("Directory not empty: %s", newrefname);
2543
+ goto rollback;
2544
+ }
2545
+ } else {
2546
+ error("unable to delete existing %s", newrefname);
2547
+ goto rollback;
2548
+ }
2549
+ }
2550
+
2551
+ if (log && rename_tmp_log(newrefname))
2552
+ goto rollback;
2553
+
2554
+ logmoved = log;
2555
+
2556
+ lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2557
+ if (!lock) {
2558
+ error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2559
+ strbuf_release(&err);
2560
+ goto rollback;
2561
+ }
2562
+ hashcpy(lock->old_oid.hash, orig_sha1);
2563
+
2564
+ if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2565
+ commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2566
+ error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2567
+ strbuf_release(&err);
2568
+ goto rollback;
2569
+ }
2570
+
2571
+ return 0;
2572
+
2573
+ rollback:
2574
+ lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2575
+ if (!lock) {
2576
+ error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2577
+ strbuf_release(&err);
2578
+ goto rollbacklog;
2579
+ }
2580
+
2581
+ flag = log_all_ref_updates;
2582
+ log_all_ref_updates = 0;
2583
+ if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2584
+ commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2585
+ error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2586
+ strbuf_release(&err);
2587
+ }
2588
+ log_all_ref_updates = flag;
2589
+
2590
+ rollbacklog:
2591
+ if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2592
+ error("unable to restore logfile %s from %s: %s",
2593
+ oldrefname, newrefname, strerror(errno));
2594
+ if (!logmoved && log &&
2595
+ rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2596
+ error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2597
+ oldrefname, strerror(errno));
2598
+
2599
+ return 1;
2600
+}
2601
+
2602
+static int close_ref(struct ref_lock *lock)
2603
+{
2604
+ if (close_lock_file(lock->lk))
2605
+ return -1;
2606
+ return 0;
2607
+}
2608
+
2609
+static int commit_ref(struct ref_lock *lock)
2610
+{
2611
+ if (commit_lock_file(lock->lk))
2612
+ return -1;
2613
+ return 0;
2614
+}
2615
+
2616
+/*
2617
+ * Create a reflog for a ref. If force_create = 0, the reflog will
2618
+ * only be created for certain refs (those for which
2619
+ * should_autocreate_reflog returns non-zero. Otherwise, create it
2620
+ * regardless of the ref name. Fill in *err and return -1 on failure.
2621
+ */
2622
+static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2623
+{
2624
+ int logfd, oflags = O_APPEND | O_WRONLY;
2625
+
2626
+ strbuf_git_path(logfile, "logs/%s", refname);
2627
+ if (force_create || should_autocreate_reflog(refname)) {
2628
+ if (safe_create_leading_directories(logfile->buf) < 0) {
2629
+ strbuf_addf(err, "unable to create directory for %s: "
2630
+ "%s", logfile->buf, strerror(errno));
2631
+ return -1;
2632
+ }
2633
+ oflags |= O_CREAT;
2634
+ }
2635
+
2636
+ logfd = open(logfile->buf, oflags, 0666);
2637
+ if (logfd < 0) {
2638
+ if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2639
+ return 0;
2640
+
2641
+ if (errno == EISDIR) {
2642
+ if (remove_empty_directories(logfile)) {
2643
+ strbuf_addf(err, "There are still logs under "
2644
+ "'%s'", logfile->buf);
2645
+ return -1;
2646
+ }
2647
+ logfd = open(logfile->buf, oflags, 0666);
2648
+ }
2649
+
2650
+ if (logfd < 0) {
2651
+ strbuf_addf(err, "unable to append to %s: %s",
2652
+ logfile->buf, strerror(errno));
2653
+ return -1;
2654
+ }
2655
+ }
2656
+
2657
+ adjust_shared_perm(logfile->buf);
2658
+ close(logfd);
2659
+ return 0;
2660
+}
2661
+
2662
+
2663
+int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2664
+{
2665
+ int ret;
2666
+ struct strbuf sb = STRBUF_INIT;
2667
+
2668
+ ret = log_ref_setup(refname, &sb, err, force_create);
2669
+ strbuf_release(&sb);
2670
+ return ret;
2671
+}
2672
+
2673
+static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2674
+ const unsigned char *new_sha1,
2675
+ const char *committer, const char *msg)
2676
+{
2677
+ int msglen, written;
2678
+ unsigned maxlen, len;
2679
+ char *logrec;
2680
+
2681
+ msglen = msg ? strlen(msg) : 0;
2682
+ maxlen = strlen(committer) + msglen + 100;
2683
+ logrec = xmalloc(maxlen);
2684
+ len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2685
+ sha1_to_hex(old_sha1),
2686
+ sha1_to_hex(new_sha1),
2687
+ committer);
2688
+ if (msglen)
2689
+ len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2690
+
2691
+ written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2692
+ free(logrec);
2693
+ if (written != len)
2694
+ return -1;
2695
+
2696
+ return 0;
2697
+}
2698
+
2699
+static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2700
+ const unsigned char *new_sha1, const char *msg,
2701
+ struct strbuf *logfile, int flags,
2702
+ struct strbuf *err)
2703
+{
2704
+ int logfd, result, oflags = O_APPEND | O_WRONLY;
2705
+
2706
+ if (log_all_ref_updates < 0)
2707
+ log_all_ref_updates = !is_bare_repository();
2708
+
2709
+ result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2710
+
2711
+ if (result)
2712
+ return result;
2713
+
2714
+ logfd = open(logfile->buf, oflags);
2715
+ if (logfd < 0)
2716
+ return 0;
2717
+ result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2718
+ git_committer_info(0), msg);
2719
+ if (result) {
2720
+ strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2721
+ strerror(errno));
2722
+ close(logfd);
2723
+ return -1;
2724
+ }
2725
+ if (close(logfd)) {
2726
+ strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2727
+ strerror(errno));
2728
+ return -1;
2729
+ }
2730
+ return 0;
2731
+}
2732
+
2733
+static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2734
+ const unsigned char *new_sha1, const char *msg,
2735
+ int flags, struct strbuf *err)
2736
+{
2737
+ struct strbuf sb = STRBUF_INIT;
2738
+ int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2739
+ err);
2740
+ strbuf_release(&sb);
2741
+ return ret;
2742
+}
2743
+
2744
+/*
2745
+ * Write sha1 into the open lockfile, then close the lockfile. On
2746
+ * errors, rollback the lockfile, fill in *err and
2747
+ * return -1.
2748
+ */
2749
+static int write_ref_to_lockfile(struct ref_lock *lock,
2750
+ const unsigned char *sha1, struct strbuf *err)
2751
+{
2752
+ static char term = '\n';
2753
+ struct object *o;
2754
+ int fd;
2755
+
2756
+ o = parse_object(sha1);
2757
+ if (!o) {
2758
+ strbuf_addf(err,
2759
+ "Trying to write ref %s with nonexistent object %s",
2760
+ lock->ref_name, sha1_to_hex(sha1));
2761
+ unlock_ref(lock);
2762
+ return -1;
2763
+ }
2764
+ if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2765
+ strbuf_addf(err,
2766
+ "Trying to write non-commit object %s to branch %s",
2767
+ sha1_to_hex(sha1), lock->ref_name);
2768
+ unlock_ref(lock);
2769
+ return -1;
2770
+ }
2771
+ fd = get_lock_file_fd(lock->lk);
2772
+ if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2773
+ write_in_full(fd, &term, 1) != 1 ||
2774
+ close_ref(lock) < 0) {
2775
+ strbuf_addf(err,
2776
+ "Couldn't write %s", get_lock_file_path(lock->lk));
2777
+ unlock_ref(lock);
2778
+ return -1;
2779
+ }
2780
+ return 0;
2781
+}
2782
+
2783
+/*
2784
+ * Commit a change to a loose reference that has already been written
2785
+ * to the loose reference lockfile. Also update the reflogs if
2786
+ * necessary, using the specified lockmsg (which can be NULL).
2787
+ */
2788
+static int commit_ref_update(struct ref_lock *lock,
2789
+ const unsigned char *sha1, const char *logmsg,
2790
+ int flags, struct strbuf *err)
2791
+{
2792
+ clear_loose_ref_cache(&ref_cache);
2793
+ if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2794
+ (strcmp(lock->ref_name, lock->orig_ref_name) &&
2795
+ log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2796
+ char *old_msg = strbuf_detach(err, NULL);
2797
+ strbuf_addf(err, "Cannot update the ref '%s': %s",
2798
+ lock->ref_name, old_msg);
2799
+ free(old_msg);
2800
+ unlock_ref(lock);
2801
+ return -1;
2802
+ }
2803
+ if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2804
+ /*
2805
+ * Special hack: If a branch is updated directly and HEAD
2806
+ * points to it (may happen on the remote side of a push
2807
+ * for example) then logically the HEAD reflog should be
2808
+ * updated too.
2809
+ * A generic solution implies reverse symref information,
2810
+ * but finding all symrefs pointing to the given branch
2811
+ * would be rather costly for this rare event (the direct
2812
+ * update of a branch) to be worth it. So let's cheat and
2813
+ * check with HEAD only which should cover 99% of all usage
2814
+ * scenarios (even 100% of the default ones).
2815
+ */
2816
+ unsigned char head_sha1[20];
2817
+ int head_flag;
2818
+ const char *head_ref;
2819
+ head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2820
+ head_sha1, &head_flag);
2821
+ if (head_ref && (head_flag & REF_ISSYMREF) &&
2822
+ !strcmp(head_ref, lock->ref_name)) {
2823
+ struct strbuf log_err = STRBUF_INIT;
2824
+ if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2825
+ logmsg, 0, &log_err)) {
2826
+ error("%s", log_err.buf);
2827
+ strbuf_release(&log_err);
2828
+ }
2829
+ }
2830
+ }
2831
+ if (commit_ref(lock)) {
2832
+ error("Couldn't set %s", lock->ref_name);
2833
+ unlock_ref(lock);
2834
+ return -1;
2835
+ }
2836
+
2837
+ unlock_ref(lock);
2838
+ return 0;
2839
+}
2840
+
2841
+int create_symref(const char *ref_target, const char *refs_heads_master,
2842
+ const char *logmsg)
2843
+{
2844
+ char *lockpath = NULL;
2845
+ char ref[1000];
2846
+ int fd, len, written;
2847
+ char *git_HEAD = git_pathdup("%s", ref_target);
2848
+ unsigned char old_sha1[20], new_sha1[20];
2849
+ struct strbuf err = STRBUF_INIT;
2850
+
2851
+ if (logmsg && read_ref(ref_target, old_sha1))
2852
+ hashclr(old_sha1);
2853
+
2854
+ if (safe_create_leading_directories(git_HEAD) < 0)
2855
+ return error("unable to create directory for %s", git_HEAD);
2856
+
2857
+#ifndef NO_SYMLINK_HEAD
2858
+ if (prefer_symlink_refs) {
2859
+ unlink(git_HEAD);
2860
+ if (!symlink(refs_heads_master, git_HEAD))
2861
+ goto done;
2862
+ fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2863
+ }
2864
+#endif
2865
+
2866
+ len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2867
+ if (sizeof(ref) <= len) {
2868
+ error("refname too long: %s", refs_heads_master);
2869
+ goto error_free_return;
2870
+ }
2871
+ lockpath = mkpathdup("%s.lock", git_HEAD);
2872
+ fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2873
+ if (fd < 0) {
2874
+ error("Unable to open %s for writing", lockpath);
2875
+ goto error_free_return;
2876
+ }
2877
+ written = write_in_full(fd, ref, len);
2878
+ if (close(fd) != 0 || written != len) {
2879
+ error("Unable to write to %s", lockpath);
2880
+ goto error_unlink_return;
2881
+ }
2882
+ if (rename(lockpath, git_HEAD) < 0) {
2883
+ error("Unable to create %s", git_HEAD);
2884
+ goto error_unlink_return;
2885
+ }
2886
+ if (adjust_shared_perm(git_HEAD)) {
2887
+ error("Unable to fix permissions on %s", lockpath);
2888
+ error_unlink_return:
2889
+ unlink_or_warn(lockpath);
2890
+ error_free_return:
2891
+ free(lockpath);
2892
+ free(git_HEAD);
2893
+ return -1;
2894
+ }
2895
+ free(lockpath);
2896
+
2897
+#ifndef NO_SYMLINK_HEAD
2898
+ done:
2899
+#endif
2900
+ if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
2901
+ log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
2902
+ error("%s", err.buf);
2903
+ strbuf_release(&err);
2904
+ }
2905
+
2906
+ free(git_HEAD);
2907
+ return 0;
2908
+}
2909
+
2910
+int reflog_exists(const char *refname)
2911
+{
2912
+ struct stat st;
2913
+
2914
+ return !lstat(git_path("logs/%s", refname), &st) &&
2915
+ S_ISREG(st.st_mode);
2916
+}
2917
+
2918
+int delete_reflog(const char *refname)
2919
+{
2920
+ return remove_path(git_path("logs/%s", refname));
2921
+}
2922
+
2923
+static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2924
+{
2925
+ unsigned char osha1[20], nsha1[20];
2926
+ char *email_end, *message;
2927
+ unsigned long timestamp;
2928
+ int tz;
2929
+
2930
+ /* old SP new SP name <email> SP time TAB msg LF */
2931
+ if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2932
+ get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2933
+ get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2934
+ !(email_end = strchr(sb->buf + 82, '>')) ||
2935
+ email_end[1] != ' ' ||
2936
+ !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2937
+ !message || message[0] != ' ' ||
2938
+ (message[1] != '+' && message[1] != '-') ||
2939
+ !isdigit(message[2]) || !isdigit(message[3]) ||
2940
+ !isdigit(message[4]) || !isdigit(message[5]))
2941
+ return 0; /* corrupt? */
2942
+ email_end[1] = '\0';
2943
+ tz = strtol(message + 1, NULL, 10);
2944
+ if (message[6] != '\t')
2945
+ message += 6;
2946
+ else
2947
+ message += 7;
2948
+ return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2949
+}
2950
+
2951
+static char *find_beginning_of_line(char *bob, char *scan)
2952
+{
2953
+ while (bob < scan && *(--scan) != '\n')
2954
+ ; /* keep scanning backwards */
2955
+ /*
2956
+ * Return either beginning of the buffer, or LF at the end of
2957
+ * the previous line.
2958
+ */
2959
+ return scan;
2960
+}
2961
+
2962
+int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2963
+{
2964
+ struct strbuf sb = STRBUF_INIT;
2965
+ FILE *logfp;
2966
+ long pos;
2967
+ int ret = 0, at_tail = 1;
2968
+
2969
+ logfp = fopen(git_path("logs/%s", refname), "r");
2970
+ if (!logfp)
2971
+ return -1;
2972
+
2973
+ /* Jump to the end */
2974
+ if (fseek(logfp, 0, SEEK_END) < 0)
2975
+ return error("cannot seek back reflog for %s: %s",
2976
+ refname, strerror(errno));
2977
+ pos = ftell(logfp);
2978
+ while (!ret && 0 < pos) {
2979
+ int cnt;
2980
+ size_t nread;
2981
+ char buf[BUFSIZ];
2982
+ char *endp, *scanp;
2983
+
2984
+ /* Fill next block from the end */
2985
+ cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2986
+ if (fseek(logfp, pos - cnt, SEEK_SET))
2987
+ return error("cannot seek back reflog for %s: %s",
2988
+ refname, strerror(errno));
2989
+ nread = fread(buf, cnt, 1, logfp);
2990
+ if (nread != 1)
2991
+ return error("cannot read %d bytes from reflog for %s: %s",
2992
+ cnt, refname, strerror(errno));
2993
+ pos -= cnt;
2994
+
2995
+ scanp = endp = buf + cnt;
2996
+ if (at_tail && scanp[-1] == '\n')
2997
+ /* Looking at the final LF at the end of the file */
2998
+ scanp--;
2999
+ at_tail = 0;
3000
+
3001
+ while (buf < scanp) {
3002
+ /*
3003
+ * terminating LF of the previous line, or the beginning
3004
+ * of the buffer.
3005
+ */
3006
+ char *bp;
3007
+
3008
+ bp = find_beginning_of_line(buf, scanp);
3009
+
3010
+ if (*bp == '\n') {
3011
+ /*
3012
+ * The newline is the end of the previous line,
3013
+ * so we know we have complete line starting
3014
+ * at (bp + 1). Prefix it onto any prior data
3015
+ * we collected for the line and process it.
3016
+ */
3017
+ strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3018
+ scanp = bp;
3019
+ endp = bp + 1;
3020
+ ret = show_one_reflog_ent(&sb, fn, cb_data);
3021
+ strbuf_reset(&sb);
3022
+ if (ret)
3023
+ break;
3024
+ } else if (!pos) {
3025
+ /*
3026
+ * We are at the start of the buffer, and the
3027
+ * start of the file; there is no previous
3028
+ * line, and we have everything for this one.
3029
+ * Process it, and we can end the loop.
3030
+ */
3031
+ strbuf_splice(&sb, 0, 0, buf, endp - buf);
3032
+ ret = show_one_reflog_ent(&sb, fn, cb_data);
3033
+ strbuf_reset(&sb);
3034
+ break;
3035
+ }
3036
+
3037
+ if (bp == buf) {
3038
+ /*
3039
+ * We are at the start of the buffer, and there
3040
+ * is more file to read backwards. Which means
3041
+ * we are in the middle of a line. Note that we
3042
+ * may get here even if *bp was a newline; that
3043
+ * just means we are at the exact end of the
3044
+ * previous line, rather than some spot in the
3045
+ * middle.
3046
+ *
3047
+ * Save away what we have to be combined with
3048
+ * the data from the next read.
3049
+ */
3050
+ strbuf_splice(&sb, 0, 0, buf, endp - buf);
3051
+ break;
3052
+ }
3053
+ }
3054
+
3055
+ }
3056
+ if (!ret && sb.len)
3057
+ die("BUG: reverse reflog parser had leftover data");
3058
+
3059
+ fclose(logfp);
3060
+ strbuf_release(&sb);
3061
+ return ret;
3062
+}
3063
+
3064
+int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3065
+{
3066
+ FILE *logfp;
3067
+ struct strbuf sb = STRBUF_INIT;
3068
+ int ret = 0;
3069
+
3070
+ logfp = fopen(git_path("logs/%s", refname), "r");
3071
+ if (!logfp)
3072
+ return -1;
3073
+
3074
+ while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3075
+ ret = show_one_reflog_ent(&sb, fn, cb_data);
3076
+ fclose(logfp);
3077
+ strbuf_release(&sb);
3078
+ return ret;
3079
+}
3080
+/*
3081
+ * Call fn for each reflog in the namespace indicated by name. name
3082
+ * must be empty or end with '/'. Name will be used as a scratch
3083
+ * space, but its contents will be restored before return.
3084
+ */
3085
+static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3086
+{
3087
+ DIR *d = opendir(git_path("logs/%s", name->buf));
3088
+ int retval = 0;
3089
+ struct dirent *de;
3090
+ int oldlen = name->len;
3091
+
3092
+ if (!d)
3093
+ return name->len ? errno : 0;
3094
+
3095
+ while ((de = readdir(d)) != NULL) {
3096
+ struct stat st;
3097
+
3098
+ if (de->d_name[0] == '.')
3099
+ continue;
3100
+ if (ends_with(de->d_name, ".lock"))
3101
+ continue;
3102
+ strbuf_addstr(name, de->d_name);
3103
+ if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3104
+ ; /* silently ignore */
3105
+ } else {
3106
+ if (S_ISDIR(st.st_mode)) {
3107
+ strbuf_addch(name, '/');
3108
+ retval = do_for_each_reflog(name, fn, cb_data);
3109
+ } else {
3110
+ struct object_id oid;
3111
+
3112
+ if (read_ref_full(name->buf, 0, oid.hash, NULL))
3113
+ retval = error("bad ref for %s", name->buf);
3114
+ else
3115
+ retval = fn(name->buf, &oid, 0, cb_data);
3116
+ }
3117
+ if (retval)
3118
+ break;
3119
+ }
3120
+ strbuf_setlen(name, oldlen);
3121
+ }
3122
+ closedir(d);
3123
+ return retval;
3124
+}
3125
+
3126
+int for_each_reflog(each_ref_fn fn, void *cb_data)
3127
+{
3128
+ int retval;
3129
+ struct strbuf name;
3130
+ strbuf_init(&name, PATH_MAX);
3131
+ retval = do_for_each_reflog(&name, fn, cb_data);
3132
+ strbuf_release(&name);
3133
+ return retval;
3134
+}
3135
+
3136
+static int ref_update_reject_duplicates(struct string_list *refnames,
3137
+ struct strbuf *err)
3138
+{
3139
+ int i, n = refnames->nr;
3140
+
3141
+ assert(err);
3142
+
3143
+ for (i = 1; i < n; i++)
3144
+ if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3145
+ strbuf_addf(err,
3146
+ "Multiple updates for ref '%s' not allowed.",
3147
+ refnames->items[i].string);
3148
+ return 1;
3149
+ }
3150
+ return 0;
3151
+}
3152
+
3153
+int ref_transaction_commit(struct ref_transaction *transaction,
3154
+ struct strbuf *err)
3155
+{
3156
+ int ret = 0, i;
3157
+ int n = transaction->nr;
3158
+ struct ref_update **updates = transaction->updates;
3159
+ struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3160
+ struct string_list_item *ref_to_delete;
3161
+ struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3162
+
3163
+ assert(err);
3164
+
3165
+ if (transaction->state != REF_TRANSACTION_OPEN)
3166
+ die("BUG: commit called for transaction that is not open");
3167
+
3168
+ if (!n) {
3169
+ transaction->state = REF_TRANSACTION_CLOSED;
3170
+ return 0;
3171
+ }
3172
+
3173
+ /* Fail if a refname appears more than once in the transaction: */
3174
+ for (i = 0; i < n; i++)
3175
+ string_list_append(&affected_refnames, updates[i]->refname);
3176
+ string_list_sort(&affected_refnames);
3177
+ if (ref_update_reject_duplicates(&affected_refnames, err)) {
3178
+ ret = TRANSACTION_GENERIC_ERROR;
3179
+ goto cleanup;
3180
+ }
3181
+
3182
+ /*
3183
+ * Acquire all locks, verify old values if provided, check
3184
+ * that new values are valid, and write new values to the
3185
+ * lockfiles, ready to be activated. Only keep one lockfile
3186
+ * open at a time to avoid running out of file descriptors.
3187
+ */
3188
+ for (i = 0; i < n; i++) {
3189
+ struct ref_update *update = updates[i];
3190
+
3191
+ if ((update->flags & REF_HAVE_NEW) &&
3192
+ is_null_sha1(update->new_sha1))
3193
+ update->flags |= REF_DELETING;
3194
+ update->lock = lock_ref_sha1_basic(
3195
+ update->refname,
3196
+ ((update->flags & REF_HAVE_OLD) ?
3197
+ update->old_sha1 : NULL),
3198
+ &affected_refnames, NULL,
3199
+ update->flags,
3200
+ &update->type,
3201
+ err);
3202
+ if (!update->lock) {
3203
+ char *reason;
3204
+
3205
+ ret = (errno == ENOTDIR)
3206
+ ? TRANSACTION_NAME_CONFLICT
3207
+ : TRANSACTION_GENERIC_ERROR;
3208
+ reason = strbuf_detach(err, NULL);
3209
+ strbuf_addf(err, "cannot lock ref '%s': %s",
3210
+ update->refname, reason);
3211
+ free(reason);
3212
+ goto cleanup;
3213
+ }
3214
+ if ((update->flags & REF_HAVE_NEW) &&
3215
+ !(update->flags & REF_DELETING)) {
3216
+ int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3217
+ (update->flags & REF_NODEREF));
3218
+
3219
+ if (!overwriting_symref &&
3220
+ !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3221
+ /*
3222
+ * The reference already has the desired
3223
+ * value, so we don't need to write it.
3224
+ */
3225
+ } else if (write_ref_to_lockfile(update->lock,
3226
+ update->new_sha1,
3227
+ err)) {
3228
+ char *write_err = strbuf_detach(err, NULL);
3229
+
3230
+ /*
3231
+ * The lock was freed upon failure of
3232
+ * write_ref_to_lockfile():
3233
+ */
3234
+ update->lock = NULL;
3235
+ strbuf_addf(err,
3236
+ "cannot update the ref '%s': %s",
3237
+ update->refname, write_err);
3238
+ free(write_err);
3239
+ ret = TRANSACTION_GENERIC_ERROR;
3240
+ goto cleanup;
3241
+ } else {
3242
+ update->flags |= REF_NEEDS_COMMIT;
3243
+ }
3244
+ }
3245
+ if (!(update->flags & REF_NEEDS_COMMIT)) {
3246
+ /*
3247
+ * We didn't have to write anything to the lockfile.
3248
+ * Close it to free up the file descriptor:
3249
+ */
3250
+ if (close_ref(update->lock)) {
3251
+ strbuf_addf(err, "Couldn't close %s.lock",
3252
+ update->refname);
3253
+ goto cleanup;
3254
+ }
3255
+ }
3256
+ }
3257
+
3258
+ /* Perform updates first so live commits remain referenced */
3259
+ for (i = 0; i < n; i++) {
3260
+ struct ref_update *update = updates[i];
3261
+
3262
+ if (update->flags & REF_NEEDS_COMMIT) {
3263
+ if (commit_ref_update(update->lock,
3264
+ update->new_sha1, update->msg,
3265
+ update->flags, err)) {
3266
+ /* freed by commit_ref_update(): */
3267
+ update->lock = NULL;
3268
+ ret = TRANSACTION_GENERIC_ERROR;
3269
+ goto cleanup;
3270
+ } else {
3271
+ /* freed by commit_ref_update(): */
3272
+ update->lock = NULL;
3273
+ }
3274
+ }
3275
+ }
3276
+
3277
+ /* Perform deletes now that updates are safely completed */
3278
+ for (i = 0; i < n; i++) {
3279
+ struct ref_update *update = updates[i];
3280
+
3281
+ if (update->flags & REF_DELETING) {
3282
+ if (delete_ref_loose(update->lock, update->type, err)) {
3283
+ ret = TRANSACTION_GENERIC_ERROR;
3284
+ goto cleanup;
3285
+ }
3286
+
3287
+ if (!(update->flags & REF_ISPRUNING))
3288
+ string_list_append(&refs_to_delete,
3289
+ update->lock->ref_name);
3290
+ }
3291
+ }
3292
+
3293
+ if (repack_without_refs(&refs_to_delete, err)) {
3294
+ ret = TRANSACTION_GENERIC_ERROR;
3295
+ goto cleanup;
3296
+ }
3297
+ for_each_string_list_item(ref_to_delete, &refs_to_delete)
3298
+ unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3299
+ clear_loose_ref_cache(&ref_cache);
3300
+
3301
+cleanup:
3302
+ transaction->state = REF_TRANSACTION_CLOSED;
3303
+
3304
+ for (i = 0; i < n; i++)
3305
+ if (updates[i]->lock)
3306
+ unlock_ref(updates[i]->lock);
3307
+ string_list_clear(&refs_to_delete, 0);
3308
+ string_list_clear(&affected_refnames, 0);
3309
+ return ret;
3310
+}
3311
+
3312
+static int ref_present(const char *refname,
3313
+ const struct object_id *oid, int flags, void *cb_data)
3314
+{
3315
+ struct string_list *affected_refnames = cb_data;
3316
+
3317
+ return string_list_has_string(affected_refnames, refname);
3318
+}
3319
+
3320
+int initial_ref_transaction_commit(struct ref_transaction *transaction,
3321
+ struct strbuf *err)
3322
+{
3323
+ int ret = 0, i;
3324
+ int n = transaction->nr;
3325
+ struct ref_update **updates = transaction->updates;
3326
+ struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3327
+
3328
+ assert(err);
3329
+
3330
+ if (transaction->state != REF_TRANSACTION_OPEN)
3331
+ die("BUG: commit called for transaction that is not open");
3332
+
3333
+ /* Fail if a refname appears more than once in the transaction: */
3334
+ for (i = 0; i < n; i++)
3335
+ string_list_append(&affected_refnames, updates[i]->refname);
3336
+ string_list_sort(&affected_refnames);
3337
+ if (ref_update_reject_duplicates(&affected_refnames, err)) {
3338
+ ret = TRANSACTION_GENERIC_ERROR;
3339
+ goto cleanup;
3340
+ }
3341
+
3342
+ /*
3343
+ * It's really undefined to call this function in an active
3344
+ * repository or when there are existing references: we are
3345
+ * only locking and changing packed-refs, so (1) any
3346
+ * simultaneous processes might try to change a reference at
3347
+ * the same time we do, and (2) any existing loose versions of
3348
+ * the references that we are setting would have precedence
3349
+ * over our values. But some remote helpers create the remote
3350
+ * "HEAD" and "master" branches before calling this function,
3351
+ * so here we really only check that none of the references
3352
+ * that we are creating already exists.
3353
+ */
3354
+ if (for_each_rawref(ref_present, &affected_refnames))
3355
+ die("BUG: initial ref transaction called with existing refs");
3356
+
3357
+ for (i = 0; i < n; i++) {
3358
+ struct ref_update *update = updates[i];
3359
+
3360
+ if ((update->flags & REF_HAVE_OLD) &&
3361
+ !is_null_sha1(update->old_sha1))
3362
+ die("BUG: initial ref transaction with old_sha1 set");
3363
+ if (verify_refname_available(update->refname,
3364
+ &affected_refnames, NULL,
3365
+ err)) {
3366
+ ret = TRANSACTION_NAME_CONFLICT;
3367
+ goto cleanup;
3368
+ }
3369
+ }
3370
+
3371
+ if (lock_packed_refs(0)) {
3372
+ strbuf_addf(err, "unable to lock packed-refs file: %s",
3373
+ strerror(errno));
3374
+ ret = TRANSACTION_GENERIC_ERROR;
3375
+ goto cleanup;
3376
+ }
3377
+
3378
+ for (i = 0; i < n; i++) {
3379
+ struct ref_update *update = updates[i];
3380
+
3381
+ if ((update->flags & REF_HAVE_NEW) &&
3382
+ !is_null_sha1(update->new_sha1))
3383
+ add_packed_ref(update->refname, update->new_sha1);
3384
+ }
3385
+
3386
+ if (commit_packed_refs()) {
3387
+ strbuf_addf(err, "unable to commit packed-refs file: %s",
3388
+ strerror(errno));
3389
+ ret = TRANSACTION_GENERIC_ERROR;
3390
+ goto cleanup;
3391
+ }
3392
+
3393
+cleanup:
3394
+ transaction->state = REF_TRANSACTION_CLOSED;
3395
+ string_list_clear(&affected_refnames, 0);
3396
+ return ret;
3397
+}
3398
+
3399
+struct expire_reflog_cb {
3400
+ unsigned int flags;
3401
+ reflog_expiry_should_prune_fn *should_prune_fn;
3402
+ void *policy_cb;
3403
+ FILE *newlog;
3404
+ unsigned char last_kept_sha1[20];
3405
+};
3406
+
3407
+static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3408
+ const char *email, unsigned long timestamp, int tz,
3409
+ const char *message, void *cb_data)
3410
+{
3411
+ struct expire_reflog_cb *cb = cb_data;
3412
+ struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3413
+
3414
+ if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3415
+ osha1 = cb->last_kept_sha1;
3416
+
3417
+ if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3418
+ message, policy_cb)) {
3419
+ if (!cb->newlog)
3420
+ printf("would prune %s", message);
3421
+ else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3422
+ printf("prune %s", message);
3423
+ } else {
3424
+ if (cb->newlog) {
3425
+ fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3426
+ sha1_to_hex(osha1), sha1_to_hex(nsha1),
3427
+ email, timestamp, tz, message);
3428
+ hashcpy(cb->last_kept_sha1, nsha1);
3429
+ }
3430
+ if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3431
+ printf("keep %s", message);
3432
+ }
3433
+ return 0;
3434
+}
3435
+
3436
+int reflog_expire(const char *refname, const unsigned char *sha1,
3437
+ unsigned int flags,
3438
+ reflog_expiry_prepare_fn prepare_fn,
3439
+ reflog_expiry_should_prune_fn should_prune_fn,
3440
+ reflog_expiry_cleanup_fn cleanup_fn,
3441
+ void *policy_cb_data)
3442
+{
3443
+ static struct lock_file reflog_lock;
3444
+ struct expire_reflog_cb cb;
3445
+ struct ref_lock *lock;
3446
+ char *log_file;
3447
+ int status = 0;
3448
+ int type;
3449
+ struct strbuf err = STRBUF_INIT;
3450
+
3451
+ memset(&cb, 0, sizeof(cb));
3452
+ cb.flags = flags;
3453
+ cb.policy_cb = policy_cb_data;
3454
+ cb.should_prune_fn = should_prune_fn;
3455
+
3456
+ /*
3457
+ * The reflog file is locked by holding the lock on the
3458
+ * reference itself, plus we might need to update the
3459
+ * reference if --updateref was specified:
3460
+ */
3461
+ lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3462
+ if (!lock) {
3463
+ error("cannot lock ref '%s': %s", refname, err.buf);
3464
+ strbuf_release(&err);
3465
+ return -1;
3466
+ }
3467
+ if (!reflog_exists(refname)) {
3468
+ unlock_ref(lock);
3469
+ return 0;
3470
+ }
3471
+
3472
+ log_file = git_pathdup("logs/%s", refname);
3473
+ if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3474
+ /*
3475
+ * Even though holding $GIT_DIR/logs/$reflog.lock has
3476
+ * no locking implications, we use the lock_file
3477
+ * machinery here anyway because it does a lot of the
3478
+ * work we need, including cleaning up if the program
3479
+ * exits unexpectedly.
3480
+ */
3481
+ if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3482
+ struct strbuf err = STRBUF_INIT;
3483
+ unable_to_lock_message(log_file, errno, &err);
3484
+ error("%s", err.buf);
3485
+ strbuf_release(&err);
3486
+ goto failure;
3487
+ }
3488
+ cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3489
+ if (!cb.newlog) {
3490
+ error("cannot fdopen %s (%s)",
3491
+ get_lock_file_path(&reflog_lock), strerror(errno));
3492
+ goto failure;
3493
+ }
3494
+ }
3495
+
3496
+ (*prepare_fn)(refname, sha1, cb.policy_cb);
3497
+ for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3498
+ (*cleanup_fn)(cb.policy_cb);
3499
+
3500
+ if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3501
+ /*
3502
+ * It doesn't make sense to adjust a reference pointed
3503
+ * to by a symbolic ref based on expiring entries in
3504
+ * the symbolic reference's reflog. Nor can we update
3505
+ * a reference if there are no remaining reflog
3506
+ * entries.
3507
+ */
3508
+ int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3509
+ !(type & REF_ISSYMREF) &&
3510
+ !is_null_sha1(cb.last_kept_sha1);
3511
+
3512
+ if (close_lock_file(&reflog_lock)) {
3513
+ status |= error("couldn't write %s: %s", log_file,
3514
+ strerror(errno));
3515
+ } else if (update &&
3516
+ (write_in_full(get_lock_file_fd(lock->lk),
3517
+ sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3518
+ write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3519
+ close_ref(lock) < 0)) {
3520
+ status |= error("couldn't write %s",
3521
+ get_lock_file_path(lock->lk));
3522
+ rollback_lock_file(&reflog_lock);
3523
+ } else if (commit_lock_file(&reflog_lock)) {
3524
+ status |= error("unable to commit reflog '%s' (%s)",
3525
+ log_file, strerror(errno));
3526
+ } else if (update && commit_ref(lock)) {
3527
+ status |= error("couldn't set %s", lock->ref_name);
3528
+ }
3529
+ }
3530
+ free(log_file);
3531
+ unlock_ref(lock);
3532
+ return status;
3533
+
3534
+ failure:
3535
+ rollback_lock_file(&reflog_lock);
3536
+ free(log_file);
3537
+ unlock_ref(lock);
3538
+ return -1;
3539
+}