Skip to content

Commit e02e6a5

Browse files
committed
url: introduce git_net_str_is_url
We occasionally need to determine whether a given string is a URL or something else. (The "something else" may be a git path in a different format, like scp formatting, which needs to be handled differently.)
1 parent 6913422 commit e02e6a5

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

src/net.c

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@
2020
#define DEFAULT_PORT_GIT "9418"
2121
#define DEFAULT_PORT_SSH "22"
2222

23+
bool git_net_str_is_url(const char *str)
24+
{
25+
const char *c;
26+
27+
for (c = str; *c; c++) {
28+
if (*c == ':' && *(c+1) == '/' && *(c+2) == '/')
29+
return true;
30+
31+
if ((*c < 'a' || *c > 'z') &&
32+
(*c < 'A' || *c > 'Z') &&
33+
(*c < '0' || *c > '9') &&
34+
(*c != '+' && *c != '-' && *c != '.'))
35+
break;
36+
}
37+
38+
return false;
39+
}
40+
2341
static const char *default_port_for_scheme(const char *scheme)
2442
{
2543
if (strcmp(scheme, "http") == 0)
@@ -28,7 +46,9 @@ static const char *default_port_for_scheme(const char *scheme)
2846
return DEFAULT_PORT_HTTPS;
2947
else if (strcmp(scheme, "git") == 0)
3048
return DEFAULT_PORT_GIT;
31-
else if (strcmp(scheme, "ssh") == 0)
49+
else if (strcmp(scheme, "ssh") == 0 ||
50+
strcmp(scheme, "ssh+git") == 0 ||
51+
strcmp(scheme, "git+ssh") == 0)
3252
return DEFAULT_PORT_SSH;
3353

3454
return NULL;

src/net.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ typedef struct git_net_url {
2121

2222
#define GIT_NET_URL_INIT { NULL }
2323

24+
/** Is a given string a url? */
25+
extern bool git_net_str_is_url(const char *str);
26+
2427
/** Duplicate a URL */
2528
extern int git_net_url_dup(git_net_url *out, git_net_url *in);
2629

tests/network/url/valid.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include "clar_libgit2.h"
2+
#include "net.h"
3+
4+
void test_network_url_valid__test(void)
5+
{
6+
cl_assert(git_net_str_is_url("http://example.com/"));
7+
cl_assert(git_net_str_is_url("file://localhost/tmp/foo/"));
8+
cl_assert(git_net_str_is_url("ssh://user@host:42/tmp"));
9+
cl_assert(git_net_str_is_url("git+ssh://user@host:42/tmp"));
10+
cl_assert(git_net_str_is_url("ssh+git://user@host:42/tmp"));
11+
cl_assert(git_net_str_is_url("https://user:pass@example.com/foo/bar"));
12+
13+
cl_assert(!git_net_str_is_url("host:foo.git"));
14+
cl_assert(!git_net_str_is_url("host:/foo.git"));
15+
cl_assert(!git_net_str_is_url("[host:42]:/foo.git"));
16+
cl_assert(!git_net_str_is_url("[user@host:42]:/foo.git"));
17+
}

0 commit comments

Comments
 (0)