Skip to content

Commit 5b65ac2

Browse files
committed
refs: implement function to read references from file
Currently, we only provide functions to read references directly from a repository's reference store via e.g. `git_reference_lookup`. But in some cases, we may want to read files not connected to the current repository, e.g. when looking up HEAD of connected work trees. This commit implements `git_reference__read_head`, which will read out and allocate a reference at an arbitrary path.
1 parent 6029725 commit 5b65ac2

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/refs.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,40 @@ int git_reference_lookup_resolved(
249249
return 0;
250250
}
251251

252+
int git_reference__read_head(
253+
git_reference **out,
254+
git_repository *repo,
255+
const char *path)
256+
{
257+
git_buf reference = GIT_BUF_INIT;
258+
char *name = NULL;
259+
int error;
260+
261+
if ((error = git_futils_readbuffer(&reference, path)) < 0)
262+
goto out;
263+
git_buf_rtrim(&reference);
264+
265+
if (git__strncmp(reference.ptr, GIT_SYMREF, strlen(GIT_SYMREF)) == 0) {
266+
git_buf_consume(&reference, reference.ptr + strlen(GIT_SYMREF));
267+
268+
name = git_path_basename(path);
269+
270+
if ((*out = git_reference__alloc_symbolic(name, reference.ptr)) == NULL) {
271+
error = -1;
272+
goto out;
273+
}
274+
} else {
275+
if ((error = git_reference_lookup(out, repo, reference.ptr)) < 0)
276+
goto out;
277+
}
278+
279+
out:
280+
free(name);
281+
git_buf_clear(&reference);
282+
283+
return error;
284+
}
285+
252286
int git_reference_dwim(git_reference **out, git_repository *repo, const char *refname)
253287
{
254288
int error = 0, i;

src/refs.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,20 @@ int git_reference_lookup_resolved(
107107
const char *name,
108108
int max_deref);
109109

110+
/**
111+
* Read reference from a file.
112+
*
113+
* This function will read in the file at `path`. If it is a
114+
* symref, it will return a new unresolved symbolic reference
115+
* with the given name pointing to the reference pointed to by
116+
* the file. If it is not a symbolic reference, it will return
117+
* the resolved reference.
118+
*/
119+
int git_reference__read_head(
120+
git_reference **out,
121+
git_repository *repo,
122+
const char *path);
123+
110124
int git_reference__log_signature(git_signature **out, git_repository *repo);
111125

112126
/** Update a reference after a commit. */

0 commit comments

Comments
 (0)