Skip to content
This repository was archived by the owner on Jun 27, 2019. It is now read-only.

Added extensions methods #2

Merged
merged 6 commits into from
Apr 20, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/GitTools.Core.Tests/Extensions/StringExtensionsFacts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace GitTools.Tests
{
using NUnit.Framework;
using Shouldly;

[TestFixture]
public class StringExtensionsFacts
{
[TestCase("/develop", false)]
[TestCase("/master", false)]
[TestCase("/pr/25", true)]
[TestCase("/pull/25", true)]
[TestCase("/pull-requests/25", true)]
public void TheIsPullRequestMethod(string input, bool expectedValue)
{
var actualValue = input.IsPullRequest();

actualValue.ShouldBe(expectedValue);
}
}
}
6 changes: 6 additions & 0 deletions src/GitTools.Core.Tests/GitTools.Core.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@
<HintPath>..\..\lib\NUnit.2.6.4\lib\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Shouldly, Version=2.5.0.0, Culture=neutral, PublicKeyToken=6042cbcb05cbc941, processorArchitecture=MSIL">
<HintPath>..\..\lib\Shouldly.2.5.0\lib\net40\Shouldly.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
Expand All @@ -54,6 +58,7 @@
<Compile Include="ArgumentParserFacts.cs" />
<Compile Include="ContextFacts.cs" />
<Compile Include="Context\Context.cs" />
<Compile Include="Extensions\StringExtensionsFacts.cs" />
<Compile Include="GlobalInitialization.cs" />
<Compile Include="ModuleInitializer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
Expand All @@ -70,6 +75,7 @@
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\lib\Fody.1.28.3\build\Fody.targets" Condition="Exists('..\..\lib\Fody.1.28.3\build\Fody.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
Expand Down
1 change: 1 addition & 0 deletions src/GitTools.Core.Tests/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
<package id="Fody" version="1.28.3" targetFramework="net45" developmentDependency="true" />
<package id="ModuleInit.Fody" version="1.5.6.0" targetFramework="net45" developmentDependency="true" />
<package id="NUnit" version="2.6.4" targetFramework="net45" />
<package id="Shouldly" version="2.5.0" targetFramework="net45" />
</packages>
2 changes: 1 addition & 1 deletion src/GitTools.Core/Constants.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace GitTools
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing namespace?

{
// TODO: Constants go here
// TODO: constants classes go here
}
75 changes: 75 additions & 0 deletions src/GitTools.Core/Extensions/LibGitExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,91 @@
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp;
using Logging;

public static class LibGitExtensions
{
private static readonly ILog Log = LogProvider.GetCurrentClassLogger();

public static DateTimeOffset When(this Commit commit)
{
return commit.Committer.When;
}

public static Branch FindBranch(this IRepository repository, string branchName)
{
var exact = repository.Branches.FirstOrDefault(x => x.Name == branchName);
if (exact != null)
{
return exact;
}

return repository.Branches.FirstOrDefault(x => x.Name == "origin/" + branchName);
}

public static bool IsDetachedHead(this Branch branch)
{
return branch.CanonicalName.Equals("(no branch)", StringComparison.OrdinalIgnoreCase);
}

public static string GetRepositoryDirectory(this IRepository repository, bool omitGitPostFix = true)
{
var gitDirectory = repository.Info.Path;

gitDirectory = gitDirectory.TrimEnd('\\');

if (omitGitPostFix && gitDirectory.EndsWith(".git"))
{
gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length);
gitDirectory = gitDirectory.TrimEnd('\\');
}

return gitDirectory;
}

public static void CheckoutFilesIfExist(this IRepository repository, params string[] fileNames)
{
if (fileNames == null || fileNames.Length == 0)
{
return;
}

Log.Info("Checking out files that might be needed later in dynamic repository");

foreach (var fileName in fileNames)
{
try
{
Log.Info(" Trying to check out '{0}'", fileName);

var headBranch = repository.Head;
var tip = headBranch.Tip;

var treeEntry = tip[fileName];
if (treeEntry == null)
{
continue;
}

var fullPath = Path.Combine(repository.GetRepositoryDirectory(), fileName);
using (var stream = ((Blob) treeEntry.Target).GetContentStream())
{
using (var streamReader = new BinaryReader(stream))
{
File.WriteAllBytes(fullPath, streamReader.ReadBytes((int)stream.Length));
}
}
}
catch (Exception ex)
{
Log.Warning(" An error occurred while checking out '{0}': '{1}'", fileName, ex.Message);
}
}
}

public static IEnumerable<Branch> GetBranchesContainingCommit(this IRepository repository, string commitSha)
{
var directBranchHasBeenFound = false;
Expand Down
15 changes: 15 additions & 0 deletions src/GitTools.Core/Extensions/StringBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace GitTools
{
using System.Text;
using JetBrains.Annotations;

public static class StringBuilderExtensions
{
[StringFormatMethod("format")]
public static void AppendLineFormat(this StringBuilder stringBuilder, string format, params object[] args)
{
stringBuilder.AppendFormat(format, args);
stringBuilder.AppendLine();
}
}
}
5 changes: 3 additions & 2 deletions src/GitTools.Core/FodyWeavers.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
LibGit2Sharp
</IncludeAssemblies>
</Costura>
<ModuleInit/>
<MethodTimer/>
<ModuleInit />
<MethodTimer />
<JetBrainsAnnotations />
</Weavers>
11 changes: 11 additions & 0 deletions src/GitTools.Core/GitTools.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
<DocumentationFile>..\..\output\release\GitTools.Core\GitTools.Core.XML</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="JetBrains.Annotations, Version=8.1.11.55, Culture=neutral, PublicKeyToken=1010a0d8d6380325, processorArchitecture=MSIL">
<HintPath>..\..\lib\JetBrainsAnnotations.Fody.1.0.2\Lib\JetBrains.Annotations.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="LibGit2Sharp, Version=0.21.0.176, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\lib\LibGit2Sharp.0.21.0.176\lib\net40\LibGit2Sharp.dll</HintPath>
<Private>True</Private>
Expand All @@ -60,6 +64,7 @@
</Compile>
<Compile Include="App_Packages\LibLog.4.2\LibLog.cs" />
<Compile Include="Constants.cs" />
<Compile Include="Testing\TestValues.cs" />
<Compile Include="Context\ContextBase.cs" />
<Compile Include="Context\Interfaces\IAuthenticationContext.cs" />
<Compile Include="Context\Interfaces\IContext.cs" />
Expand All @@ -68,17 +73,23 @@
<Compile Include="Exceptions\GitToolsException.cs" />
<Compile Include="Extensions\IntExtensions.cs" />
<Compile Include="Extensions\LibGitExtensions.cs" />
<Compile Include="Extensions\StringBuilderExtensions.cs" />
<Compile Include="Extensions\StringExtensions.cs" />
<Compile Include="Git\GitDirFinder.cs" />
<Compile Include="Git\GitPreparer.cs" />
<Compile Include="Git\Interfaces\IRepositoryPreparer.cs" />
<Compile Include="Git\RepositoryLoader.cs" />
<Compile Include="Helpers\DeleteHelper.cs" />
<Compile Include="Helpers\GitHelper.cs" />
<Compile Include="Helpers\ProcessHelper.cs" />
<Compile Include="IO\TemporaryFilesContext.cs" />
<Compile Include="Logging\Extensions\LogExtensions.cs" />
<Compile Include="ModuleInitializer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Testing\Extensions\GitTestExtensions.cs" />
<Compile Include="Testing\Fixtures\EmptyRepositoryFixture.cs" />
<Compile Include="Testing\Fixtures\RemoteRepositoryFixture.cs" />
<Compile Include="Testing\Fixtures\RepositoryFixtureBase.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\..\lib\LibGit2Sharp.0.21.0.176\lib\net40\NativeBinaries\amd64\git2-e0902fb.dll">
Expand Down
144 changes: 144 additions & 0 deletions src/GitTools.Core/Helpers/ProcessHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
namespace GitTools
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

public static class ProcessHelper
{
private static volatile object _lockObject = new object();

// http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3
public static Process Start(ProcessStartInfo startInfo)
{
Process process;

lock (_lockObject)
{
using (new ChangeErrorMode(ErrorModes.FailCriticalErrors | ErrorModes.NoGpFaultErrorBox))
{
process = Process.Start(startInfo);
process.PriorityClass = ProcessPriorityClass.Idle;
}
}

return process;
}

// http://csharptest.net/532/using-processstart-to-capture-console-output/
public static int Run(Action<string> output, Action<string> errorOutput, TextReader input, string exe, string args, string workingDirectory, params KeyValuePair<string, string>[] environmentalVariables)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should be using threads to read this. I should add an issue to fix this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably. I just copy/pasted this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, not for this PR anyways. Just a note to myself really

{
if (String.IsNullOrEmpty(exe))
{
throw new FileNotFoundException();
}

if (output == null)
{
throw new ArgumentNullException("output");
}

var psi = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
ErrorDialog = false,
WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory,
FileName = exe,
Arguments = args
};

foreach (var environmentalVariable in environmentalVariables)
{
if (!psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key) && environmentalVariable.Value != null)
psi.EnvironmentVariables.Add(environmentalVariable.Key, environmentalVariable.Value);
if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key) && environmentalVariable.Value == null)
psi.EnvironmentVariables.Remove(environmentalVariable.Key);
}

using (var process = Process.Start(psi))
{
using (var mreOut = new ManualResetEvent(false))
{
using (var mreErr = new ManualResetEvent(false))
{
process.EnableRaisingEvents = true;
process.OutputDataReceived += (o, e) =>
{
// ReSharper disable once AccessToDisposedClosure
if (e.Data == null)
{
mreOut.Set();
}
else
{
output(e.Data);
}
};
process.BeginOutputReadLine();
process.ErrorDataReceived += (o, e) =>
{
// ReSharper disable once AccessToDisposedClosure
if (e.Data == null)
{
mreErr.Set();
}
else
{
errorOutput(e.Data);
}
};

process.BeginErrorReadLine();

string line;
while (input != null && null != (line = input.ReadLine()))
{
process.StandardInput.WriteLine(line);
}

process.StandardInput.Close();
process.WaitForExit();

mreOut.WaitOne();
mreErr.WaitOne();

return process.ExitCode;
}
}
}
}

[Flags]
public enum ErrorModes
{
Default = 0x0,
FailCriticalErrors = 0x1,
NoGpFaultErrorBox = 0x2,
NoAlignmentFaultExcept = 0x4,
NoOpenFileErrorBox = 0x8000
}

public struct ChangeErrorMode : IDisposable
{
private readonly int _oldMode;

public ChangeErrorMode(ErrorModes mode)
{
_oldMode = SetErrorMode((int)mode);
}

void IDisposable.Dispose() { SetErrorMode(_oldMode); }

[DllImport("kernel32.dll")]
static extern int SetErrorMode(int newMode);
}
}
}
Loading