Added validation when creating reference

This commit is contained in:
Kristian Hellang
2013-11-25 22:22:31 +01:00
parent 09dc5edc27
commit 0d0cf18b2e
3 changed files with 53 additions and 4 deletions
+25
View File
@@ -0,0 +1,25 @@
using System;
using Octokit;
using Xunit;
public class NewReferenceTests
{
public class TheCtor
{
[Fact]
public void EnforcesRefsPrefix()
{
var create = new NewReference("heads/develop", "sha");
Assert.Equal(create.Ref, "refs/heads/develop");
}
[Fact]
public void ThrowsExceptionIfRefHasLessThanTwoSlashes()
{
Assert.Throws<FormatException>(() => new NewReference("refs/develop", "sha"));
}
}
}
+1
View File
@@ -111,6 +111,7 @@
<Compile Include="Http\ResponseTests.cs" />
<Compile Include="Http\RequestTests.cs" />
<Compile Include="Models\CommitTests.cs" />
<Compile Include="Models\NewReferenceTests.cs" />
<Compile Include="Models\MilestoneRequestTests.cs" />
<Compile Include="Models\IssueRequestTests.cs" />
<Compile Include="Models\ModelExtensionsTests.cs" />
+27 -4
View File
@@ -1,17 +1,40 @@
namespace Octokit
using System;
using System.Linq;
namespace Octokit
{
public class NewReference
{
public NewReference(string @ref, string sha)
const string _refsPrefix = "refs";
public NewReference(string reference, string sha)
{
Ensure.ArgumentNotNullOrEmptyString(@ref, "ref");
Ensure.ArgumentNotNullOrEmptyString(reference, "ref");
Ensure.ArgumentNotNullOrEmptyString(sha, "sha");
Ref = @ref;
Ref = GetReference(reference);
Sha = sha;
}
public string Ref { get; private set; }
public string Sha { get; private set; }
static string GetReference(string reference)
{
var parts = reference.Split('/').ToList();
var refsPart = parts.FirstOrDefault();
if (refsPart != null && refsPart != _refsPrefix)
{
parts.Insert(0, _refsPrefix);
}
if (parts.Count < 3)
{
throw new FormatException("Reference must start with 'refs' and have at least two slashes.");
}
return string.Join("/", parts);
}
}
}