Skip to content

Commit

Permalink
Look in packed-refs if the ref file cannot be found, and validate the…
Browse files Browse the repository at this point in the history
… found hash
  • Loading branch information
cdhowie committed Nov 20, 2012
1 parent 0b2b228 commit c038a0e
Showing 1 changed file with 45 additions and 6 deletions.
51 changes: 45 additions & 6 deletions Cdh.Toolkit.BuildTasks/WriteGitCommit.cs
Expand Up @@ -28,6 +28,7 @@
using Microsoft.Build.Utilities; using Microsoft.Build.Utilities;
using Microsoft.Build.Framework; using Microsoft.Build.Framework;
using System.IO; using System.IO;
using System.Text.RegularExpressions;


namespace Cdh.Toolkit.BuildTasks namespace Cdh.Toolkit.BuildTasks
{ {
Expand All @@ -43,18 +44,56 @@ public WriteGitCommit()
OutputFile = "git-commit"; OutputFile = "git-commit";
} }


private static readonly Regex validationRegex = new Regex(@"^[0-9a-f]{40}$");

public override bool Execute() public override bool Execute()
{ {
using (var outputFile = File.CreateText(OutputFile)) { using (var outputFile = File.CreateText(OutputFile)) {
string head; string headRef;
using (var headFile = File.OpenText(Path.Combine(Repository, "HEAD"))) using (var headFile = File.OpenText(Path.Combine(Repository, "HEAD")))
head = headFile.ReadLine(); headRef = headFile.ReadLine();


if (head.StartsWith("ref: ")) { string head;
string refPath = head.Substring(5).Replace('/', Path.DirectorySeparatorChar);
if (headRef.StartsWith("ref: ")) {
string refPath = headRef.Substring(5);
string refFilePath = refPath.Replace('/', Path.DirectorySeparatorChar);

try {
using (var refFile = File.OpenText(Path.Combine(Repository, refFilePath)))
head = refFile.ReadLine();
} catch (FileNotFoundException) {
// Maybe the ref is packed?

using (var packedRef = File.OpenText(Path.Combine(Repository, "packed-refs"))) {
string line;

head = null;

while ((line = packedRef.ReadLine()) != null) {
if (line.StartsWith("#")) {
continue;
}

var parts = line.Split(new[] { ' ' }, 2);

if (parts.Length == 2 && refPath.Equals(parts[1])) {
head = parts[0];
break;
}
}

if (head == null) {
throw new ApplicationException(string.Format("Unable to find ref {0} in packed refs.", headRef));
}
}
}
} else {
head = headRef;
}


using (var refFile = File.OpenText(Path.Combine(Repository, refPath))) if (!validationRegex.IsMatch(head)) {
head = refFile.ReadLine(); throw new ApplicationException(string.Format("Located commit ID \"{0}\" is not valid.", head));
} }


outputFile.Write(head); outputFile.Write(head);
Expand Down

0 comments on commit c038a0e

Please sign in to comment.