Commit d1c281a5525882c4a6f157ea1f18837d5819dab3

Carlos Martín Nieto 2014-06-25T16:24:26

cred: add convenience function to get the username Since each cred defines the username on their own, introduce git_cred__username to retrieve the username pointer from them.

diff --git a/include/git2/transport.h b/include/git2/transport.h
index d1322a1..b57d1dd 100644
--- a/include/git2/transport.h
+++ b/include/git2/transport.h
@@ -221,6 +221,14 @@ GIT_EXTERN(int) git_cred_ssh_custom_new(
 GIT_EXTERN(int) git_cred_default_new(git_cred **out);
 
 /**
+ * Create a credential to specify a username.
+ *
+ * This is used with ssh authentication to query for the username if
+ * none is specified in the url.
+ */
+GIT_EXTERN(int) git_cred_username_new(git_cred **cred, const char *username);
+
+/**
  * Signature of a function which acquires a credential object.
  *
  * - cred: The newly created credential object.
diff --git a/src/transports/cred.c b/src/transports/cred.c
index 872b0ad..1b4d29c 100644
--- a/src/transports/cred.c
+++ b/src/transports/cred.c
@@ -17,6 +17,40 @@ int git_cred_has_username(git_cred *cred)
 	return 1;
 }
 
+const char *git_cred__username(git_cred *cred)
+{
+	switch (cred->credtype) {
+	case GIT_CREDTYPE_USERNAME:
+	{
+		git_cred_username *c = (git_cred_username *) cred;
+		return c->username;
+	}
+	case GIT_CREDTYPE_USERPASS_PLAINTEXT:
+	{
+		git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *) cred;
+		return c->username;
+	}
+	case GIT_CREDTYPE_SSH_KEY:
+	{
+		git_cred_ssh_key *c = (git_cred_ssh_key *) cred;
+		return c->username;
+	}
+	case GIT_CREDTYPE_SSH_CUSTOM:
+	{
+		git_cred_ssh_custom *c = (git_cred_ssh_custom *) cred;
+		return c->username;
+	}
+	case GIT_CREDTYPE_SSH_INTERACTIVE:
+	{
+		git_cred_ssh_interactive *c = (git_cred_ssh_interactive *) cred;
+		return c->username;
+	}
+
+	default:
+		return NULL;
+	}
+}
+
 static void plaintext_free(struct git_cred *cred)
 {
 	git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *)cred;
@@ -284,5 +318,6 @@ int git_cred_username_new(git_cred **cred, const char *username)
 	c->parent.free = username_free;
 	memcpy(c->username, username, len + 1);
 
+	*cred = (git_cred *) c;
 	return 0;
 }
diff --git a/src/transports/cred.h b/src/transports/cred.h
new file mode 100644
index 0000000..2de8dee
--- /dev/null
+++ b/src/transports/cred.h
@@ -0,0 +1,14 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+#ifndef INCLUDE_git_cred_h__
+#define INCLUDE_git_cred_h__
+
+#include "git2/transport.h"
+
+const char *git_cred__username(git_cred *cred);
+
+#endif