diff --git a/Octokit.Tests.Integration/Clients/RepositoryHooksClientTests.cs b/Octokit.Tests.Integration/Clients/RepositoryHooksClientTests.cs index 33d954ae95..a206232547 100644 --- a/Octokit.Tests.Integration/Clients/RepositoryHooksClientTests.cs +++ b/Octokit.Tests.Integration/Clients/RepositoryHooksClientTests.cs @@ -63,23 +63,28 @@ public async Task CreateAWebHookForTestRepository() var repoName = Helper.MakeNameWithTimestamp("create-hooks-test"); var repository = await github.Repository.Create(new NewRepository(repoName) { AutoInit = true }); + var url = "http://test.com/example"; + var contentType = WebHookContentType.Json; + var secret = "53cr37"; var config = new Dictionary { - { "content_type", "json" }, - { "url", "http://test.com/example" }, { "hostname", "http://hostname.url" }, { "username", "username" }, { "password", "password" } }; - var parameters = new NewRepositoryHook("windowsazure", config) + var parameters = new NewRepositoryWebHook("windowsazure", config, url) { Events = new[] { "push" }, - Active = false + Active = false, + ContentType = contentType, + Secret = secret }; - var hook = await github.Repository.Hooks.Create(Helper.Credentials.Login, repository.Name, parameters); + var hook = await github.Repository.Hooks.Create(Helper.Credentials.Login, repository.Name, parameters.ToRequest()); var baseHookUrl = CreateExpectedBaseHookUrl(repository.Url, hook.Id); + var webHookConfig = CreateExpectedConfigDictionary(config, url, contentType, secret); + Assert.Equal("windowsazure", hook.Name); Assert.Equal(new[] { "push" }.ToList(), hook.Events.ToList()); Assert.Equal(baseHookUrl, hook.Url); @@ -87,11 +92,22 @@ public async Task CreateAWebHookForTestRepository() Assert.Equal(baseHookUrl + "/pings", hook.PingUrl); Assert.NotNull(hook.CreatedAt); Assert.NotNull(hook.UpdatedAt); - Assert.Equal(config.Keys, hook.Config.Keys); - Assert.Equal(config.Values, hook.Config.Values); + Assert.Equal(webHookConfig.Keys, hook.Config.Keys); + Assert.Equal(webHookConfig.Values, hook.Config.Values); Assert.Equal(false, hook.Active); } + Dictionary CreateExpectedConfigDictionary(Dictionary config, string url, WebHookContentType contentType, string secret) + { + return config.Union(new Dictionary + { + { "url", url }, + { "content_type", contentType.ToString().ToLowerInvariant() }, + { "secret", secret }, + { "insecure_ssl", "False" } + }).ToDictionary(k => k.Key, v => v.Value); + } + string CreateExpectedBaseHookUrl(string url, int id) { return url + "/hooks/" + id; diff --git a/Octokit.Tests/Models/NewRepositoryWebHookTests.cs b/Octokit.Tests/Models/NewRepositoryWebHookTests.cs new file mode 100644 index 0000000000..ca95ec7036 --- /dev/null +++ b/Octokit.Tests/Models/NewRepositoryWebHookTests.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using Xunit; + +namespace Octokit.Tests.Models +{ + public class NewRepositoryWebHookTests + { + public class TheCtor + { + string ExpectedRepositoryWebHookConfigExceptionMessage = + "Duplicate webhook config values found - these values: Url should not be passed in as part of the config values. Use the properties on the NewRepositoryWebHook class instead."; + + [Fact] + public void UsesDefaultValuesForDefaultConfig() + { + var create = new NewRepositoryWebHook("windowsazure", new Dictionary(), "http://test.com/example"); + Assert.Equal(create.Url, "http://test.com/example"); + Assert.Equal(create.ContentType, WebHookContentType.Form); + Assert.Empty(create.Secret); + Assert.False(create.InsecureSsl); + + var request = create.ToRequest(); + Assert.Equal(request.Config.Count, 4); + + Assert.True(request.Config.ContainsKey("url")); + Assert.True(request.Config.ContainsKey("content_type")); + Assert.True(request.Config.ContainsKey("secret")); + Assert.True(request.Config.ContainsKey("insecure_ssl")); + + Assert.Equal(request.Config["url"], "http://test.com/example"); + Assert.Equal(request.Config["content_type"], WebHookContentType.Form.ToParameter()); + Assert.Equal(request.Config["secret"], ""); + Assert.Equal(request.Config["insecure_ssl"], "False"); + } + + [Fact] + public void CombinesUserSpecifiedContentTypeWithConfig() + { + var config = new Dictionary + { + {"hostname", "http://hostname.url"}, + {"username", "username"}, + {"password", "password"} + }; + + var create = new NewRepositoryWebHook("windowsazure", config, "http://test.com/example") + { + ContentType = WebHookContentType.Json, + Secret = string.Empty, + InsecureSsl = true + }; + + Assert.Equal(create.Url, "http://test.com/example"); + Assert.Equal(create.ContentType, WebHookContentType.Json); + Assert.Empty(create.Secret); + Assert.True(create.InsecureSsl); + + var request = create.ToRequest(); + + Assert.Equal(request.Config.Count, 7); + + Assert.True(request.Config.ContainsKey("url")); + Assert.True(request.Config.ContainsKey("content_type")); + Assert.True(request.Config.ContainsKey("secret")); + Assert.True(request.Config.ContainsKey("insecure_ssl")); + + Assert.Equal(request.Config["url"], "http://test.com/example"); + Assert.Equal(request.Config["content_type"], WebHookContentType.Json.ToParameter()); + Assert.Equal(request.Config["secret"], ""); + Assert.Equal(request.Config["insecure_ssl"], true.ToString()); + + Assert.True(request.Config.ContainsKey("hostname")); + Assert.Equal(request.Config["hostname"], config["hostname"]); + Assert.True(request.Config.ContainsKey("username")); + Assert.Equal(request.Config["username"], config["username"]); + Assert.True(request.Config.ContainsKey("password")); + Assert.Equal(request.Config["password"], config["password"]); + } + + [Fact] + public void ShouldThrowRepositoryWebHookConfigExceptionWhenDuplicateKeysExists() + { + var config = new Dictionary + { + {"url", "http://example.com/test"}, + {"hostname", "http://hostname.url"}, + {"username", "username"}, + {"password", "password"} + }; + + var create = new NewRepositoryWebHook("windowsazure", config, "http://test.com/example") + { + ContentType = WebHookContentType.Json, + Secret = string.Empty, + InsecureSsl = true + }; + + Assert.Equal(create.Url, "http://test.com/example"); + Assert.Equal(create.ContentType, WebHookContentType.Json); + Assert.Empty(create.Secret); + Assert.True(create.InsecureSsl); + + var ex = Assert.Throws(() => create.ToRequest()); + Assert.Equal(ExpectedRepositoryWebHookConfigExceptionMessage, ex.Message); + } + } + } +} diff --git a/Octokit.Tests/Octokit.Tests.csproj b/Octokit.Tests/Octokit.Tests.csproj index 9c00502159..804ebfc417 100644 --- a/Octokit.Tests/Octokit.Tests.csproj +++ b/Octokit.Tests/Octokit.Tests.csproj @@ -157,6 +157,7 @@ + diff --git a/Octokit/Clients/RepositoryHooksClient.cs b/Octokit/Clients/RepositoryHooksClient.cs index d4d30e55ca..458a1596f5 100644 --- a/Octokit/Clients/RepositoryHooksClient.cs +++ b/Octokit/Clients/RepositoryHooksClient.cs @@ -54,7 +54,7 @@ public Task Create(string owner, string repositoryName, NewRepos Ensure.ArgumentNotNullOrEmptyString(repositoryName, "repositoryName"); Ensure.ArgumentNotNull(hook, "hook"); - return ApiConnection.Post(ApiUrls.RepositoryHooks(owner, repositoryName), hook); + return ApiConnection.Post(ApiUrls.RepositoryHooks(owner, repositoryName), hook.ToRequest()); } /// diff --git a/Octokit/Exceptions/RepositoryWebHookConfigException.cs b/Octokit/Exceptions/RepositoryWebHookConfigException.cs new file mode 100644 index 0000000000..2368e6c73f --- /dev/null +++ b/Octokit/Exceptions/RepositoryWebHookConfigException.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Octokit +{ +#if !NETFX_CORE + [Serializable] +#endif + [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", + Justification = "These exceptions are specific to the GitHub API and not general purpose exceptions")] + public class RepositoryWebHookConfigException : Exception + { + readonly string message; + + public RepositoryWebHookConfigException(IEnumerable invalidConfig) + { + var parameterList = string.Join(", ", invalidConfig.Select(ic => ic.FromRubyCase())); + message = string.Format(CultureInfo.InvariantCulture, + "Duplicate webhook config values found - these values: {0} should not be passed in as part of the config values. Use the properties on the NewRepositoryWebHook class instead.", + parameterList); + } + + public override string Message + { + get { return message; } + } + +#if !NETFX_CORE + /// + /// Constructs an instance of RepositoryWebHookConfigException + /// + /// + /// The that holds the + /// serialized object data about the exception being thrown. + /// + /// + /// The that contains + /// contextual information about the source or destination. + /// + protected RepositoryWebHookConfigException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + if (info == null) return; + message = info.GetString("Message"); + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("Message", Message); + } +#endif + } +} diff --git a/Octokit/Helpers/StringExtensions.cs b/Octokit/Helpers/StringExtensions.cs index 71df432664..f195d405d4 100644 --- a/Octokit/Helpers/StringExtensions.cs +++ b/Octokit/Helpers/StringExtensions.cs @@ -84,6 +84,17 @@ public static string ToRubyCase(this string propertyName) return string.Join("_", propertyName.SplitUpperCase()).ToLowerInvariant(); } + public static string FromRubyCase(this string propertyName) + { + Ensure.ArgumentNotNullOrEmptyString(propertyName, "s"); + return string.Join("", propertyName.Split('_')).ToCapitalizedInvariant(); + } + + public static string ToCapitalizedInvariant(this string value) + { + Ensure.ArgumentNotNullOrEmptyString(value, "s"); + return string.Concat(value[0].ToString().ToUpperInvariant(), value.Substring(1)); + } static IEnumerable SplitUpperCase(this string source) { Ensure.ArgumentNotNullOrEmptyString(source, "source"); diff --git a/Octokit/Helpers/WebHookConfigComparer.cs b/Octokit/Helpers/WebHookConfigComparer.cs new file mode 100644 index 0000000000..4c71681554 --- /dev/null +++ b/Octokit/Helpers/WebHookConfigComparer.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace Octokit +{ + public class WebHookConfigComparer : IEqualityComparer> + { + public bool Equals(KeyValuePair x, KeyValuePair y) + { + return x.Key == y.Key; + } + + public int GetHashCode(KeyValuePair obj) + { + return obj.Key.GetHashCode(); + } + } +} diff --git a/Octokit/Models/Request/NewRepositoryHook.cs b/Octokit/Models/Request/NewRepositoryHook.cs index 86ac3b70d2..2a651cf617 100644 --- a/Octokit/Models/Request/NewRepositoryHook.cs +++ b/Octokit/Models/Request/NewRepositoryHook.cs @@ -18,8 +18,8 @@ namespace Octokit /// /// content_type /// - /// An optional string defining the media type used to serialize the payloads.Supported values include json and - /// form.The default is form. + /// An optional string defining the media type used to serialize the payloads. Supported values include json and + /// form. The default is form. /// /// /// @@ -33,7 +33,7 @@ namespace Octokit /// insecure_ssl: /// /// An optional string that determines whether the SSL certificate of the host for url will be verified when - /// delivering payloads.Supported values include "0" (verification is performed) and "1" (verification is not + /// delivering payloads. Supported values include "0" (verification is performed) and "1" (verification is not /// performed). The default is "0". /// /// @@ -100,6 +100,11 @@ public NewRepositoryHook(string name, IReadOnlyDictionary config /// public bool Active { get; set; } + public virtual NewRepositoryHook ToRequest() + { + return this; + } + internal string DebuggerDisplay { get diff --git a/Octokit/Models/Request/NewRepositoryWebHook.cs b/Octokit/Models/Request/NewRepositoryWebHook.cs new file mode 100644 index 0000000000..36d0183296 --- /dev/null +++ b/Octokit/Models/Request/NewRepositoryWebHook.cs @@ -0,0 +1,147 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace Octokit +{ + /// + /// Creates a Webhook for the repository. + /// + /// + /// To create a webhook, the following fields are required by the config: + /// + /// + /// url + /// A required string defining the URL to which the payloads will be delivered. + /// + /// + /// content_type + /// + /// An optional string defining the media type used to serialize the payloads. Supported values include json and + /// form. The default is form. + /// + /// + /// + /// secret + /// + /// An optional string that’s passed with the HTTP requests as an X-Hub-Signature header. The value of this + /// header is computed as the HMAC hex digest of the body, using the secret as the key. + /// + /// + /// + /// insecure_ssl: + /// + /// An optional string that determines whether the SSL certificate of the host for url will be verified when + /// delivering payloads. Supported values include "0" (verification is performed) and "1" (verification is not + /// performed). The default is "0". + /// + /// + /// + /// + /// API: https://developer.github.com/v3/repos/hooks/#create-a-hook + /// + /// + [DebuggerDisplay("{DebuggerDisplay,nq}")] + public class NewRepositoryWebHook : NewRepositoryHook + { + /// + /// Initializes a new instance of the class. + /// Using default values for ContentType, Secret and InsecureSsl. + /// + /// + /// Use "web" for a webhook or use the name of a valid service. (See + /// https://api.github.com/hooks for the list of valid service + /// names.) + /// + /// + /// Key/value pairs to provide settings for this hook. These settings vary between the services and are + /// defined in the github-services repository. Booleans are stored internally as “1” for true, and “0” for + /// false. Any true/false values will be converted automatically. + /// + /// + /// A required string defining the URL to which the payloads will be delivered. + /// + public NewRepositoryWebHook(string name, IReadOnlyDictionary config, string url) + : base(name, config) + { + Ensure.ArgumentNotNullOrEmptyString(url, "url"); + + Url = url; + ContentType = WebHookContentType.Form; + Secret = ""; + InsecureSsl = false; + } + + /// + /// Gets the URL of the hook to create. + /// + /// + /// The URL. + /// + public string Url { get; protected set; } + + /// + /// Gets the content type used to serialize the payload. The default is `form`. + /// + /// + /// The content type. + /// + public WebHookContentType ContentType { get; set; } + + /// + /// Gets the secret used as the key for the HMAC hex digest + /// of the body passed with the HTTP requests as an X-Hub-Signature header. + /// + /// + /// The secret. + /// + public string Secret { get; set; } + + /// + /// Gets whether the SSL certificate of the host will be verified when + /// delivering payloads. The default is `false`. + /// + /// + /// true if SSL certificate verification is not performed; + /// otherwise, false. + /// + public bool InsecureSsl { get; set; } + + public override NewRepositoryHook ToRequest() + { + var webHookConfig = GetWebHookConfig(); + if (Config.Any(c => webHookConfig.ContainsKey(c.Key))) + { + var invalidConfigs = Config.Where(c => webHookConfig.ContainsKey(c.Key)).Select(c => c.Key); + throw new RepositoryWebHookConfigException(invalidConfigs); + } + + var config = webHookConfig + .Union(Config, new WebHookConfigComparer()) + .ToDictionary(k => k.Key, v => v.Value); + + return new NewRepositoryHook(Name, config); + } + + Dictionary GetWebHookConfig() + { + return new Dictionary + { + { "url", Url }, + { "content_type", ContentType.ToParameter() }, + { "secret", Secret }, + { "insecure_ssl", InsecureSsl.ToString() } + }; + } + } + + /// + /// The supported content types for payload serialization. + /// + public enum WebHookContentType + { + Form, + Json + } + +} diff --git a/Octokit/Octokit-Mono.csproj b/Octokit/Octokit-Mono.csproj index 535992f9a6..fd3d9f2c6e 100644 --- a/Octokit/Octokit-Mono.csproj +++ b/Octokit/Octokit-Mono.csproj @@ -406,6 +406,9 @@ + + + \ No newline at end of file diff --git a/Octokit/Octokit-MonoAndroid.csproj b/Octokit/Octokit-MonoAndroid.csproj index b3cd6ca899..7a813d2cef 100644 --- a/Octokit/Octokit-MonoAndroid.csproj +++ b/Octokit/Octokit-MonoAndroid.csproj @@ -413,6 +413,9 @@ + + + diff --git a/Octokit/Octokit-Monotouch.csproj b/Octokit/Octokit-Monotouch.csproj index 1b7629f554..5eb79ac2e6 100644 --- a/Octokit/Octokit-Monotouch.csproj +++ b/Octokit/Octokit-Monotouch.csproj @@ -409,7 +409,10 @@ + + + - + \ No newline at end of file diff --git a/Octokit/Octokit-Portable.csproj b/Octokit/Octokit-Portable.csproj index da5eba1682..6757e1a656 100644 --- a/Octokit/Octokit-Portable.csproj +++ b/Octokit/Octokit-Portable.csproj @@ -403,6 +403,9 @@ + + + diff --git a/Octokit/Octokit-netcore45.csproj b/Octokit/Octokit-netcore45.csproj index caef09227c..d6a2fd84af 100644 --- a/Octokit/Octokit-netcore45.csproj +++ b/Octokit/Octokit-netcore45.csproj @@ -410,6 +410,9 @@ + + + diff --git a/Octokit/Octokit.csproj b/Octokit/Octokit.csproj index c5460f1f69..2c15e7535d 100644 --- a/Octokit/Octokit.csproj +++ b/Octokit/Octokit.csproj @@ -76,6 +76,7 @@ + @@ -84,6 +85,7 @@ + @@ -91,6 +93,7 @@ +