Skip to content

Commit 1474c89

Browse files
committed
cli: introduce cli_resolve_path
The git CLI takes paths as command-line inputs from the current working directory; provide a helper method to provide a repo-relative path based on paths specified on the command-line.
1 parent 49402cc commit 1474c89

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/cli/common.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
#include "git2_util.h"
1212
#include "vector.h"
13+
#include "fs_path.h"
1314

1415
#include "common.h"
1516
#include "error.h"
@@ -124,3 +125,44 @@ int cli_repository_open(
124125
*out = repo;
125126
return 0;
126127
}
128+
129+
/*
130+
* This resolves paths - not _pathspecs_ like git - it accepts an absolute
131+
* path (to a path within the repository working directory) or a path
132+
* relative to the current directory.
133+
*/
134+
int cli_resolve_path(git_str *out, git_repository *repo, const char *given_path)
135+
{
136+
git_str path = GIT_STR_INIT;
137+
int error = 0;
138+
139+
if (!git_fs_path_is_absolute(given_path)) {
140+
char cwd[GIT_PATH_MAX];
141+
142+
if (p_getcwd(cwd, GIT_PATH_MAX) < 0)
143+
error = cli_error_os();
144+
else if (git_str_puts(&path, cwd) < 0 ||
145+
git_fs_path_apply_relative(&path, given_path) < 0)
146+
error = cli_error_git();
147+
148+
if (error)
149+
goto done;
150+
} else if (git_str_puts(&path, given_path) < 0) {
151+
error = cli_error_git();
152+
goto done;
153+
}
154+
155+
error = git_fs_path_make_relative(&path, git_repository_workdir(repo));
156+
157+
if (error == GIT_ENOTFOUND)
158+
error = cli_error("path '%s' is not inside the git repository '%s'",
159+
given_path, git_repository_workdir(repo));
160+
else if (error < 0)
161+
error = cli_error_git();
162+
else
163+
git_str_swap(out, &path);
164+
165+
done:
166+
git_str_dispose(&path);
167+
return error;
168+
}

src/cli/common.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@ extern int cli_repository_open(
4444
git_repository **out,
4545
cli_repository_open_options *opts);
4646

47+
extern int cli_resolve_path(
48+
git_str *out,
49+
git_repository *repo,
50+
const char *given_path);
51+
4752
/*
4853
* Common command arguments.
4954
*/

0 commit comments

Comments
 (0)