Skip to content

Commit

Permalink
Merge pull request #4129 from arturcic/fix/4125
Browse files Browse the repository at this point in the history
Fix help and version arguments on non git folder
  • Loading branch information
arturcic authored Jul 29, 2024
2 parents 5687fea + 88afda3 commit 2fe7669
Show file tree
Hide file tree
Showing 16 changed files with 139 additions and 38 deletions.
20 changes: 20 additions & 0 deletions src/.run/cli (help).run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="cli (help)" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.App/bin/Debug/net8.0/gitversion" />
<option name="PROGRAM_PARAMETERS" value="-help" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/../.." />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/GitVersion.App/GitVersion.App.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>
20 changes: 20 additions & 0 deletions src/.run/cli (showconfig).run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="cli (showconfig)" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.App/bin/Debug/net8.0/gitversion" />
<option name="PROGRAM_PARAMETERS" value="-showconfig" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/.." />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/GitVersion.App/GitVersion.App.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>
20 changes: 20 additions & 0 deletions src/.run/cli (version).run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="cli (version)" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.App/bin/Debug/net8.0/gitversion" />
<option name="PROGRAM_PARAMETERS" value="-version" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/../.." />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/GitVersion.App/GitVersion.App.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="0" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>
2 changes: 1 addition & 1 deletion src/.run/cli.run.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="cli" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.App/bin/Debug/net8.0/gitversion.exe" />
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.App/bin/Debug/net8.0/gitversion" />
<option name="PROGRAM_PARAMETERS" value="-nocache -l console" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/GitVersion.App/bin/Debug/net8.0" />
<option name="PASS_PARENT_ENVS" value="1" />
Expand Down
2 changes: 1 addition & 1 deletion src/.run/schema.run.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="schema" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.Schema/bin/Debug/net8.0/schema.exe" />
<option name="EXE_PATH" value="$PROJECT_DIR$/GitVersion.Schema/bin/Debug/net8.0/schema" />
<option name="PROGRAM_PARAMETERS" value="--OutputDirectory schemas --Version 6.0" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/.." />
<option name="PASS_PARENT_ENVS" value="1" />
Expand Down
12 changes: 11 additions & 1 deletion src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,23 @@ public void CheckBuildServerVerbosityConsole(string verbosityArg, string expecte
[Test]
public void WorkingDirectoryWithoutGitFolderFailsWithInformativeMessage()
{
var result = GitVersionHelper.ExecuteIn(SysEnv.SystemDirectory, null, false);
var result = GitVersionHelper.ExecuteIn(Path.GetTempPath(), null, false);

result.ExitCode.ShouldNotBe(0);
result.Output.ShouldNotBeNull();
result.Output.ShouldContain("Cannot find the .git directory");
}

[TestCase(" -help")]
[TestCase(" -version")]
public void WorkingDirectoryWithoutGitFolderDoesNotFailForVersionAndHelp(string argument)
{
var result = GitVersionHelper.ExecuteIn(workingDirectory: null, arguments: argument);

result.ExitCode.ShouldBe(0);
result.Output.ShouldNotBeNull();
}

[Test]
public void WorkingDirectoryWithoutCommitsFailsWithInformativeMessage()
{
Expand Down
13 changes: 8 additions & 5 deletions src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ namespace GitVersion.App.Tests;

public class ArgumentBuilder
{
public ArgumentBuilder(string workingDirectory) => this.WorkingDirectory = workingDirectory;
public ArgumentBuilder(string? workingDirectory) => this.WorkingDirectory = workingDirectory;

public ArgumentBuilder(string workingDirectory, string? exec, string? execArgs, string? projectFile, string? projectArgs, string? logFile)
public ArgumentBuilder(string? workingDirectory, string? exec, string? execArgs, string? projectFile, string? projectArgs, string? logFile)
{
this.WorkingDirectory = workingDirectory;
this.exec = exec;
Expand All @@ -16,22 +16,25 @@ public ArgumentBuilder(string workingDirectory, string? exec, string? execArgs,
this.LogFile = logFile;
}

public ArgumentBuilder(string workingDirectory, string? additionalArguments, string? logFile)
public ArgumentBuilder(string? workingDirectory, string? additionalArguments, string? logFile)
{
this.WorkingDirectory = workingDirectory;
this.additionalArguments = additionalArguments;
this.LogFile = logFile;
}

public string WorkingDirectory { get; }
public string? WorkingDirectory { get; }

public string? LogFile { get; }

public override string ToString()
{
var arguments = new StringBuilder();

arguments.Append(" /targetpath \"").Append(this.WorkingDirectory).Append('\"');
if (!this.WorkingDirectory.IsNullOrWhiteSpace())
{
arguments.Append(" /targetpath \"").Append(this.WorkingDirectory).Append('\"');
}

if (!this.exec.IsNullOrWhiteSpace())
{
Expand Down
10 changes: 6 additions & 4 deletions src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace GitVersion.App.Tests;

public static class GitVersionHelper
{
public static ExecutionResults ExecuteIn(string workingDirectory,
public static ExecutionResults ExecuteIn(string? workingDirectory,
string? exec = null,
string? execArgs = null,
string? projectFile = null,
Expand All @@ -22,12 +22,12 @@ public static ExecutionResults ExecuteIn(string workingDirectory,
}

public static ExecutionResults ExecuteIn(
string workingDirectory,
string? workingDirectory,
string? arguments,
bool logToFile = true,
params KeyValuePair<string, string?>[] environments)
{
var logFile = logToFile ? PathHelper.Combine(workingDirectory, "log.txt") : null;
var logFile = workingDirectory is not null && logToFile ? PathHelper.Combine(workingDirectory, "log.txt") : null;
var args = new ArgumentBuilder(workingDirectory, arguments, logFile);
return ExecuteIn(args, environments);
}
Expand Down Expand Up @@ -64,13 +64,15 @@ private static ExecutionResults ExecuteIn(ArgumentBuilder arguments,
Console.WriteLine("Executing: {0} {1}", executable, args);
Console.WriteLine();

var workingDirectory = arguments.WorkingDirectory ?? PathHelper.GetCurrentDirectory();

exitCode = ProcessHelper.Run(
s => output.AppendLine(s),
s => output.AppendLine(s),
null,
executable,
args,
arguments.WorkingDirectory,
workingDirectory,
[.. environmentalVariables]);
}
catch (Exception exception)
Expand Down
12 changes: 8 additions & 4 deletions src/GitVersion.App/GitVersionExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,29 @@ namespace GitVersion;
internal class GitVersionExecutor(
ILog log,
IConsole console,
IVersionWriter versionWriter,
IHelpWriter helpWriter,
IConfigurationFileLocator configurationFileLocator,
IConfigurationProvider configurationProvider,
IConfigurationSerializer configurationSerializer,
IGitVersionCalculateTool gitVersionCalculateTool,
IGitVersionOutputTool gitVersionOutputTool,
IVersionWriter versionWriter,
IHelpWriter helpWriter,
IGitRepository gitRepository,
IGitRepositoryInfo repositoryInfo)
: IGitVersionExecutor
{
private readonly ILog log = log.NotNull();
private readonly IConsole console = console.NotNull();
private readonly IVersionWriter versionWriter = versionWriter.NotNull();
private readonly IHelpWriter helpWriter = helpWriter.NotNull();

private readonly IConfigurationFileLocator configurationFileLocator = configurationFileLocator.NotNull();
private readonly IConfigurationProvider configurationProvider = configurationProvider.NotNull();
private readonly IConfigurationSerializer configurationSerializer = configurationSerializer.NotNull();

private readonly IGitVersionCalculateTool gitVersionCalculateTool = gitVersionCalculateTool.NotNull();
private readonly IGitVersionOutputTool gitVersionOutputTool = gitVersionOutputTool.NotNull();
private readonly IVersionWriter versionWriter = versionWriter.NotNull();
private readonly IHelpWriter helpWriter = helpWriter.NotNull();
private readonly IGitRepository gitRepository = gitRepository.NotNull();
private readonly IGitRepositoryInfo repositoryInfo = repositoryInfo.NotNull();

public int Execute(GitVersionOptions gitVersionOptions)
Expand All @@ -49,6 +52,7 @@ public int Execute(GitVersionOptions gitVersionOptions)

private int RunGitVersionTool(GitVersionOptions gitVersionOptions)
{
this.gitRepository.DiscoverRepository(gitVersionOptions.WorkingDirectory);
var mutexName = this.repositoryInfo.DotGitDirectory?.Replace(Path.DirectorySeparatorChar.ToString(), "") ?? string.Empty;
using var mutex = new Mutex(true, $@"Global\gitversion{mutexName}", out var acquired);

Expand Down
2 changes: 2 additions & 0 deletions src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran

var sp = ConfigureServices(services => services.AddSingleton(options));

sp.DiscoverRepository();

var gitPreparer = sp.GetRequiredService<IGitPreparer>();
gitPreparer.Prepare();

Expand Down
15 changes: 15 additions & 0 deletions src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public void CacheKeySameAfterReNormalizing()

this.sp = GetServiceProvider(gitVersionOptions, environment: environment);

sp.DiscoverRepository();

var preparer = this.sp.GetRequiredService<IGitPreparer>();

preparer.Prepare();
Expand Down Expand Up @@ -78,6 +80,8 @@ public void CacheKeyForWorktree()

this.sp = GetServiceProvider(gitVersionOptions);

sp.DiscoverRepository();

var preparer = this.sp.GetRequiredService<IGitPreparer>();
preparer.Prepare();
var cacheKeyFactory = this.sp.GetRequiredService<IGitVersionCacheKeyFactory>();
Expand Down Expand Up @@ -516,6 +520,9 @@ public void CalculateVersionVariables_TwoBranchHasSameCommitHeadDetachedAndNotTa
environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, "true");

this.sp = GetServiceProvider(gitVersionOptions, environment: environment);

sp.DiscoverRepository();

var sut = sp.GetRequiredService<IGitVersionCalculateTool>();

// Execute & Verify
Expand Down Expand Up @@ -543,6 +550,9 @@ public void CalculateVersionVariables_TwoBranchHasSameCommitHeadDetachedAndTagge
environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, "true");

this.sp = GetServiceProvider(gitVersionOptions, environment: environment);

sp.DiscoverRepository();

var sut = sp.GetRequiredService<IGitVersionCalculateTool>();

// Execute
Expand All @@ -568,6 +578,9 @@ public void CalculateVersionVariables_ShallowFetch_ThrowException()
environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, "true");

this.sp = GetServiceProvider(gitVersionOptions, environment: environment);

sp.DiscoverRepository();

var sut = sp.GetRequiredService<IGitVersionCalculateTool>();

// Execute & Verify
Expand All @@ -583,6 +596,8 @@ private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVe
this.log = this.sp.GetRequiredService<ILog>();
this.gitVersionCacheProvider = (GitVersionCacheProvider)this.sp.GetRequiredService<IGitVersionCacheProvider>();

sp.DiscoverRepository();

return this.sp.GetRequiredService<IGitVersionCalculateTool>();
}

Expand Down
10 changes: 10 additions & 0 deletions src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ public static IBranch CreateMockBranch(string name, params ICommit[] commits)
return branch;
}

public static void DiscoverRepository(this IServiceProvider sp)
{
var gitRepository = sp.GetRequiredService<IGitRepository>();
var gitRepositoryInfo = sp.GetRequiredService<IGitRepositoryInfo>();
gitRepository.DiscoverRepository(gitRepositoryInfo.GitRootPath);
}

public static IBranch FindBranch(this IGitRepository repository, string branchName)
=> repository.Branches.FirstOrDefault(branch => branch.Name.WithoutOrigin == branchName)
?? throw new GitVersionException($"Branch {branchName} not found");
Expand Down Expand Up @@ -84,6 +91,9 @@ public static GitVersionVariables GetVersion(this RepositoryFixtureBase fixture,
services.AddSingleton(options);
services.AddSingleton(configurationProviderMock);
});

sp.DiscoverRepository();

var variableProvider = sp.GetRequiredService<IVariableProvider>();
var nextVersionCalculator = sp.GetRequiredService<INextVersionCalculator>();
var contextOptions = sp.GetRequiredService<Lazy<GitVersionContext>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ public void GivenARemoteGitRepositoryWithCommitsAndBranchesThenClonedLocalShould
services.AddSingleton<IEnvironment>(environment);
});

sp.DiscoverRepository();

var gitPreparer = sp.GetRequiredService<IGitPreparer>();

gitPreparer.Prepare();
Expand Down
16 changes: 9 additions & 7 deletions src/GitVersion.LibGit2Sharp/Git/GitRepository.extended.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ namespace GitVersion.Git;

internal partial class GitRepository(ILog log) : IMutatingGitRepository
{
private readonly ILog log = log.NotNull();

public void Clone(string? sourceUrl, string? workdirPath, AuthenticationInfo auth)
{
try
{
var path = Repository.Clone(sourceUrl, workdirPath, GetCloneOptions(auth));
log.Info($"Returned path after repository clone: {path}");
this.log.Info($"Returned path after repository clone: {path}");
}
catch (LibGit2Sharp.LockedFileException ex)
{
Expand Down Expand Up @@ -48,7 +50,7 @@ public void Fetch(string remote, IEnumerable<string> refSpecs, AuthenticationInf
Commands.Fetch((Repository)RepositoryInstance, remote, refSpecs, GetFetchOptions(auth), logMessage));
public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) => RepositoryExtensions.RunSafe(() =>
{
log.Info("Fetching remote refs to see if there is a pull request ref");
this.log.Info("Fetching remote refs to see if there is a pull request ref");
// FIX ME: What to do when Tip is null?
if (Head.Tip == null)
Expand All @@ -59,21 +61,21 @@ public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) => Reposit
var reference = GetPullRequestReference(auth, remote, headTipSha);
var canonicalName = reference.CanonicalName;
var referenceName = ReferenceName.Parse(reference.CanonicalName);
log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'.");
this.log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'.");
if (referenceName.IsTag)
{
log.Info($"Checking out tag '{canonicalName}'");
this.log.Info($"Checking out tag '{canonicalName}'");
Checkout(reference.Target.Sha);
}
else if (referenceName.IsPullRequest)
{
var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/");
log.Info($"Creating fake local branch '{fakeBranchName}'.");
this.log.Info($"Creating fake local branch '{fakeBranchName}'.");
Refs.Add(fakeBranchName, headTipSha);
log.Info($"Checking local branch '{fakeBranchName}' out.");
this.log.Info($"Checking local branch '{fakeBranchName}' out.");
Checkout(fakeBranchName);
}
else
Expand All @@ -91,7 +93,7 @@ private DirectReference GetPullRequestReference(AuthenticationInfo auth, LibGit2
: network.ListReferences(remote))
.Select(r => r.ResolveToDirectReference()).ToList();

log.Info($"Remote Refs:{PathHelper.NewLine}" + string.Join(PathHelper.NewLine, remoteTips.Select(r => r.CanonicalName)));
this.log.Info($"Remote Refs:{PathHelper.NewLine}" + string.Join(PathHelper.NewLine, remoteTips.Select(r => r.CanonicalName)));
var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList();

switch (refs.Count)
Expand Down
Loading

0 comments on commit 2fe7669

Please sign in to comment.