Skip to content

Commit

Permalink
Refactor ProcessHelper and PathHelper classes
Browse files Browse the repository at this point in the history
The ProcessHelper and PathHelper classes have been refactored to align with proper visibility levels and aliased "System.Environment.Newline" to "PathHelper.Newline". Their corresponding usages throughout the project have also been updated. Additionally, redundant code has been removed with this change.
  • Loading branch information
arturcic committed Nov 6, 2023
1 parent 37e6daa commit 2b6bca0
Show file tree
Hide file tree
Showing 46 changed files with 102 additions and 289 deletions.
1 change: 1 addition & 0 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
<Using Include="System.Text.Json"/>
<Using Include="System.Text.Json.Serialization"/>
<Using Include="System.Xml"/>
<Using Include="System.Environment" Alias="SysEnv"/>
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.App.Tests/ArgumentParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public void SetUp()
public void EmptyMeansUseCurrentDirectory()
{
var arguments = this.argumentParser.ParseArguments("");
arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory);
arguments.TargetPath.ShouldBe(SysEnv.CurrentDirectory);
arguments.LogFilePath.ShouldBe(null);
arguments.IsHelp.ShouldBe(false);
}
Expand All @@ -48,7 +48,7 @@ public void SingleMeansUseAsTargetDirectory()
public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory()
{
var arguments = this.argumentParser.ParseArguments("-l logFilePath");
arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory);
arguments.TargetPath.ShouldBe(SysEnv.CurrentDirectory);
arguments.LogFilePath.ShouldBe("logFilePath");
arguments.IsHelp.ShouldBe(false);
}
Expand Down
6 changes: 3 additions & 3 deletions src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void CheckBuildServerVerbosityConsole(string verbosityArg, string expecte
[Test]
public void WorkingDirectoryWithoutGitFolderFailsWithInformativeMessage()
{
var result = GitVersionHelper.ExecuteIn(System.Environment.SystemDirectory, null, false);
var result = GitVersionHelper.ExecuteIn(SysEnv.SystemDirectory, null, false);

result.ExitCode.ShouldNotBe(0);
result.Output.ShouldContain("Cannot find the .git directory");
Expand All @@ -69,7 +69,7 @@ public void WorkingDirectoryWithoutCommitsFailsWithInformativeMessage()
[Test]
public void WorkingDirectoryDoesNotExistFailsWithInformativeMessage()
{
var workingDirectory = PathHelper.Combine(ExecutableHelper.GetCurrentDirectory(), Guid.NewGuid().ToString("N"));
var workingDirectory = PathHelper.Combine(PathHelper.GetCurrentDirectory(), Guid.NewGuid().ToString("N"));
var executable = ExecutableHelper.GetDotNetExecutable();

var output = new StringBuilder();
Expand All @@ -81,7 +81,7 @@ public void WorkingDirectoryDoesNotExistFailsWithInformativeMessage()
null,
executable,
args,
ExecutableHelper.GetCurrentDirectory());
PathHelper.GetCurrentDirectory());

exitCode.ShouldNotBe(0);
var outputString = output.ToString();
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.App.Tests/Helpers/ProgramFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public async Task<ProgramFixtureResult> Run(params string[] args)

return new ProgramFixtureResult
{
ExitCode = System.Environment.ExitCode,
ExitCode = SysEnv.ExitCode,
Output = this.output.Value,
Log = this.logger.Value
};
Expand Down
3 changes: 2 additions & 1 deletion src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using GitVersion.Agents;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Output;
using LibGit2Sharp;

Expand Down Expand Up @@ -142,7 +143,7 @@ public async Task VerifyBitBucketPipelinesPullRequest(string pullRequestRef)
private static async Task VerifyPullRequestVersionIsCalculatedProperly(string pullRequestRef, Dictionary<string, string> env)
{
using var fixture = new EmptyRepositoryFixture("main");
var remoteRepositoryPath = ExecutableHelper.GetTempPath();
var remoteRepositoryPath = PathHelper.GetTempPath();
RepositoryFixtureBase.Init(remoteRepositoryPath, "main");
using (var remoteRepository = new Repository(remoteRepositoryPath))
{
Expand Down
3 changes: 2 additions & 1 deletion src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using GitVersion.Agents;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Helpers;
using LibGit2Sharp;

namespace GitVersion.App.Tests;
Expand Down Expand Up @@ -34,7 +35,7 @@ public async Task VerifyTagCheckoutOnGitHubActions()
private static async Task VerifyTagCheckoutVersionIsCalculatedProperly(Dictionary<string, string> env)
{
using var fixture = new EmptyRepositoryFixture("main");
var remoteRepositoryPath = ExecutableHelper.GetTempPath();
var remoteRepositoryPath = PathHelper.GetTempPath();
RepositoryFixtureBase.Init(remoteRepositoryPath, "main");
using (var remoteRepository = new Repository(remoteRepositoryPath))
{
Expand Down
8 changes: 4 additions & 4 deletions src/GitVersion.App/ArgumentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public Arguments ParseArguments(string[] commandLineArguments)
{
var args = new Arguments
{
TargetPath = System.Environment.CurrentDirectory
TargetPath = SysEnv.CurrentDirectory
};

args.Output.Add(OutputType.Json);
Expand All @@ -54,7 +54,7 @@ public Arguments ParseArguments(string[] commandLineArguments)
{
return new Arguments
{
TargetPath = System.Environment.CurrentDirectory,
TargetPath = SysEnv.CurrentDirectory,
Init = true
};
}
Expand Down Expand Up @@ -99,7 +99,7 @@ public Arguments ParseArguments(string[] commandLineArguments)
// If the first argument is a switch, it should already have been consumed in the above loop,
// or else a WarningException should have been thrown and we wouldn't end up here.
arguments.TargetPath ??= firstArgumentIsSwitch
? System.Environment.CurrentDirectory
? SysEnv.CurrentDirectory
: firstArgument;

arguments.TargetPath = arguments.TargetPath.TrimEnd('/', '\\');
Expand Down Expand Up @@ -388,7 +388,7 @@ private static void ParseShowVariable(Arguments arguments, string? value, string

if (versionVariable == null)
{
var message = $"{name} requires a valid version variable. Available variables are:{System.Environment.NewLine}" +
var message = $"{name} requires a valid version variable. Available variables are:{PathHelper.NewLine}" +
string.Join(", ", availableVariables.Select(x => string.Concat("'", x, "'")));
throw new WarningException(message);
}
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.App/GitVersionApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ public Task StartAsync(CancellationToken cancellationToken)
{
var gitVersionOptions = this.options.Value;
this.log.Verbosity = gitVersionOptions.Verbosity;
System.Environment.ExitCode = this.gitVersionExecutor.Execute(gitVersionOptions);
SysEnv.ExitCode = this.gitVersionExecutor.Execute(gitVersionOptions);
}
catch (Exception exception)
{
Console.Error.WriteLine(exception.Message);
System.Environment.ExitCode = 1;
SysEnv.ExitCode = 1;
}

this.applicationLifetime.StopApplication();
Expand Down
5 changes: 3 additions & 2 deletions src/GitVersion.App/GitVersionExecutor.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using GitVersion.Configuration;
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion;
Expand Down Expand Up @@ -72,13 +73,13 @@ private int RunGitVersionTool(GitVersionOptions gitVersionOptions)
}
catch (WarningException exception)
{
var error = $"An error occurred:{System.Environment.NewLine}{exception.Message}";
var error = $"An error occurred:{PathHelper.NewLine}{exception.Message}";
this.log.Warning(error);
return 1;
}
catch (Exception exception)
{
var error = $"An unexpected error occurred:{System.Environment.NewLine}{exception}";
var error = $"An unexpected error occurred:{PathHelper.NewLine}{exception}";
this.log.Error(error);

this.log.Info("Attempting to show the current git graph (please include in issue): ");
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.App/HelpWriter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion;
Expand All @@ -23,8 +24,7 @@ public void WriteTo(Action<string> writeAction)
this.versionWriter.WriteTo(assembly, v => version = v);

var args = ArgumentList();
var nl = System.Environment.NewLine;
var message = "GitVersion " + version + nl + nl + args;
var message = $"GitVersion {version}{PathHelper.NewLine}{PathHelper.NewLine}{args}";

writeAction(message);
}
Expand Down
5 changes: 3 additions & 2 deletions src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Core.Tests.Helpers;
using GitVersion.Helpers;
using Microsoft.Extensions.DependencyInjection;

namespace GitVersion.Agents.Tests;
Expand Down Expand Up @@ -136,8 +137,8 @@ public void ShouldWriteIntegration()
// Assert
var expected = new List<string> { "Executing GenerateSetVersionMessage for 'GitHubActions'.", "", "Executing GenerateBuildLogOutput for 'GitHubActions'.", "Writing version variables to $GITHUB_ENV file for 'GitHubActions'." };

string.Join(Environment.NewLine, list)
.ShouldBe(string.Join(Environment.NewLine, expected));
string.Join(PathHelper.NewLine, list)
.ShouldBe(string.Join(PathHelper.NewLine, expected));

var expectedFileContents = new List<string> { "GitVersion_Major=1.0.0" };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void RegexIsRequired()
label: bugfix";
SetupConfigFileContent(text);
var ex = Should.Throw<ConfigurationException>(() => this.configurationProvider.ProvideForDirectory(this.repoPath));
ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{System.Environment.NewLine}" +
ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{PathHelper.NewLine}" +
"See https://gitversion.net/docs/reference/configuration for more info");
}

Expand All @@ -96,7 +96,7 @@ public void SourceBranchesValidationShouldFailWhenMatchingBranchConfigurationIsM
source-branches: [notconfigured]";
SetupConfigFileContent(text);
var ex = Should.Throw<ConfigurationException>(() => this.configurationProvider.ProvideForDirectory(this.repoPath));
ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{System.Environment.NewLine}" +
ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{PathHelper.NewLine}" +
"See https://gitversion.net/docs/reference/configuration for more info");
}

Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ public void NoCacheBypassesCache()
[Test]
public void WorkingDirectoryWithoutGit()
{
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = System.Environment.SystemDirectory };
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = SysEnv.SystemDirectory };

var exception = Assert.Throws<DirectoryNotFoundException>(() =>
{
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.Core.Tests/DocumentationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void ConfigurationDocumentationIsUpToDate()
{
var formattedConfigProperty = $"### {configProperty}";
configurationDocumentationFile.ShouldContain(formattedConfigProperty, Case.Insensitive,
System.Environment.NewLine + configurationDocumentationFile);
PathHelper.NewLine + configurationDocumentationFile);
}
}

Expand All @@ -48,7 +48,7 @@ public void VariableDocumentationIsUpToDate()
foreach (var variable in variables)
{
variableDocumentationFile.ShouldContain(variable, Case.Insensitive,
System.Environment.NewLine + variableDocumentationFile);
PathHelper.NewLine + variableDocumentationFile);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public static void DeleteDirectory(string directoryPath)
"{0}Known and common causes include:" +
"{0}- Windows Search Indexer (go to the Indexing Options, in the Windows Control Panel, and exclude the bin folder of LibGit2Sharp.Tests)" +
"{0}- Antivirus (exclude the bin folder of LibGit2Sharp.Tests from the paths scanned by your real-time antivirus){0}",
System.Environment.NewLine, Path.GetFullPath(directoryPath)));
PathHelper.NewLine, Path.GetFullPath(directoryPath)));
}
}
}
6 changes: 1 addition & 5 deletions src/GitVersion.Core.Tests/Helpers/ExecutableHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@ namespace GitVersion.Core.Tests.Helpers;

public static class ExecutableHelper
{
public static string GetCurrentDirectory() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new InvalidOperationException();

public static string GetDotNetExecutable() => "dotnet";

public static string GetExecutableArgs(string args) => $"{PathHelper.Combine(GetExeDirectory(), "gitversion.dll")} {args}";

public static string GetTempPath() => PathHelper.Combine(GetCurrentDirectory(), "TestRepositories", Guid.NewGuid().ToString());

private static string GetExeDirectory() => GetCurrentDirectory().Replace("GitVersion.App.Tests", "GitVersion.App");
private static string GetExeDirectory() => PathHelper.GetCurrentDirectory().Replace("GitVersion.App.Tests", "GitVersion.App");
}
5 changes: 3 additions & 2 deletions src/GitVersion.Core.Tests/Helpers/TestConsole.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion.Core.Tests.Helpers;
Expand All @@ -13,9 +14,9 @@ public TestConsole(params string[] responses)
this.responses = new Queue<string>(responses);
}

public void WriteLine(string? msg) => this.log.Info(msg + System.Environment.NewLine);
public void WriteLine(string? msg) => this.log.Info(msg + PathHelper.NewLine);

public void WriteLine() => this.log.Info(System.Environment.NewLine);
public void WriteLine() => this.log.Info(PathHelper.NewLine);

public void Write(string? msg) => this.log.Info(msg ?? throw new ArgumentNullException(nameof(msg)));

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.VersionCalculation;

namespace GitVersion.Configuration;
Expand Down Expand Up @@ -432,7 +433,7 @@ private static void ValidateConfiguration(IGitVersionConfiguration configuration
{
foreach (var (name, branchConfiguration) in configuration.Branches)
{
var helpUrl = $"{System.Environment.NewLine}See https://gitversion.net/docs/reference/configuration for more info";
var helpUrl = $"{PathHelper.NewLine}See https://gitversion.net/docs/reference/configuration for more info";

if (branchConfiguration.RegularExpression == null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Configuration.Init.Wizard;
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion.Configuration.Init.SetConfig;
Expand Down Expand Up @@ -41,7 +42,7 @@ protected override string GetPrompt(ConfigurationBuilder configurationBuilder, s
return @"Which branch would you like to configure:
0) Go Back
" + string.Join(System.Environment.NewLine, OrderedBranches(configuration).Select((c, i) => $"{i + 1}) {c.Key}"));
" + string.Join(PathHelper.NewLine, OrderedBranches(configuration).Select((c, i) => $"{i + 1}) {c.Key}"));
}

private static IOrderedEnumerable<KeyValuePair<string, IBranchConfiguration>> OrderedBranches(IGitVersionConfiguration configuration)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion.Configuration.Init.Wizard;
Expand All @@ -8,5 +9,5 @@ public FinishedSetupStep(IConsole console, IFileSystem fileSystem, ILog log, ICo
{
}

protected override string GetPrompt(ConfigurationBuilder configurationBuilder, string workingDirectory) => $"Questions are all done, you can now edit GitVersion's configuration further{System.Environment.NewLine}" + base.GetPrompt(configurationBuilder, workingDirectory);
protected override string GetPrompt(ConfigurationBuilder configurationBuilder, string workingDirectory) => $"Questions are all done, you can now edit GitVersion's configuration further{PathHelper.NewLine}" + base.GetPrompt(configurationBuilder, workingDirectory);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Configuration.Init.SetConfig;
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion.Configuration.Init.Wizard;
Expand All @@ -10,5 +11,5 @@ public GitFlowSetupStep(IConsole console, IFileSystem fileSystem, ILog log, ICon
}

protected override string GetPrompt(ConfigurationBuilder configurationBuilder, string workingDirectory)
=> $"By default GitVersion will only increment the version of the 'develop' branch every commit, all other branches will increment when tagged{System.Environment.NewLine}{System.Environment.NewLine}" + base.GetPrompt(configurationBuilder, workingDirectory);
=> $"By default GitVersion will only increment the version of the 'develop' branch every commit, all other branches will increment when tagged{PathHelper.NewLine}{PathHelper.NewLine}" + base.GetPrompt(configurationBuilder, workingDirectory);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Configuration.Init.SetConfig;
using GitVersion.Helpers;
using GitVersion.Logging;

namespace GitVersion.Configuration.Init.Wizard;
Expand All @@ -9,5 +10,5 @@ public GitHubFlowStep(IConsole console, IFileSystem fileSystem, ILog log, IConfi
{
}

protected override string GetPrompt(ConfigurationBuilder configurationBuilder, string workingDirectory) => $"By default GitVersion will only increment the version when tagged{System.Environment.NewLine}{System.Environment.NewLine}" + base.GetPrompt(configurationBuilder, workingDirectory);
protected override string GetPrompt(ConfigurationBuilder configurationBuilder, string workingDirectory) => $"By default GitVersion will only increment the version when tagged{PathHelper.NewLine}{PathHelper.NewLine}" + base.GetPrompt(configurationBuilder, workingDirectory);
}
4 changes: 2 additions & 2 deletions src/GitVersion.Core/Core/Environment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace GitVersion;

internal class Environment : IEnvironment
{
public string? GetEnvironmentVariable(string variableName) => System.Environment.GetEnvironmentVariable(variableName);
public string? GetEnvironmentVariable(string variableName) => SysEnv.GetEnvironmentVariable(variableName);

public void SetEnvironmentVariable(string variableName, string? value) => System.Environment.SetEnvironmentVariable(variableName, value);
public void SetEnvironmentVariable(string variableName, string? value) => SysEnv.SetEnvironmentVariable(variableName, value);
}
2 changes: 1 addition & 1 deletion src/GitVersion.Core/Core/GitPreparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private void EnsureHeadIsAttachedToBranch(string? currentBranchName, Authenticat

this.log.Info($"HEAD is detached and points at commit '{headSha}'.");
var localRefs = this.repository.Refs.FromGlob("*").Select(r => $"{r.Name.Canonical} ({r.TargetIdentifier})");
this.log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, localRefs));
this.log.Info($"Local Refs:{PathHelper.NewLine}" + string.Join(PathHelper.NewLine, localRefs));

// In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
// If they do, go ahead and checkout that branch
Expand Down
3 changes: 2 additions & 1 deletion src/GitVersion.Core/Core/GitVersionCalculateTool.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.Logging;
using GitVersion.OutputVariables;
using GitVersion.VersionCalculation;
Expand Down Expand Up @@ -61,7 +62,7 @@ public GitVersionVariables CalculateVersionVariables()
}
catch (AggregateException e)
{
this.log.Warning($"One or more exceptions during cache write:{System.Environment.NewLine}{e}");
this.log.Warning($"One or more exceptions during cache write:{PathHelper.NewLine}{e}");
}

return versionVariables;
Expand Down
Loading

0 comments on commit 2b6bca0

Please sign in to comment.