|
9 | 9 |
|
10 | 10 | #include "common.h" |
11 | 11 | #include "repository.h" |
| 12 | +#include "worktree.h" |
12 | 13 |
|
13 | 14 | static bool is_worktree_dir(git_buf *dir) |
14 | 15 | { |
@@ -56,3 +57,91 @@ int git_worktree_list(git_strarray *wts, git_repository *repo) |
56 | 57 |
|
57 | 58 | return error; |
58 | 59 | } |
| 60 | + |
| 61 | +static char *read_link(const char *base, const char *file) |
| 62 | +{ |
| 63 | + git_buf path = GIT_BUF_INIT, buf = GIT_BUF_INIT; |
| 64 | + |
| 65 | + assert(base && file); |
| 66 | + |
| 67 | + if (git_buf_joinpath(&path, base, file) < 0) |
| 68 | + goto err; |
| 69 | + if (git_futils_readbuffer(&buf, path.ptr) < 0) |
| 70 | + goto err; |
| 71 | + git_buf_free(&path); |
| 72 | + |
| 73 | + git_buf_rtrim(&buf); |
| 74 | + |
| 75 | + if (!git_path_is_relative(buf.ptr)) |
| 76 | + return git_buf_detach(&buf); |
| 77 | + |
| 78 | + if (git_buf_sets(&path, base) < 0) |
| 79 | + goto err; |
| 80 | + if (git_path_apply_relative(&path, buf.ptr) < 0) |
| 81 | + goto err; |
| 82 | + git_buf_free(&buf); |
| 83 | + |
| 84 | + return git_buf_detach(&path); |
| 85 | + |
| 86 | +err: |
| 87 | + git_buf_free(&buf); |
| 88 | + git_buf_free(&path); |
| 89 | + |
| 90 | + return NULL; |
| 91 | +} |
| 92 | + |
| 93 | +int git_worktree_lookup(git_worktree **out, git_repository *repo, const char *name) |
| 94 | +{ |
| 95 | + git_buf path = GIT_BUF_INIT; |
| 96 | + git_worktree *wt = NULL; |
| 97 | + int error; |
| 98 | + |
| 99 | + assert(repo && name); |
| 100 | + |
| 101 | + *out = NULL; |
| 102 | + |
| 103 | + if ((error = git_buf_printf(&path, "%s/worktrees/%s", repo->commondir, name)) < 0) |
| 104 | + goto out; |
| 105 | + |
| 106 | + if (!is_worktree_dir(&path)) { |
| 107 | + error = -1; |
| 108 | + goto out; |
| 109 | + } |
| 110 | + |
| 111 | + if ((wt = git__malloc(sizeof(struct git_repository))) == NULL) { |
| 112 | + error = -1; |
| 113 | + goto out; |
| 114 | + } |
| 115 | + |
| 116 | + if ((wt->name = git__strdup(name)) == NULL |
| 117 | + || (wt->commondir_path = read_link(path.ptr, "commondir")) == NULL |
| 118 | + || (wt->gitlink_path = read_link(path.ptr, "gitdir")) == NULL |
| 119 | + || (wt->parent_path = git__strdup(git_repository_path(repo))) == NULL) { |
| 120 | + error = -1; |
| 121 | + goto out; |
| 122 | + } |
| 123 | + wt->gitdir_path = git_buf_detach(&path); |
| 124 | + |
| 125 | + (*out) = wt; |
| 126 | + |
| 127 | +out: |
| 128 | + git_buf_free(&path); |
| 129 | + |
| 130 | + if (error) |
| 131 | + git_worktree_free(wt); |
| 132 | + |
| 133 | + return error; |
| 134 | +} |
| 135 | + |
| 136 | +void git_worktree_free(git_worktree *wt) |
| 137 | +{ |
| 138 | + if (!wt) |
| 139 | + return; |
| 140 | + |
| 141 | + git__free(wt->commondir_path); |
| 142 | + git__free(wt->gitlink_path); |
| 143 | + git__free(wt->gitdir_path); |
| 144 | + git__free(wt->parent_path); |
| 145 | + git__free(wt->name); |
| 146 | + git__free(wt); |
| 147 | +} |
0 commit comments