Commit 6a9597c5b57456dfe02e4b5ba94ef437907fe1f1

Carlos Martín Nieto 2011-06-08T19:11:38

Add function to generate a request Add git_pkt_gen_proto to crete a request from an url. Signed-off-by: Carlos Martín Nieto <carlos@cmartin.tk>

diff --git a/include/git2/net.h b/include/git2/net.h
index 67e8a44..fb09eb5 100644
--- a/include/git2/net.h
+++ b/include/git2/net.h
@@ -5,6 +5,8 @@
 #include "oid.h"
 #include "types.h"
 
+#define GIT_DEFAULT_PORT "9418"
+
 /*
  * We need this because we need to know whether we should call
  * git-upload-pack or git-receive-pack on the remote end when get_refs
diff --git a/include/git2/pkt.h b/include/git2/pkt.h
index 0b933ab..8ba3c2a 100644
--- a/include/git2/pkt.h
+++ b/include/git2/pkt.h
@@ -50,3 +50,8 @@ struct git_pkt_ref {
 	git_remote_head head;
 	char *capabilities;
 };
+
+/**
+ * Create a git protocol request.
+ */
+int git_pkt_gen_proto(char **out, int *outlen, const char *url);
diff --git a/src/pkt.c b/src/pkt.c
index 612a431..023196a 100644
--- a/src/pkt.c
+++ b/src/pkt.c
@@ -172,3 +172,42 @@ int git_pkt_parse_line(git_pkt **head, const char *line, const char **out)
 
 	return error;
 }
+
+/*
+ * Create a git procol request.
+ *
+ * For example: 0035git-upload-pack /libgit2/libgit2\0host=github.com\0
+ *
+ * TODO: the command should not be hard-coded
+ */
+int git_pkt_gen_proto(char **out, int *outlen, const char *url)
+{
+	char *delim, *repo, *ptr;
+	char command[] = "git-upload-pack";
+	char host[] = "host=";
+	int len;
+
+	delim = strchr(url, '/');
+	if (delim == NULL)
+		return git__throw(GIT_EOBJCORRUPTED, "Failed to create proto-request: malformed URL");
+
+	repo = delim;
+
+	delim = strchr(url, ':');
+	if (delim == NULL)
+		delim = strchr(url, '/');
+
+	len = 4 + STRLEN(command) + 1 + strlen(repo) + 1 + STRLEN(host) + (delim - url) + 2;
+
+	*out = git__malloc(len);
+	if (*out == NULL)
+		return GIT_ENOMEM;
+
+	*outlen = len - 1;
+	ptr = *out;
+	memset(ptr, 0x0, len);
+	/* We expect the return value to be > len - 1 so don't bother checking it */
+	snprintf(ptr, len -1, "%04x%s %s%c%s%s", len - 1, command, repo, 0, host, url);
+
+	return GIT_SUCCESS;
+}