From 937dc2ed8a42a258beaa3890e8dc125071796e35 Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Wed, 16 Apr 2025 06:12:35 +0200 Subject: [PATCH 1/2] Refactor file system logic to use `FileSystemHelper` Replaces `PathHelper` and `DirectoryHelper` with a centralized `FileSystemHelper` for consistent file system operations. Removes redundant helper implementations and updates all references within the codebase to adopt the new utility. This change improves maintainability and leverages `System.IO.Abstractions` for better testability. --- .../ArgumentParserTests.cs | 42 ++--- .../ExecCmdLineArgumentTest.cs | 7 +- .../Helpers/GitVersionHelper.cs | 8 +- .../JsonOutputOnBuildServerTest.cs | 4 +- .../PullRequestInBuildAgentTest.cs | 4 +- .../TagCheckoutInBuildAgentTests.cs | 4 +- .../UpdateWixVersionFileTests.cs | 6 +- src/GitVersion.App/ArgumentParser.cs | 12 +- .../ArgumentParserExtensions.cs | 10 +- src/GitVersion.App/FileAppender.cs | 4 +- src/GitVersion.App/GitVersionExecutor.cs | 6 +- src/GitVersion.App/GlobbingResolver.cs | 6 +- src/GitVersion.App/HelpWriter.cs | 2 +- .../Agents/BitBucketPipelinesTests.cs | 6 +- .../Agents/CodeBuildTests.cs | 4 +- .../Agents/EnvRunTests.cs | 2 +- .../Agents/GitHubActionsTests.cs | 6 +- .../Agents/GitLabCiTests.cs | 4 +- .../Agents/JenkinsTests.cs | 4 +- .../ConfigurationFileLocatorTests.cs | 18 +- .../ConfigurationProviderTests.cs | 8 +- .../Configuration/Extensions.cs | 6 +- .../Builders/ConfigurationBuilderBase.cs | 2 +- .../ConfigurationFileLocator.cs | 12 +- .../Core/DynamicRepositoryTests.cs | 8 +- .../Core/GitVersionExecutorTests.cs | 16 +- .../Core/GitVersionToolDirectoryTests.cs | 6 +- .../DocumentationTests.cs | 6 +- .../GitRepositoryTestingExtensions.cs | 5 +- .../Helpers/ExecutableHelper.cs | 4 +- .../Helpers/TestConsole.cs | 4 +- .../IntegrationTests/OtherScenarios.cs | 5 +- .../IntegrationTests/WorktreeScenarios.cs | 2 +- src/GitVersion.Core/Core/GitPreparer.cs | 2 +- .../Core/GitVersionCalculateTool.cs | 2 +- src/GitVersion.Core/Core/RepositoryStore.cs | 4 +- .../Extensions/ConfigurationExtensions.cs | 16 +- .../Helpers/DirectoryHelper.cs | 46 ------ .../Helpers/FileSystemHelper.cs | 154 ++++++++++++++++++ src/GitVersion.Core/Helpers/PathHelper.cs | 95 ----------- .../Caching/GitVersionCacheKeyFactory.cs | 4 +- .../Caching/GitVersionCacheProvider.cs | 4 +- .../Git/GitRepository.mutating.cs | 2 +- .../Git/GitRepositoryInfo.cs | 8 +- .../Helpers/MsBuildExeFixture.cs | 4 +- .../Helpers/MsBuildTaskFixture.cs | 2 +- .../InvalidFileCheckerTests.cs | 42 ++--- .../GenerateGitVersionInformationTest.cs | 24 +-- .../Tasks/TestTaskBase.cs | 8 +- .../Tasks/UpdateAssemblyInfoTaskTest.cs | 16 +- .../Tasks/WriteVersionInfoTest.cs | 2 +- .../GitVersionTaskExecutor.cs | 6 +- .../Helpers/AssemblyInfoFileHelper.cs | 12 +- .../Helpers/MsBuildAppender.cs | 2 +- .../Output/AssemblyInfoFileUpdaterTests.cs | 68 ++++---- .../Output/GitVersionInfoGeneratorTests.cs | 16 +- .../Output/ProjectFileUpdaterTests.cs | 4 +- .../Output/WixFileTests.cs | 12 +- .../AssemblyInfo/AssemblyInfoFileUpdater.cs | 4 +- .../AssemblyInfo/ProjectFileUpdater.cs | 2 +- .../GitVersionInfo/GitVersionInfoGenerator.cs | 12 +- src/GitVersion.Output/TemplateManager.cs | 2 +- .../WixUpdater/WixVersionFileUpdater.cs | 2 +- .../Fixtures/BaseGitFlowRepositoryFixture.cs | 4 +- .../Fixtures/RepositoryFixtureBase.cs | 8 +- src/GitVersion.Testing/GitTestExtensions.cs | 13 +- .../GitVersion.Testing.csproj | 4 +- 67 files changed, 428 insertions(+), 421 deletions(-) delete mode 100644 src/GitVersion.Core/Helpers/DirectoryHelper.cs create mode 100644 src/GitVersion.Core/Helpers/FileSystemHelper.cs delete mode 100644 src/GitVersion.Core/Helpers/PathHelper.cs diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index abdcd6c2a5..ce806d2f12 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -283,13 +283,13 @@ public void UpdateAssemblyInfoWithFilename() { using var repo = new EmptyRepositoryFixture(); - var assemblyFile = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); + var assemblyFile = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = this.fileSystem.File.Create(assemblyFile); var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] @@ -297,17 +297,17 @@ public void UpdateAssemblyInfoWithMultipleFilenames() { using var repo = new EmptyRepositoryFixture(); - var assemblyFile1 = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); + var assemblyFile1 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = this.fileSystem.File.Create(assemblyFile1); - var assemblyFile2 = PathHelper.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); + var assemblyFile2 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = this.fileSystem.File.Create(assemblyFile2); var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("VersionAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); } [Test] @@ -315,17 +315,17 @@ public void UpdateProjectFilesWithMultipleFilenames() { using var repo = new EmptyRepositoryFixture(); - var assemblyFile1 = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.csproj"); + var assemblyFile1 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.csproj"); using var file = this.fileSystem.File.Create(assemblyFile1); - var assemblyFile2 = PathHelper.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); + var assemblyFile2 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); using var file2 = this.fileSystem.File.Create(assemblyFile2); var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateProjectFiles CommonAssemblyInfo.csproj VersionAssemblyInfo.csproj"); arguments.UpdateProjectFiles.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); } [Test] @@ -333,24 +333,24 @@ public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() { using var repo = new EmptyRepositoryFixture(); - var assemblyFile1 = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); + var assemblyFile1 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = this.fileSystem.File.Create(assemblyFile1); - var assemblyFile2 = PathHelper.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); + var assemblyFile2 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = this.fileSystem.File.Create(assemblyFile2); - var subdir = PathHelper.Combine(repo.RepositoryPath, "subdir"); + var subdir = FileSystemHelper.Path.Combine(repo.RepositoryPath, "subdir"); this.fileSystem.Directory.CreateDirectory(subdir); - var assemblyFile3 = PathHelper.Combine(subdir, "LocalAssemblyInfo.cs"); + var assemblyFile3 = FileSystemHelper.Path.Combine(subdir, "LocalAssemblyInfo.cs"); using var file3 = this.fileSystem.File.Create(assemblyFile3); var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo **/*AssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(3); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("VersionAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("LocalAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("LocalAssemblyInfo.cs")); } [Test] @@ -358,16 +358,16 @@ public void UpdateAssemblyInfoWithRelativeFilename() { using var repo = new EmptyRepositoryFixture(); - var assemblyFile = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); + var assemblyFile = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = this.fileSystem.File.Create(assemblyFile); - var targetPath = PathHelper.Combine(repo.RepositoryPath, "subdir1", "subdir2"); + var targetPath = FileSystemHelper.Path.Combine(repo.RepositoryPath, "subdir1", "subdir2"); this.fileSystem.Directory.CreateDirectory(targetPath); var arguments = this.argumentParser.ParseArguments($"-targetpath {targetPath} -updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] @@ -765,7 +765,7 @@ public void ThrowIfConfigurationFileDoesNotExist(string configFile) => [Test] public void EnsureConfigurationFileIsSet() { - var configFile = PathHelper.GetTempPath() + Guid.NewGuid() + ".yaml"; + var configFile = FileSystemHelper.Path.GetTempPath() + Guid.NewGuid() + ".yaml"; this.fileSystem.File.WriteAllText(configFile, "next-version: 1.0.0"); var arguments = this.argumentParser.ParseArguments($"-config {configFile}"); arguments.ConfigurationFile.ShouldBe(configFile); diff --git a/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs b/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs index bd93f3a99f..b732fdf6ac 100644 --- a/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs +++ b/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs @@ -52,7 +52,8 @@ public void CheckBuildServerVerbosityConsole(string verbosityArg, string expecte [Test] public void WorkingDirectoryWithoutGitFolderFailsWithInformativeMessage() { - var result = GitVersionHelper.ExecuteIn(Path.GetTempPath(), null, false); + var workingDirectory = FileSystemHelper.Path.GetTempPathLegacy(); + var result = GitVersionHelper.ExecuteIn(workingDirectory, null, false); result.ExitCode.ShouldNotBe(0); result.Output.ShouldNotBeNull(); @@ -84,7 +85,7 @@ public void WorkingDirectoryWithoutCommitsFailsWithInformativeMessage() [Test] public void WorkingDirectoryDoesNotExistFailsWithInformativeMessage() { - var workingDirectory = PathHelper.Combine(PathHelper.GetCurrentDirectory(), Guid.NewGuid().ToString("N")); + var workingDirectory = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetCurrentDirectory(), Guid.NewGuid().ToString("N")); var executable = ExecutableHelper.GetDotNetExecutable(); var output = new StringBuilder(); @@ -96,7 +97,7 @@ public void WorkingDirectoryDoesNotExistFailsWithInformativeMessage() null, executable, args, - PathHelper.GetCurrentDirectory()); + FileSystemHelper.Path.GetCurrentDirectory()); exitCode.ShouldNotBe(0); var outputString = output.ToString(); diff --git a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs index 6e46593bb2..fb92374e31 100644 --- a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs +++ b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs @@ -13,7 +13,7 @@ public static ExecutionResults ExecuteIn( bool logToFile = true, params KeyValuePair[] environments) { - var logFile = workingDirectory is not null && logToFile ? PathHelper.Combine(workingDirectory, "log.txt") : null; + var logFile = workingDirectory is not null && logToFile ? FileSystemHelper.Path.Combine(workingDirectory, "log.txt") : null; var args = new ArgumentBuilder(workingDirectory, arguments, logFile); return ExecuteIn(args, environments); } @@ -50,7 +50,7 @@ private static ExecutionResults ExecuteIn(ArgumentBuilder arguments, Console.WriteLine("Executing: {0} {1}", executable, args); Console.WriteLine(); - var workingDirectory = arguments.WorkingDirectory ?? PathHelper.GetCurrentDirectory(); + var workingDirectory = arguments.WorkingDirectory ?? FileSystemHelper.Path.GetCurrentDirectory(); exitCode = ProcessHelper.Run( s => output.AppendLine(s), @@ -77,12 +77,12 @@ private static ExecutionResults ExecuteIn(ArgumentBuilder arguments, Console.WriteLine(); Console.WriteLine("-------------------------------------------------------"); - if (arguments.LogFile.IsNullOrWhiteSpace() || !File.Exists(arguments.LogFile)) + if (arguments.LogFile.IsNullOrWhiteSpace() || !FileSystemHelper.File.Exists(arguments.LogFile)) { return new(exitCode, output.ToString()); } - var logContents = File.ReadAllText(arguments.LogFile); + var logContents = FileSystemHelper.File.ReadAllText(arguments.LogFile); Console.WriteLine("Log from gitversion tool"); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine(logContents); diff --git a/src/GitVersion.App.Tests/JsonOutputOnBuildServerTest.cs b/src/GitVersion.App.Tests/JsonOutputOnBuildServerTest.cs index 86c373ff4e..30d6d48108 100644 --- a/src/GitVersion.App.Tests/JsonOutputOnBuildServerTest.cs +++ b/src/GitVersion.App.Tests/JsonOutputOnBuildServerTest.cs @@ -60,8 +60,8 @@ public void BeingOnBuildServerWithOutputJsonAndOutputFileDoesNotFail(string outp result.OutputVariables.ShouldNotBeNull(); result.OutputVariables.FullSemVer.ShouldBeEquivalentTo(expectedVersion); - var filePath = PathHelper.Combine(fixture.LocalRepositoryFixture.RepositoryPath, fileName); - var json = File.ReadAllText(filePath); + var filePath = FileSystemHelper.Path.Combine(fixture.LocalRepositoryFixture.RepositoryPath, fileName); + var json = FileSystemHelper.File.ReadAllText(filePath); var outputVariables = json.ToGitVersionVariables(); outputVariables.ShouldNotBeNull(); diff --git a/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs b/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs index 9fb5e7db11..56d919756f 100644 --- a/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs +++ b/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs @@ -144,7 +144,7 @@ public async Task VerifyBitBucketPipelinesPullRequest(string pullRequestRef) private static async Task VerifyPullRequestVersionIsCalculatedProperly(string pullRequestRef, Dictionary env) { using var fixture = new EmptyRepositoryFixture(); - var remoteRepositoryPath = PathHelper.GetRepositoryTempPath(); + var remoteRepositoryPath = FileSystemHelper.Path.GetRepositoryTempPath(); RepositoryFixtureBase.Init(remoteRepositoryPath); using (var remoteRepository = new Repository(remoteRepositoryPath)) { @@ -184,7 +184,7 @@ private static async Task VerifyPullRequestVersionIsCalculatedProperly(string pu result.OutputVariables.FullSemVer.ShouldBe("1.0.4-PullRequest5.3"); // Cleanup repository files - DirectoryHelper.DeleteDirectory(remoteRepositoryPath); + FileSystemHelper.Directory.DeleteDirectory(remoteRepositoryPath); } private static readonly object[] PrMergeRefInputs = diff --git a/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs b/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs index b66e9debf6..fc31fa4a7d 100644 --- a/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs +++ b/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs @@ -35,7 +35,7 @@ public async Task VerifyTagCheckoutOnGitHubActions() private static async Task VerifyTagCheckoutVersionIsCalculatedProperly(Dictionary env) { using var fixture = new EmptyRepositoryFixture(); - var remoteRepositoryPath = PathHelper.GetRepositoryTempPath(); + var remoteRepositoryPath = FileSystemHelper.Path.GetRepositoryTempPath(); RepositoryFixtureBase.Init(remoteRepositoryPath); using (var remoteRepository = new Repository(remoteRepositoryPath)) { @@ -66,6 +66,6 @@ private static async Task VerifyTagCheckoutVersionIsCalculatedProperly(Dictionar result.OutputVariables.FullSemVer.ShouldBe("0.2.0"); // Cleanup repository files - DirectoryHelper.DeleteDirectory(remoteRepositoryPath); + FileSystemHelper.Directory.DeleteDirectory(remoteRepositoryPath); } } diff --git a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs index e224aabf53..a73c361411 100644 --- a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs +++ b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs @@ -21,7 +21,7 @@ public void WixVersionFileCreationTest() fixture.MakeACommit(); GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - Assert.That(File.Exists(PathHelper.Combine(fixture.RepositoryPath, this.wixVersionFileName)), Is.True); + Assert.That(FileSystemHelper.File.Exists(FileSystemHelper.Path.Combine(fixture.RepositoryPath, this.wixVersionFileName)), Is.True); } [Test] @@ -36,7 +36,7 @@ public void WixVersionFileVarCountTest() GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - var gitVersionVarsInWix = GetGitVersionVarsInWixFile(PathHelper.Combine(fixture.RepositoryPath, this.wixVersionFileName)); + var gitVersionVarsInWix = GetGitVersionVarsInWixFile(FileSystemHelper.Path.Combine(fixture.RepositoryPath, this.wixVersionFileName)); var gitVersionVars = GitVersionVariables.AvailableVariables; Assert.That(gitVersionVarsInWix, Has.Count.EqualTo(gitVersionVars.Count())); @@ -55,7 +55,7 @@ public void WixVersionFileContentTest() GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - var gitVersionVarsInWix = GetGitVersionVarsInWixFile(PathHelper.Combine(fixture.RepositoryPath, this.wixVersionFileName)); + var gitVersionVarsInWix = GetGitVersionVarsInWixFile(FileSystemHelper.Path.Combine(fixture.RepositoryPath, this.wixVersionFileName)); var gitVersionVars = GitVersionVariables.AvailableVariables; foreach (var variable in gitVersionVars) diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index bccbc96d36..aae568d64b 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -107,14 +107,14 @@ private void ValidateConfigurationFile(Arguments arguments) { if (arguments.ConfigurationFile.IsNullOrWhiteSpace()) return; - if (PathHelper.IsPathRooted(arguments.ConfigurationFile)) + if (FileSystemHelper.Path.IsPathRooted(arguments.ConfigurationFile)) { if (!this.fileSystem.File.Exists(arguments.ConfigurationFile)) throw new WarningException($"Could not find config file at '{arguments.ConfigurationFile}'"); - arguments.ConfigurationFile = PathHelper.GetFullPath(arguments.ConfigurationFile); + arguments.ConfigurationFile = FileSystemHelper.Path.GetFullPath(arguments.ConfigurationFile); } else { - var configFilePath = PathHelper.GetFullPath(PathHelper.Combine(arguments.TargetPath, arguments.ConfigurationFile)); + var configFilePath = FileSystemHelper.Path.GetFullPath(FileSystemHelper.Path.Combine(arguments.TargetPath, arguments.ConfigurationFile)); if (!this.fileSystem.File.Exists(configFilePath)) throw new WarningException($"Could not find config file at '{configFilePath}'"); arguments.ConfigurationFile = configFilePath; } @@ -156,7 +156,7 @@ private IEnumerable ResolveFiles(string workingDirectory, ISet? foreach (var path in paths) { - yield return PathHelper.GetFullPath(PathHelper.Combine(workingDirectory, path)); + yield return FileSystemHelper.Path.GetFullPath(FileSystemHelper.Path.Combine(workingDirectory, path)); } } } @@ -182,7 +182,7 @@ private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList string.Concat("'", x, "'"))); throw new WarningException(message); } diff --git a/src/GitVersion.App/ArgumentParserExtensions.cs b/src/GitVersion.App/ArgumentParserExtensions.cs index b1e6063957..493052fa06 100644 --- a/src/GitVersion.App/ArgumentParserExtensions.cs +++ b/src/GitVersion.App/ArgumentParserExtensions.cs @@ -19,15 +19,15 @@ public static bool IsValidPath(this string? path) try { - _ = PathHelper.GetFullPath(path); + _ = FileSystemHelper.Path.GetFullPath(path); } catch { - path = PathHelper.Combine(SysEnv.CurrentDirectory, path); + path = FileSystemHelper.Path.Combine(SysEnv.CurrentDirectory, path); try { - _ = PathHelper.GetFullPath(path); + _ = FileSystemHelper.Path.GetFullPath(path); } catch { @@ -35,7 +35,7 @@ public static bool IsValidPath(this string? path) } } - return Directory.Exists(path); + return FileSystemHelper.Directory.Exists(path); } public static bool IsSwitchArgument(this string? value) @@ -74,7 +74,7 @@ public static bool ArgumentRequiresValue(this string argument, int argumentIndex var argumentMightRequireValue = !booleanArguments.Contains(argument[1..], StringComparer.OrdinalIgnoreCase); // If this is the first argument that might be a target path, the argument starts with slash, and we're on an OS that supports paths with slashes, the argument does not require a value. - if (argumentMightRequireValue && argumentIndex == 0 && argument.StartsWith('/') && PathHelper.DirectorySeparatorChar == '/' && argument.IsValidPath()) + if (argumentMightRequireValue && argumentIndex == 0 && argument.StartsWith('/') && FileSystemHelper.Path.DirectorySeparatorChar == '/' && argument.IsValidPath()) return false; return argumentMightRequireValue; diff --git a/src/GitVersion.App/FileAppender.cs b/src/GitVersion.App/FileAppender.cs index 37007bb4f5..ca75930e87 100644 --- a/src/GitVersion.App/FileAppender.cs +++ b/src/GitVersion.App/FileAppender.cs @@ -15,7 +15,7 @@ public FileAppender(IFileSystem fileSystem, string filePath) this.fileSystem = fileSystem.NotNull(); this.filePath = filePath; - var logFile = this.fileSystem.FileInfo.New(PathHelper.GetFullPath(filePath)); + var logFile = this.fileSystem.FileInfo.New(FileSystemHelper.Path.GetFullPath(filePath)); logFile.Directory?.Create(); if (logFile.Exists) return; @@ -37,7 +37,7 @@ public void WriteTo(LogLevel level, string message) private void WriteLogEntry(string logFilePath, string str) { - var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{str}{PathHelper.NewLine}"; + var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{str}{FileSystemHelper.Path.NewLine}"; this.fileSystem.File.AppendAllText(logFilePath, contents); } } diff --git a/src/GitVersion.App/GitVersionExecutor.cs b/src/GitVersion.App/GitVersionExecutor.cs index 059eee6914..36199ac398 100644 --- a/src/GitVersion.App/GitVersionExecutor.cs +++ b/src/GitVersion.App/GitVersionExecutor.cs @@ -56,7 +56,7 @@ public int Execute(GitVersionOptions gitVersionOptions) private int RunGitVersionTool(GitVersionOptions gitVersionOptions) { this.gitRepository.DiscoverRepository(gitVersionOptions.WorkingDirectory); - var mutexName = this.repositoryInfo.DotGitDirectory?.Replace(PathHelper.DirectorySeparatorChar.ToString(), "") ?? string.Empty; + var mutexName = this.repositoryInfo.DotGitDirectory?.Replace(FileSystemHelper.Path.DirectorySeparatorChar.ToString(), "") ?? string.Empty; using var mutex = new Mutex(true, $@"Global\gitversion{mutexName}", out var acquired); try @@ -76,13 +76,13 @@ private int RunGitVersionTool(GitVersionOptions gitVersionOptions) } catch (WarningException exception) { - var error = $"An error occurred:{PathHelper.NewLine}{exception.Message}"; + var error = $"An error occurred:{FileSystemHelper.Path.NewLine}{exception.Message}"; this.log.Warning(error); return 1; } catch (Exception exception) { - var error = $"An unexpected error occurred:{PathHelper.NewLine}{exception}"; + var error = $"An unexpected error occurred:{FileSystemHelper.Path.NewLine}{exception}"; this.log.Error(error); try diff --git a/src/GitVersion.App/GlobbingResolver.cs b/src/GitVersion.App/GlobbingResolver.cs index d17606436a..f16423a78f 100644 --- a/src/GitVersion.App/GlobbingResolver.cs +++ b/src/GitVersion.App/GlobbingResolver.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.FileSystemGlobbing; -using Microsoft.Extensions.FileSystemGlobbing.Abstractions; namespace GitVersion; @@ -10,9 +9,6 @@ internal class GlobbingResolver : IGlobbingResolver public IEnumerable Resolve(string workingDirectory, string pattern) { this.matcher.AddInclude(pattern); - return this.matcher.Execute(GetDirectoryInfoWrapper(workingDirectory)).Files.Select(file => file.Path); + return this.matcher.GetResultsInFullPath(workingDirectory); } - - private static DirectoryInfoWrapper GetDirectoryInfoWrapper(string workingDirectory) - => new(new DirectoryInfo(workingDirectory)); } diff --git a/src/GitVersion.App/HelpWriter.cs b/src/GitVersion.App/HelpWriter.cs index 8ba9ed8e84..7bc0db8951 100644 --- a/src/GitVersion.App/HelpWriter.cs +++ b/src/GitVersion.App/HelpWriter.cs @@ -18,7 +18,7 @@ public void WriteTo(Action writeAction) this.versionWriter.WriteTo(assembly, v => version = v); var args = ArgumentList(); - var message = $"GitVersion {version}{PathHelper.NewLine}{PathHelper.NewLine}{args}"; + var message = $"GitVersion {version}{FileSystemHelper.Path.NewLine}{FileSystemHelper.Path.NewLine}{args}"; writeAction(message); } diff --git a/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs index a8a39cbca0..a443730955 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs @@ -120,10 +120,10 @@ public void GetCurrentBranchShouldHandlePullRequests() [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = FileSystemHelper.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); - var propertyFile = PathHelper.Combine(assemblyLocation, "gitversion.properties"); - var ps1File = PathHelper.Combine(assemblyLocation, "gitversion.ps1"); + var propertyFile = FileSystemHelper.Path.Combine(assemblyLocation, "gitversion.properties"); + var ps1File = FileSystemHelper.Path.Combine(assemblyLocation, "gitversion.ps1"); try { diff --git a/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs index 5b072bdf1e..9924a3da9e 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs @@ -55,9 +55,9 @@ public void PicksUpBranchNameFromEnvironmentFromWebHook() [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = FileSystemHelper.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); - var f = PathHelper.Combine(assemblyLocation, "codebuild_this_file_should_be_deleted.properties"); + var f = FileSystemHelper.Path.Combine(assemblyLocation, "codebuild_this_file_should_be_deleted.properties"); try { diff --git a/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs index bff6125322..86604b2737 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs @@ -23,7 +23,7 @@ public void SetEnvironmentVariableForTest() this.buildServer = sp.GetRequiredService(); // set environment variable and create an empty envrun file to indicate that EnvRun is running... - this.mFilePath = PathHelper.Combine(PathHelper.GetTempPath(), "envrun.db"); + this.mFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "envrun.db"); this.environment.SetEnvironmentVariable(EnvVarName, this.mFilePath); this.fileSystem.File.OpenWrite(this.mFilePath).Dispose(); } diff --git a/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs index 34f7c43140..2e0e258a13 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs @@ -23,7 +23,7 @@ public void SetUp() this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true"); this.environment.SetEnvironmentVariable("GITHUB_REF_TYPE", "branch"); - this.githubSetEnvironmentTempFilePath = PathHelper.GetTempFileName(); + this.githubSetEnvironmentTempFilePath = FileSystemHelper.Path.GetRandomFileName(); this.environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, this.githubSetEnvironmentTempFilePath); } @@ -142,8 +142,8 @@ public void ShouldWriteIntegration() // Assert var expected = new List { "Set Build Number for 'GitHubActions'.", "", "Set Output Variables for 'GitHubActions'.", "Writing version variables to $GITHUB_ENV file for 'GitHubActions'." }; - string.Join(PathHelper.NewLine, list) - .ShouldBe(string.Join(PathHelper.NewLine, expected)); + string.Join(FileSystemHelper.Path.NewLine, list) + .ShouldBe(string.Join(FileSystemHelper.Path.NewLine, expected)); var expectedFileContents = new List { "GitVersion_Major=1.0.0" }; diff --git a/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs index 9f78e800a7..457955b088 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs @@ -95,9 +95,9 @@ public void GetCurrentBranchShouldHandlePullRequests(string branchName, string e [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = FileSystemHelper.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); - var f = PathHelper.Combine(assemblyLocation, "jenkins_this_file_should_be_deleted.properties"); + var f = FileSystemHelper.Path.Combine(assemblyLocation, "jenkins_this_file_should_be_deleted.properties"); try { diff --git a/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs index 0899cd8c31..6c23d10ec2 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs @@ -111,9 +111,9 @@ public void ShouldSetOutputVariables() [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = FileSystemHelper.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); - var f = PathHelper.Combine(assemblyLocation, "gitlab_this_file_should_be_deleted.properties"); + var f = FileSystemHelper.Path.Combine(assemblyLocation, "gitlab_this_file_should_be_deleted.properties"); try { diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs index e7b04d800a..084ce06795 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs @@ -23,8 +23,8 @@ public class DefaultConfigFileLocatorTests : TestBase [SetUp] public void Setup() { - this.repoPath = PathHelper.Combine(PathHelper.GetTempPath(), "MyGitRepo"); - this.workingPath = PathHelper.Combine(PathHelper.GetTempPath(), "MyGitRepo", "Working"); + this.repoPath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "MyGitRepo"); + this.workingPath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "MyGitRepo", "Working"); var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => services.AddSingleton(options)); @@ -103,8 +103,8 @@ public class NamedConfigurationFileLocatorTests : TestBase public void Setup() { this.gitVersionOptions = new() { ConfigurationInfo = { ConfigurationFile = "my-config.yaml" } }; - this.repoPath = PathHelper.Combine(PathHelper.GetTempPath(), "MyGitRepo"); - this.workingPath = PathHelper.Combine(PathHelper.GetTempPath(), "MyGitRepo", "Working"); + this.repoPath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "MyGitRepo"); + this.workingPath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "MyGitRepo", "Working"); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); } @@ -157,7 +157,7 @@ public void DoNotThrowWhenWorkingAndRepoPathsAreSame_WithDifferentCasing() public void ReturnConfigurationFilePathIfCustomConfigurationIsSet() { this.workingPath = this.repoPath; - string configurationFilePath = Path.Combine(this.workingPath, "Configuration", "CustomConfig.yaml"); + string configurationFilePath = FileSystemHelper.Path.Combine(this.workingPath, "Configuration", "CustomConfig.yaml"); this.gitVersionOptions = new() { ConfigurationInfo = { ConfigurationFile = configurationFilePath } }; @@ -165,7 +165,7 @@ public void ReturnConfigurationFilePathIfCustomConfigurationIsSet() this.fileSystem = serviceProvider.GetRequiredService(); using var _ = this.fileSystem.SetupConfigFile( - path: Path.Combine(this.workingPath, "Configuration"), fileName: "CustomConfig.yaml" + path: FileSystemHelper.Path.Combine(this.workingPath, "Configuration"), fileName: "CustomConfig.yaml" ); this.configFileLocator = serviceProvider.GetRequiredService(); @@ -238,7 +238,7 @@ public void NoWarnOnCustomYmlFileOutsideRepoPath() this.configFileLocator = sp.GetRequiredService(); this.fileSystem = sp.GetRequiredService(); - string path = PathHelper.Combine(PathHelper.GetTempPath(), "unrelatedPath"); + string path = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "unrelatedPath"); using var _ = this.fileSystem.SetupConfigFile(path: path, fileName: ConfigFile); var configurationProvider = (ConfigurationProvider)sp.GetRequiredService(); @@ -256,8 +256,8 @@ public void ThrowsExceptionOnCustomYmlFileDoesNotExist() var exception = Should.Throw(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var configurationFile = this.gitVersionOptions.ConfigurationInfo.ConfigurationFile; - var workingPathFileConfig = PathHelper.Combine(this.workingPath, configurationFile); - var repoPathFileConfig = PathHelper.Combine(this.repoPath, configurationFile); + var workingPathFileConfig = FileSystemHelper.Path.Combine(this.workingPath, configurationFile); + var repoPathFileConfig = FileSystemHelper.Path.Combine(this.repoPath, configurationFile); var expectedMessage = $"The configuration file was not found at '{workingPathFileConfig}' or '{repoPathFileConfig}'"; exception.Message.ShouldBe(expectedMessage); } diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs index 3b350cbe7d..6dfe2f3760 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs @@ -21,7 +21,7 @@ public class ConfigurationProviderTests : TestBase [SetUp] public void Setup() { - this.repoPath = PathHelper.Combine(PathHelper.GetTempPath(), "MyGitRepo"); + this.repoPath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "MyGitRepo"); var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => services.AddSingleton(options)); this.configurationProvider = (ConfigurationProvider)sp.GetRequiredService(); @@ -94,7 +94,7 @@ public void RegexIsRequired() label: bugfix"; using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); var ex = Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); - ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{PathHelper.NewLine}" + + ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{FileSystemHelper.Path.NewLine}" + "See https://gitversion.net/docs/reference/configuration for more info"); } @@ -109,7 +109,7 @@ public void SourceBranchesValidationShouldFailWhenMatchingBranchConfigurationIsM source-branches: [notconfigured]"; using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); var ex = Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); - ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{PathHelper.NewLine}" + + ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{FileSystemHelper.Path.NewLine}" + "See https://gitversion.net/docs/reference/configuration for more info"); } @@ -286,7 +286,7 @@ public void NoWarnOnGitVersionYmlFile() this.configurationProvider.ProvideForDirectory(this.repoPath); - var filePath = PathHelper.Combine(this.repoPath, ConfigurationFileLocator.DefaultFileName); + var filePath = FileSystemHelper.Path.Combine(this.repoPath, ConfigurationFileLocator.DefaultFileName); stringLogger.ShouldContain($"Using configuration file '{filePath}'"); } diff --git a/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs b/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs index e6f9932e03..dafc7c5ce0 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs @@ -10,11 +10,11 @@ public static IDisposable SetupConfigFile(this IFileSystem fileSystem, s { if (path.IsNullOrEmpty()) { - path = PathHelper.GetRepositoryTempPath(); + path = FileSystemHelper.Path.GetRepositoryTempPath(); } - var fullPath = PathHelper.Combine(path, fileName); - var directory = PathHelper.GetDirectoryName(fullPath); + var fullPath = FileSystemHelper.Path.Combine(path, fileName); + var directory = FileSystemHelper.Path.GetDirectoryName(fullPath); if (!fileSystem.Directory.Exists(directory)) { fileSystem.Directory.CreateDirectory(directory); diff --git a/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs b/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs index 3a7bfa3b3c..afd8bfa04d 100644 --- a/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs +++ b/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs @@ -463,7 +463,7 @@ private static void ValidateConfiguration(IGitVersionConfiguration configuration { foreach (var (name, branchConfiguration) in configuration.Branches) { - var helpUrl = $"{PathHelper.NewLine}See https://gitversion.net/docs/reference/configuration for more info"; + var helpUrl = $"{FileSystemHelper.Path.NewLine}See https://gitversion.net/docs/reference/configuration for more info"; if (branchConfiguration.RegularExpression == null) { diff --git a/src/GitVersion.Configuration/ConfigurationFileLocator.cs b/src/GitVersion.Configuration/ConfigurationFileLocator.cs index de69aef59f..2f5eccf0f9 100644 --- a/src/GitVersion.Configuration/ConfigurationFileLocator.cs +++ b/src/GitVersion.Configuration/ConfigurationFileLocator.cs @@ -33,8 +33,8 @@ internal class ConfigurationFileLocator( public void Verify(string? workingDirectory, string? projectRootDirectory) { - if (PathHelper.IsPathRooted(this.ConfigurationFile)) return; - if (PathHelper.Equal(workingDirectory, projectRootDirectory)) return; + if (FileSystemHelper.Path.IsPathRooted(this.ConfigurationFile)) return; + if (FileSystemHelper.Path.Equal(workingDirectory, projectRootDirectory)) return; WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory); } @@ -56,7 +56,7 @@ public void Verify(string? workingDirectory, string? projectRootDirectory) foreach (var fileName in this.SupportedConfigFileNames) { this.log.Debug($"Trying to find configuration file {fileName} at '{directoryPath}'"); - string? matchingFile = files.FirstOrDefault(file => string.Equals(PathHelper.GetFileName(file), fileName, StringComparison.OrdinalIgnoreCase)); + string? matchingFile = files.FirstOrDefault(file => string.Equals(FileSystemHelper.Path.GetFileName(file), fileName, StringComparison.OrdinalIgnoreCase)); if (matchingFile != null) { this.log.Info($"Found configuration file at '{matchingFile}'"); @@ -74,7 +74,7 @@ public void Verify(string? workingDirectory, string? projectRootDirectory) string configurationFilePath = this.ConfigurationFile; if (!string.IsNullOrWhiteSpace(directoryPath)) { - configurationFilePath = Path.Combine(directoryPath, this.ConfigurationFile); + configurationFilePath = FileSystemHelper.Path.Combine(directoryPath, this.ConfigurationFile); } if (fileSystem.File.Exists(configurationFilePath)) @@ -101,8 +101,8 @@ private void WarnAboutAmbiguousConfigFileSelection(string? workingDirectory, str if (hasConfigInProjectRootDirectory || hasConfigInWorkingDirectory || this.SupportedConfigFileNames.Any(entry => entry.Equals(this.ConfigurationFile, StringComparison.OrdinalIgnoreCase))) return; - workingConfigFile = PathHelper.Combine(workingDirectory, this.ConfigurationFile); - projectRootConfigFile = PathHelper.Combine(projectRootDirectory, this.ConfigurationFile); + workingConfigFile = FileSystemHelper.Path.Combine(workingDirectory, this.ConfigurationFile); + projectRootConfigFile = FileSystemHelper.Path.Combine(projectRootDirectory, this.ConfigurationFile); throw new WarningException($"The configuration file was not found at '{workingConfigFile}' or '{projectRootConfigFile}'"); } } diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index a8b0ca9985..03eb85b522 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -12,7 +12,7 @@ public class DynamicRepositoryTests : TestBase private string? workDirectory; [SetUp] - public void SetUp() => this.workDirectory = PathHelper.Combine(Path.GetTempPath(), "GV"); + public void SetUp() => this.workDirectory = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPathLegacy(), "GV"); [TearDown] public void TearDown() @@ -25,9 +25,9 @@ public void TearDown() [TestCase("GV_main", "https://github.com/GitTools/GitVersion", MainBranch, "efddf2f92c539a9c27f1904d952dcab8fb955f0e", "5.8.2-56")] public void FindsVersionInDynamicRepo(string name, string url, string targetBranch, string commitId, string expectedFullSemVer) { - var root = PathHelper.Combine(this.workDirectory, name); - var dynamicDirectory = PathHelper.Combine(root, "D"); // dynamic, keeping directory as short as possible - var workingDirectory = PathHelper.Combine(root, "W"); // working, keeping directory as short as possible + var root = FileSystemHelper.Path.Combine(this.workDirectory, name); + var dynamicDirectory = FileSystemHelper.Path.Combine(root, "D"); // dynamic, keeping directory as short as possible + var workingDirectory = FileSystemHelper.Path.Combine(root, "W"); // working, keeping directory as short as possible var gitVersionOptions = new GitVersionOptions { RepositoryInfo = diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index 6bb47da39c..d4dbf79950 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -92,7 +92,7 @@ public void CacheKeyForWorktree() } finally { - DirectoryHelper.DeleteDirectory(worktreePath); + FileSystemHelper.Directory.DeleteDirectory(worktreePath); } } @@ -299,7 +299,7 @@ public void ConfigChangeInvalidatesCache(string configFileName) versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); - var configPath = PathHelper.Combine(fixture.RepositoryPath, configFileName); + var configPath = FileSystemHelper.Path.Combine(fixture.RepositoryPath, configFileName); this.fileSystem.File.WriteAllText(configPath, "next-version: 5.0.0"); gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: this.fileSystem); @@ -416,7 +416,7 @@ public void GetProjectRootDirectoryWorkingDirectoryWithWorktree() } finally { - DirectoryHelper.DeleteDirectory(worktreePath); + FileSystemHelper.Directory.DeleteDirectory(worktreePath); } } @@ -445,7 +445,7 @@ public void GetDotGitDirectoryNoWorktree() this.sp = GetServiceProvider(gitVersionOptions); var repositoryInfo = this.sp.GetRequiredService(); - var expectedPath = PathHelper.Combine(fixture.RepositoryPath, ".git"); + var expectedPath = FileSystemHelper.Path.Combine(fixture.RepositoryPath, ".git"); repositoryInfo.DotGitDirectory.ShouldBe(expectedPath); } @@ -467,12 +467,12 @@ public void GetDotGitDirectoryWorktree() this.sp = GetServiceProvider(gitVersionOptions); var repositoryInfo = this.sp.GetRequiredService(); - var expectedPath = PathHelper.Combine(fixture.RepositoryPath, ".git"); + var expectedPath = FileSystemHelper.Path.Combine(fixture.RepositoryPath, ".git"); repositoryInfo.DotGitDirectory.ShouldBe(expectedPath); } finally { - DirectoryHelper.DeleteDirectory(worktreePath); + FileSystemHelper.Directory.DeleteDirectory(worktreePath); } } @@ -483,7 +483,7 @@ public void CalculateVersionFromWorktreeHead() this.fileSystem = new FileSystem(); using var fixture = new EmptyRepositoryFixture(); var repoDir = fileSystem.DirectoryInfo.New(fixture.RepositoryPath); - var worktreePath = PathHelper.Combine(repoDir.Parent?.FullName, $"{repoDir.Name}-v1"); + var worktreePath = FileSystemHelper.Path.Combine(repoDir.Parent?.FullName, $"{repoDir.Name}-v1"); fixture.Repository.MakeATaggedCommit("v1.0.0"); var branchV1 = fixture.Repository.CreateBranch("support/1.0"); @@ -595,7 +595,7 @@ public void CalculateVersionVariables_ShallowFetch_ThrowException() private string GetWorktreePath(EmptyRepositoryFixture fixture) { - var worktreePath = PathHelper.Combine(this.fileSystem.Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); + var worktreePath = FileSystemHelper.Path.Combine(this.fileSystem.Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); return worktreePath; } diff --git a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs index c4c9e1140d..9f2d17b57d 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs @@ -19,8 +19,8 @@ public void SetUp() { var sp = ConfigureServices(); this.fileSystem = sp.GetRequiredService(); - this.workDirectory = PathHelper.Combine(PathHelper.GetTempPath(), Guid.NewGuid().ToString()); - this.gitDirectory = Repository.Init(this.workDirectory).TrimEnd(PathHelper.DirectorySeparatorChar); + this.workDirectory = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), Guid.NewGuid().ToString()); + this.gitDirectory = Repository.Init(this.workDirectory).TrimEnd(FileSystemHelper.Path.DirectorySeparatorChar); Assert.That(this.gitDirectory, Is.Not.Null); } @@ -46,7 +46,7 @@ public void FindsGitDirectory() [Test] public void FindsGitDirectoryInParent() { - var childDir = PathHelper.Combine(this.workDirectory, "child"); + var childDir = FileSystemHelper.Path.Combine(this.workDirectory, "child"); this.fileSystem.Directory.CreateDirectory(childDir); var exception = Assert.Catch(() => diff --git a/src/GitVersion.Core.Tests/DocumentationTests.cs b/src/GitVersion.Core.Tests/DocumentationTests.cs index fe753448a5..cc77fe446b 100644 --- a/src/GitVersion.Core.Tests/DocumentationTests.cs +++ b/src/GitVersion.Core.Tests/DocumentationTests.cs @@ -39,7 +39,7 @@ public void ConfigurationDocumentationIsUpToDate() { var formattedConfigProperty = $"### {configProperty}"; configurationDocumentationFile.ShouldContain(formattedConfigProperty, Case.Insensitive, - PathHelper.NewLine + configurationDocumentationFile); + FileSystemHelper.Path.NewLine + configurationDocumentationFile); } } @@ -54,13 +54,13 @@ public void VariableDocumentationIsUpToDate() foreach (var variable in variables) { variableDocumentationFile.ShouldContain(variable, Case.Insensitive, - PathHelper.NewLine + variableDocumentationFile); + FileSystemHelper.Path.NewLine + variableDocumentationFile); } } private string ReadDocumentationFile(string relativeDocumentationFilePath) { - var documentationFilePath = PathHelper.Combine(this.docsDirectory.FullName, relativeDocumentationFilePath); + var documentationFilePath = FileSystemHelper.Path.Combine(this.docsDirectory.FullName, relativeDocumentationFilePath); // Normalize path separators and such. documentationFilePath = fileSystem.FileInfo.New(documentationFilePath).FullName; diff --git a/src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs b/src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs index 97fdf611d9..01cb2f7808 100644 --- a/src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs @@ -3,6 +3,7 @@ using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Git; +using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.OutputVariables; using GitVersion.VersionCalculation; @@ -117,9 +118,7 @@ public static void WriteVersionVariables(this RepositoryFixtureBase fixture, str { var versionVariables = fixture.GetVersion(); - using var stream = File.Open(versionFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); - using var writer = new StreamWriter(stream); - writer.Write(versionVariables.ToJson()); + FileSystemHelper.File.WriteAllText(versionFile, versionVariables.ToJson()); } public static void AssertFullSemver(this RepositoryFixtureBase fixture, string fullSemver, diff --git a/src/GitVersion.Core.Tests/Helpers/ExecutableHelper.cs b/src/GitVersion.Core.Tests/Helpers/ExecutableHelper.cs index d220bfa157..0918b3a9dd 100644 --- a/src/GitVersion.Core.Tests/Helpers/ExecutableHelper.cs +++ b/src/GitVersion.Core.Tests/Helpers/ExecutableHelper.cs @@ -6,7 +6,7 @@ public static class ExecutableHelper { public static string GetDotNetExecutable() => "dotnet"; - public static string GetExecutableArgs(string args) => $"{PathHelper.Combine(GetExeDirectory(), "gitversion.dll")} {args}"; + public static string GetExecutableArgs(string args) => $"{FileSystemHelper.Path.Combine(GetExeDirectory(), "gitversion.dll")} {args}"; - private static string GetExeDirectory() => PathHelper.GetCurrentDirectory().Replace("GitVersion.App.Tests", "GitVersion.App"); + private static string GetExeDirectory() => FileSystemHelper.Path.GetCurrentDirectory().Replace("GitVersion.App.Tests", "GitVersion.App"); } diff --git a/src/GitVersion.Core.Tests/Helpers/TestConsole.cs b/src/GitVersion.Core.Tests/Helpers/TestConsole.cs index 8a73e0e7db..7e48006020 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestConsole.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestConsole.cs @@ -9,9 +9,9 @@ public class TestConsole(params string[] responses) : IConsole private readonly Queue responses = new(responses); private readonly ILog log = new NullLog(); - public void WriteLine(string? msg) => this.log.Info(msg + PathHelper.NewLine); + public void WriteLine(string? msg) => this.log.Info(msg + FileSystemHelper.Path.NewLine); - public void WriteLine() => this.log.Info(PathHelper.NewLine); + public void WriteLine() => this.log.Info(FileSystemHelper.Path.NewLine); public void Write(string? msg) => this.log.Info(msg.NotNull()); diff --git a/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs index 17d9946478..5784d9472e 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs @@ -111,9 +111,8 @@ public void HasDirtyFlagWhenUncommittedChangesAreInRepository(bool stageFile, in for (int i = 0; i < numberOfFiles; i++) { - var tempFile = PathHelper.GetTempFileName(); - var repoFile = PathHelper.Combine(fixture.RepositoryPath, PathHelper.GetFileNameWithoutExtension(tempFile) + ".txt"); - fileSystem.File.Move(tempFile, repoFile); + var tempFile = FileSystemHelper.Path.GetRandomFileName(); + var repoFile = FileSystemHelper.Path.Combine(fixture.RepositoryPath, FileSystemHelper.Path.GetFileNameWithoutExtension(tempFile) + ".txt"); fileSystem.File.WriteAllText(repoFile, $"Hello world / testfile {i}"); if (stageFile) diff --git a/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs index 8d31541820..89cfd4c2ce 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs @@ -18,7 +18,7 @@ public void UseWorktreeRepositoryForVersion() var repoDir = fileSystem.DirectoryInfo.New(fixture.RepositoryPath); repoDir.Parent.ShouldNotBeNull(); - var worktreePath = PathHelper.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1"); + var worktreePath = FileSystemHelper.Path.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1"); fixture.Repository.MakeATaggedCommit("v1.0.0"); var branchV1 = fixture.Repository.CreateBranch("support/1.0"); diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index a1fffa9746..166dc8c600 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -221,7 +221,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:{PathHelper.NewLine}" + string.Join(PathHelper.NewLine, localRefs)); + this.log.Info($"Local Refs:{FileSystemHelper.Path.NewLine}" + string.Join(FileSystemHelper.Path.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 diff --git a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs index 92c48bd78b..ade7499fae 100644 --- a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs +++ b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs @@ -56,7 +56,7 @@ public GitVersionVariables CalculateVersionVariables() } catch (AggregateException e) { - this.log.Warning($"One or more exceptions during cache write:{PathHelper.NewLine}{e}"); + this.log.Warning($"One or more exceptions during cache write:{FileSystemHelper.Path.NewLine}{e}"); } return versionVariables; diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index bc8554f32e..d02f3d767d 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -196,8 +196,8 @@ public BranchCommit FindCommitBranchBranchedFrom(IBranch? branch, IGitVersionCon return possibleBranches.SingleOrDefault(); var first = possibleBranches[0]; - this.log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{PathHelper.NewLine}" + - $"This may result in incorrect commit counting.{PathHelper.NewLine}Options were:{PathHelper.NewLine}" + + this.log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{FileSystemHelper.Path.NewLine}" + + $"This may result in incorrect commit counting.{FileSystemHelper.Path.NewLine}Options were:{FileSystemHelper.Path.NewLine}" + string.Join(", ", possibleBranches.Select(b => b.Branch.ToString()))); return first; } diff --git a/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs b/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs index 65b6d0cb67..adb129c78d 100644 --- a/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs +++ b/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs @@ -122,35 +122,35 @@ public static (string GitDirectory, string WorkingTreeDirectory)? FindGitDir(thi string? startingDir = path; while (startingDir is not null) { - var dirOrFilePath = PathHelper.Combine(startingDir, ".git"); + var dirOrFilePath = FileSystemHelper.Path.Combine(startingDir, ".git"); if (fileSystem.Directory.Exists(dirOrFilePath)) { - return (dirOrFilePath, PathHelper.GetDirectoryName(dirOrFilePath)); + return (dirOrFilePath, FileSystemHelper.Path.GetDirectoryName(dirOrFilePath)); } if (fileSystem.File.Exists(dirOrFilePath)) { - string? relativeGitDirPath = ReadGitDirFromFile(dirOrFilePath); + string? relativeGitDirPath = ReadGitDirFromFile(fileSystem, dirOrFilePath); if (!string.IsNullOrWhiteSpace(relativeGitDirPath)) { - var fullGitDirPath = PathHelper.GetFullPath(PathHelper.Combine(startingDir, relativeGitDirPath)); + var fullGitDirPath = FileSystemHelper.Path.GetFullPath(FileSystemHelper.Path.Combine(startingDir, relativeGitDirPath)); if (fileSystem.Directory.Exists(fullGitDirPath)) { - return (fullGitDirPath, PathHelper.GetDirectoryName(dirOrFilePath)); + return (fullGitDirPath, FileSystemHelper.Path.GetDirectoryName(dirOrFilePath)); } } } - startingDir = PathHelper.GetDirectoryName(startingDir); + startingDir = FileSystemHelper.Path.GetDirectoryName(startingDir); } return null; } - private static string? ReadGitDirFromFile(string fileName) + private static string? ReadGitDirFromFile(IFileSystem fileSystem, string fileName) { const string expectedPrefix = "gitdir: "; - var firstLineOfFile = File.ReadLines(fileName).FirstOrDefault(); + var firstLineOfFile = fileSystem.File.ReadLines(fileName).FirstOrDefault(); if (firstLineOfFile?.StartsWith(expectedPrefix) ?? false) { return firstLineOfFile[expectedPrefix.Length..]; // strip off the prefix, leaving just the path diff --git a/src/GitVersion.Core/Helpers/DirectoryHelper.cs b/src/GitVersion.Core/Helpers/DirectoryHelper.cs deleted file mode 100644 index 357815c5e1..0000000000 --- a/src/GitVersion.Core/Helpers/DirectoryHelper.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace GitVersion.Helpers; - -internal static class DirectoryHelper -{ - public static void DeleteDirectory(string directoryPath) - { - // From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502 - - if (!Directory.Exists(directoryPath)) - { - Trace.WriteLine( - $"Directory '{directoryPath}' is missing and can't be removed."); - - return; - } - - var files = Directory.GetFiles(directoryPath); - var dirs = Directory.GetDirectories(directoryPath); - - foreach (var file in files) - { - File.SetAttributes(file, FileAttributes.Normal); - File.Delete(file); - } - - foreach (var dir in dirs) - { - DeleteDirectory(dir); - } - - File.SetAttributes(directoryPath, FileAttributes.Normal); - try - { - Directory.Delete(directoryPath, false); - } - catch (IOException) - { - Trace.WriteLine(string.Format("{0}The directory '{1}' could not be deleted!" + - "{0}Most of the time, this is due to an external process accessing the files in the temporary repositories created during the test runs, and keeping a handle on the directory, thus preventing the deletion of those files." + - "{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}", - PathHelper.NewLine, PathHelper.GetFullPath(directoryPath))); - } - } -} diff --git a/src/GitVersion.Core/Helpers/FileSystemHelper.cs b/src/GitVersion.Core/Helpers/FileSystemHelper.cs new file mode 100644 index 0000000000..45d63737d1 --- /dev/null +++ b/src/GitVersion.Core/Helpers/FileSystemHelper.cs @@ -0,0 +1,154 @@ +using System.IO.Abstractions; +using System.Runtime.InteropServices; + +namespace GitVersion.Helpers; + +internal static class FileSystemHelper +{ + private static readonly FileSystem fileSystem = new(); + + internal static class File + { + public static bool Exists(string path) => fileSystem.File.Exists(path); + public static void Delete(string path) => fileSystem.File.Delete(path); + public static string ReadAllText(string path) => fileSystem.File.ReadAllText(path); + public static void WriteAllText(string path, string? contents) => fileSystem.File.WriteAllText(path, contents); + } + + internal static class Directory + { + public static bool Exists(string directoryPath) => fileSystem.Directory.Exists(directoryPath); + + public static void DeleteDirectory(string directoryPath) + { + // From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502 + + if (!fileSystem.Directory.Exists(directoryPath)) + { + Trace.WriteLine($"Directory '{directoryPath}' is missing and can't be removed."); + + return; + } + + var files = fileSystem.Directory.GetFiles(directoryPath); + var dirs = fileSystem.Directory.GetDirectories(directoryPath); + + foreach (var file in files) + { + fileSystem.File.SetAttributes(file, FileAttributes.Normal); + fileSystem.File.Delete(file); + } + + foreach (var dir in dirs) + { + DeleteDirectory(dir); + } + + fileSystem.File.SetAttributes(directoryPath, FileAttributes.Normal); + try + { + fileSystem.Directory.Delete(directoryPath, false); + } + catch (IOException) + { + Trace.WriteLine(string.Format("{0}The directory '{1}' could not be deleted!" + + "{0}Most of the time, this is due to an external process accessing the files in the temporary repositories created during the test runs, and keeping a handle on the directory, thus preventing the deletion of those files." + + "{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}", + Path.NewLine, fileSystem.Path.GetFullPath(directoryPath))); + } + } + } + + internal static class Path + { + public static string NewLine => SysEnv.NewLine; + public static char DirectorySeparatorChar => fileSystem.Path.DirectorySeparatorChar; + + private static readonly StringComparison OsDependentComparison = + RuntimeInformation.IsOSPlatform(OSPlatform.Linux) + ? StringComparison.Ordinal + : StringComparison.OrdinalIgnoreCase; + + public static string GetCurrentDirectory() => AppContext.BaseDirectory ?? throw new InvalidOperationException(); + + public static string GetTempPathLegacy() => fileSystem.Path.GetTempPath(); + public static string GetTempPath() + { + var tempPath = GetCurrentDirectory(); + if (!string.IsNullOrWhiteSpace(SysEnv.GetEnvironmentVariable("RUNNER_TEMP"))) + { + tempPath = SysEnv.GetEnvironmentVariable("RUNNER_TEMP"); + } + + return tempPath!; + } + + public static string GetRepositoryTempPath() => Combine(GetTempPath(), "TestRepositories", Guid.NewGuid().ToString()); + + public static string GetDirectoryName(string? path) + { + ArgumentNullException.ThrowIfNull(path, nameof(path)); + + return fileSystem.Path.GetDirectoryName(path)!; + } + + public static string GetFileName(string? path) + { + ArgumentNullException.ThrowIfNull(path, nameof(path)); + + return fileSystem.Path.GetFileName(path); + } + + public static string? GetFileNameWithoutExtension(string? path) => fileSystem.Path.GetFileNameWithoutExtension(path); + + public static string? GetExtension(string? path) => fileSystem.Path.GetExtension(path); + + public static string GetFullPath(string? path) => fileSystem.Path.GetFullPath(path!); + + public static string Combine(string? path1, string? path2) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path1); + ArgumentException.ThrowIfNullOrWhiteSpace(path2); + + return fileSystem.Path.Combine(path1, path2); + } + + public static string Combine(string? path1) + { + ArgumentNullException.ThrowIfNull(path1, nameof(path1)); + + return fileSystem.Path.Combine(path1); + } + + public static string Combine(string? path1, string? path2, string? path3) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path1); + ArgumentException.ThrowIfNullOrWhiteSpace(path2); + ArgumentException.ThrowIfNullOrWhiteSpace(path3); + + return fileSystem.Path.Combine(path1, path2, path3); + } + + public static string Combine(string? path1, string? path2, string? path3, string? path4) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path1); + ArgumentException.ThrowIfNullOrWhiteSpace(path2); + ArgumentException.ThrowIfNullOrWhiteSpace(path3); + ArgumentException.ThrowIfNullOrWhiteSpace(path4); + + return fileSystem.Path.Combine(path1, path2, path3, path4); + } + + public static bool Equal(string? path, string? otherPath) => + string.Equals( + GetFullPath(path).TrimEnd('\\').TrimEnd('/'), + GetFullPath(otherPath).TrimEnd('\\').TrimEnd('/'), + OsDependentComparison); + + public static string GetRandomFileName() => fileSystem.Path.GetRandomFileName(); + + public static bool IsPathRooted(string? path) => fileSystem.Path.IsPathRooted(path); + } +} diff --git a/src/GitVersion.Core/Helpers/PathHelper.cs b/src/GitVersion.Core/Helpers/PathHelper.cs deleted file mode 100644 index 42c69c0f41..0000000000 --- a/src/GitVersion.Core/Helpers/PathHelper.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System.Runtime.InteropServices; - -namespace GitVersion.Helpers; - -internal static class PathHelper -{ - public static string NewLine => SysEnv.NewLine; - public static char DirectorySeparatorChar => Path.DirectorySeparatorChar; - - private static readonly StringComparison OsDependentComparison = - RuntimeInformation.IsOSPlatform(OSPlatform.Linux) - ? StringComparison.Ordinal - : StringComparison.OrdinalIgnoreCase; - - public static string GetCurrentDirectory() => AppContext.BaseDirectory ?? throw new InvalidOperationException(); - - public static string GetTempPath() - { - var tempPath = GetCurrentDirectory(); - if (!string.IsNullOrWhiteSpace(SysEnv.GetEnvironmentVariable("RUNNER_TEMP"))) - { - tempPath = SysEnv.GetEnvironmentVariable("RUNNER_TEMP"); - } - - return tempPath!; - } - - public static string GetRepositoryTempPath() => Combine(GetTempPath(), "TestRepositories", Guid.NewGuid().ToString()); - - public static string GetDirectoryName(string? path) - { - ArgumentNullException.ThrowIfNull(path, nameof(path)); - - return Path.GetDirectoryName(path)!; - } - - public static string GetFileName(string? path) - { - ArgumentNullException.ThrowIfNull(path, nameof(path)); - - return Path.GetFileName(path); - } - - public static string? GetFileNameWithoutExtension(string? path) => Path.GetFileNameWithoutExtension(path); - - public static string? GetExtension(string? path) => Path.GetExtension(path); - - public static string GetFullPath(string? path) => Path.GetFullPath(path!); - - public static string Combine(string? path1, string? path2) - { - ArgumentException.ThrowIfNullOrWhiteSpace(path1); - ArgumentException.ThrowIfNullOrWhiteSpace(path2); - - return Path.Combine(path1, path2); - } - - public static string Combine(string? path1) - { - ArgumentNullException.ThrowIfNull(path1, nameof(path1)); - - return Path.Combine(path1); - } - - public static string Combine(string? path1, string? path2, string? path3) - { - ArgumentException.ThrowIfNullOrWhiteSpace(path1); - ArgumentException.ThrowIfNullOrWhiteSpace(path2); - ArgumentException.ThrowIfNullOrWhiteSpace(path3); - - return Path.Combine(path1, path2, path3); - } - - public static string Combine(string? path1, string? path2, string? path3, string? path4) - { - ArgumentException.ThrowIfNullOrWhiteSpace(path1); - ArgumentException.ThrowIfNullOrWhiteSpace(path2); - ArgumentException.ThrowIfNullOrWhiteSpace(path3); - ArgumentException.ThrowIfNullOrWhiteSpace(path4); - - return Path.Combine(path1, path2, path3, path4); - } - - public static bool Equal(string? path, string? otherPath) => - string.Equals( - GetFullPath(path).TrimEnd('\\').TrimEnd('/'), - GetFullPath(otherPath).TrimEnd('\\').TrimEnd('/'), - OsDependentComparison); - - public static string GetRandomFileName() => Path.GetRandomFileName(); - - public static string GetTempFileName() => Path.GetTempFileName(); - - public static bool IsPathRooted(string? path) => Path.IsPathRooted(path); -} diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs index b024a27a22..4029c0e0d2 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs @@ -44,7 +44,7 @@ private string GetGitSystemHash() var dotGitDirectory = this.repositoryInfo.DotGitDirectory; // traverse the directory and get a list of files, use that for GetHash - var contents = CalculateDirectoryContents(PathHelper.Combine(dotGitDirectory, "refs")); + var contents = CalculateDirectoryContents(FileSystemHelper.Path.Combine(dotGitDirectory, "refs")); return GetHash([.. contents]); } @@ -118,7 +118,7 @@ private List CalculateDirectoryContents(string root) try { if (!this.fileSystem.File.Exists(file)) continue; - result.Add(PathHelper.GetFileName(file)); + result.Add(FileSystemHelper.Path.GetFileName(file)); result.Add(this.fileSystem.File.ReadAllText(file)); } catch (IOException e) diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs index 59363dc86f..d80979db7a 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs @@ -85,7 +85,7 @@ internal string GetCacheFileName(GitVersionCacheKey cacheKey) internal string GetCacheDirectory() { var gitDir = this.repositoryInfo.DotGitDirectory; - return PathHelper.Combine(gitDir, "gitversion_cache"); + return FileSystemHelper.Path.Combine(gitDir, "gitversion_cache"); } private string PrepareCacheDirectory() @@ -104,5 +104,5 @@ private GitVersionCacheKey GetCacheKey() return cacheKey; } - private static string GetCacheFileName(GitVersionCacheKey key, string cacheDir) => PathHelper.Combine(cacheDir, key.Value); + private static string GetCacheFileName(GitVersionCacheKey key, string cacheDir) => FileSystemHelper.Path.Combine(cacheDir, key.Value); } diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.mutating.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.mutating.cs index d4e6827dd6..b3b8f919aa 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.mutating.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.mutating.cs @@ -93,7 +93,7 @@ private DirectReference GetPullRequestReference(AuthenticationInfo auth, LibGit2 : network.ListReferences(remote)) .Select(r => r.ResolveToDirectReference()).ToList(); - this.log.Info($"Remote Refs:{PathHelper.NewLine}" + string.Join(PathHelper.NewLine, remoteTips.Select(r => r.CanonicalName))); + this.log.Info($"Remote Refs:{FileSystemHelper.Path.NewLine}" + string.Join(FileSystemHelper.Path.NewLine, remoteTips.Select(r => r.CanonicalName))); var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList(); switch (refs.Count) diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index d5df195240..070a5f130f 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -40,9 +40,9 @@ public GitRepositoryInfo(IFileSystem fileSystem, IOptions opt var targetUrl = repositoryInfo.TargetUrl; var clonePath = repositoryInfo.ClonePath; - var userTemp = clonePath ?? PathHelper.GetTempPath(); + var userTemp = clonePath ?? FileSystemHelper.Path.GetTempPath(); var repositoryName = targetUrl.Split('/', '\\').Last().Replace(".git", string.Empty); - var possiblePath = PathHelper.Combine(userTemp, repositoryName); + var possiblePath = FileSystemHelper.Path.Combine(userTemp, repositoryName); // Verify that the existing directory is ok for us to use if (this.fileSystem.Directory.Exists(possiblePath) && !GitRepoHasMatchingRemote(possiblePath, targetUrl)) @@ -57,7 +57,7 @@ public GitRepositoryInfo(IFileSystem fileSystem, IOptions opt } while (possiblePathExists && !GitRepoHasMatchingRemote(possiblePath, targetUrl)); } - var repositoryPath = PathHelper.Combine(possiblePath, ".git"); + var repositoryPath = FileSystemHelper.Path.Combine(possiblePath, ".git"); return repositoryPath; } @@ -72,7 +72,7 @@ public GitRepositoryInfo(IFileSystem fileSystem, IOptions opt throw new DirectoryNotFoundException("Cannot find the .git directory"); var directoryInfo = this.fileSystem.Directory.GetParent(gitDirectory) ?? throw new DirectoryNotFoundException("Cannot find the .git directory"); - return gitDirectory.Contains(PathHelper.Combine(".git", "worktrees")) + return gitDirectory.Contains(FileSystemHelper.Path.Combine(".git", "worktrees")) ? this.fileSystem.Directory.GetParent(directoryInfo.FullName)?.FullName : gitDirectory; } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs index c0a0bc82b0..1d1c138d8c 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs @@ -24,9 +24,9 @@ public MsBuildExeFixture(RepositoryFixtureBase fixture, string workingDirectory { var projectExtension = AssemblyInfoFileHelper.GetProjectExtension(language); this.fixture = fixture; - this.ProjectPath = PathHelper.Combine(workingDirectory, $"app.{projectExtension}"); + this.ProjectPath = FileSystemHelper.Path.Combine(workingDirectory, $"app.{projectExtension}"); - var versionFile = PathHelper.Combine(workingDirectory, "gitversion.json"); + var versionFile = FileSystemHelper.Path.Combine(workingDirectory, "gitversion.json"); fixture.WriteVersionVariables(versionFile); } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index 0e8eac0e9a..3efac8d61d 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -18,7 +18,7 @@ public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBa task.BuildEngine = buildEngine; - var versionFile = PathHelper.Combine(task.SolutionDirectory, "gitversion.json"); + var versionFile = FileSystemHelper.Path.Combine(task.SolutionDirectory, "gitversion.json"); fixture.WriteVersionVariables(versionFile); task.VersionFile = versionFile; diff --git a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs index 2efca18ee2..3607471cd0 100644 --- a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs +++ b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs @@ -18,8 +18,8 @@ public void CreateTemporaryProject() { var sp = ConfigureServices(); this.fileSystem = sp.GetRequiredService(); - this.projectDirectory = PathHelper.Combine(PathHelper.GetTempPath(), Guid.NewGuid().ToString()); - this.projectFile = PathHelper.Combine(this.projectDirectory, "Fake.csproj"); + this.projectDirectory = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), Guid.NewGuid().ToString()); + this.projectFile = FileSystemHelper.Path.Combine(this.projectDirectory, "Fake.csproj"); this.fileSystem.Directory.CreateDirectory(this.projectDirectory); @@ -32,7 +32,7 @@ public void CreateTemporaryProject() [Test] public void VerifyIgnoreNonAssemblyInfoFile() { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "SomeOtherthis.fileSystem.File.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "SomeOtherthis.fileSystem.File.cs"))) { writer.Write(""" @@ -50,7 +50,7 @@ public void VerifyIgnoreNonAssemblyInfoFile() [Test] public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -70,7 +70,7 @@ public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileV [Test] public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -91,7 +91,7 @@ public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "As [Test] public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -109,7 +109,7 @@ public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVer [Test] public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -126,7 +126,7 @@ public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion" [Test] public void VerifyStringWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -147,7 +147,7 @@ public class Temp [Test] public void VerifyIdentifierWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -167,7 +167,7 @@ public class {0} [Test] public void VerifyAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -187,7 +187,7 @@ Imports System.Reflection [Test] public void VerifyUnformattedAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -208,7 +208,7 @@ Imports System.Reflection [Test] public void VerifyCommentWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -226,7 +226,7 @@ Imports System.Reflection [Test] public void VerifyCommentWithNoNewLineAtEndWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -243,7 +243,7 @@ Imports System.Reflection [Test] public void VerifyStringWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -263,7 +263,7 @@ End Class [Test] public void VerifyIdentifierWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -282,7 +282,7 @@ End Class [Test] public void VerifyAttributeFoundFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -302,7 +302,7 @@ open System.Reflection [Test] public void VerifyUnformattedAttributeFoundFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -323,7 +323,7 @@ open System.Reflection [Test] public void VerifyCommentWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -341,7 +341,7 @@ open System.Reflection [Test] public void VerifyCommentWithNoNewLineAtEndWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -358,7 +358,7 @@ open System.Reflection [Test] public void VerifyStringWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -377,7 +377,7 @@ type Temp() = [Test] public void VerifyIdentifierWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(FileSystemHelper.Path.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" diff --git a/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs index 9a2892572b..d4e3328e7c 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs @@ -76,7 +76,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuild( result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -103,7 +103,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildI result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -133,7 +133,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenIntermediateOut fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.MajorMinorPatch), "1.2.4")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.FullSemVer), "1.2.4-1")); - DirectoryHelper.DeleteDirectory(task.IntermediateOutputPath); + FileSystemHelper.Directory.DeleteDirectory(task.IntermediateOutputPath); } [TestCaseSource(nameof(Languages))] @@ -155,7 +155,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServerWhenIn fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.MajorMinorPatch), "1.0.1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.FullSemVer), "1.0.1-1")); - DirectoryHelper.DeleteDirectory(task.IntermediateOutputPath); + FileSystemHelper.Directory.DeleteDirectory(task.IntermediateOutputPath); } [TestCaseSource(nameof(Languages))] @@ -168,7 +168,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => { - var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); + var intermediateOutputPath = FileSystemHelper.Path.Combine("$(MSBuildProjectDirectory)", randDir); AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, language, intermediateOutputPath); }, language); @@ -178,7 +178,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -199,7 +199,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => { - var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); + var intermediateOutputPath = FileSystemHelper.Path.Combine("$(MSBuildProjectDirectory)", randDir); AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, language, intermediateOutputPath); }, language); @@ -209,7 +209,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -230,7 +230,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => { - var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); + var intermediateOutputPath = FileSystemHelper.Path.Combine("$(MSBuildProjectDirectory)", randDir); AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, language, intermediateOutputPath).Property("UseProjectNamespaceForGitVersionInformation", "True").Property("RootNamespace", "Test.Root"); }, language); @@ -240,7 +240,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -263,7 +263,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => { - var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); + var intermediateOutputPath = FileSystemHelper.Path.Combine("$(MSBuildProjectDirectory)", randDir); AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, language, intermediateOutputPath).Property("UseProjectNamespaceForGitVersionInformation", "True"); }, language); @@ -273,7 +273,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs index fc155e8bb3..e2f1bbcdd5 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs @@ -50,7 +50,7 @@ protected static MsBuildExeFixtureResult ExecuteMsBuildExe(Action ExecuteMsBuildTaskInAzurePipeline(T task, string? buildNumber = null, string? configurationText = null) where T : GitVersionTaskBase + protected MsBuildTaskFixtureResult ExecuteMsBuildTaskInAzurePipeline(T task, string? buildNumber = null, string? configurationText = null) where T : GitVersionTaskBase { var fixture = CreateRemoteRepositoryFixture(); task.SolutionDirectory = fixture.LocalRepositoryFixture.RepositoryPath; @@ -123,9 +123,9 @@ private static RemoteRepositoryFixture CreateRemoteRepositoryFixture() return fixture; } - private static void CreateConfiguration(string repoFolder, string content) + private void CreateConfiguration(string repoFolder, string content) { - var configFilePath = PathHelper.Combine(repoFolder, ConfigurationFileLocator.DefaultFileName); - File.WriteAllText(configFilePath, content); + var configFilePath = FileSystemHelper.Path.Combine(repoFolder, ConfigurationFileLocator.DefaultFileName); + this.FileSystem.File.WriteAllText(configFilePath, content); } } diff --git a/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs index 71cf8d8b7a..239621caa6 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs @@ -66,7 +66,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuild(string lang result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -89,7 +89,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildInBuildServe result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -111,7 +111,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoes var fileContent = this.FileSystem.File.ReadAllText(result.Task.AssemblyInfoTempFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.2.4.0"")"); - DirectoryHelper.DeleteDirectory(task.IntermediateOutputPath); + FileSystemHelper.Directory.DeleteDirectory(task.IntermediateOutputPath); } [TestCaseSource(nameof(Languages))] @@ -129,7 +129,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoes var fileContent = this.FileSystem.File.ReadAllText(result.Task.AssemblyInfoTempFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.0.1.0"")"); - DirectoryHelper.DeleteDirectory(task.IntermediateOutputPath); + FileSystemHelper.Directory.DeleteDirectory(task.IntermediateOutputPath); } [TestCaseSource(nameof(Languages))] @@ -142,7 +142,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => { - var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); + var intermediateOutputPath = FileSystemHelper.Path.Combine("$(MSBuildProjectDirectory)", randDir); AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty, language, intermediateOutputPath); }, language); @@ -152,7 +152,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); @@ -169,7 +169,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => { - var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); + var intermediateOutputPath = FileSystemHelper.Path.Combine("$(MSBuildProjectDirectory)", randDir); AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty, language, intermediateOutputPath); }, language); @@ -179,7 +179,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); + var generatedFilePath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs index d45eff7758..c979681ed5 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs @@ -71,7 +71,7 @@ public void WriteVersionInfoTaskShouldLogOutputVariablesToBuildOutputInGitHubAct return; } - envFilePath = $"{PathHelper.GetTempPath()}/github-env.txt"; + envFilePath = $"{FileSystemHelper.Path.GetTempPath()}/github-env.txt"; SysEnv.SetEnvironmentVariable("GITHUB_ENV", envFilePath); var task = new WriteVersionInfoToBuildLog(); diff --git a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs index a5c7ed5e25..9597ba52fa 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs @@ -44,7 +44,7 @@ public void UpdateAssemblyInfo(UpdateAssemblyInfo task) } var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "AssemblyInfo"); - task.AssemblyInfoTempFilePath = PathHelper.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); + task.AssemblyInfoTempFilePath = FileSystemHelper.Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); if (!this.fileSystem.Directory.Exists(fileWriteInfo.WorkingDirectory)) { @@ -70,7 +70,7 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) } var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "GitVersionInformation"); - task.GitVersionInformationFilePath = PathHelper.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); + task.GitVersionInformationFilePath = FileSystemHelper.Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); if (!this.fileSystem.Directory.Exists(fileWriteInfo.WorkingDirectory)) { @@ -90,7 +90,7 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) targetNamespace = task.RootNamespace; if (string.IsNullOrWhiteSpace(targetNamespace)) { - targetNamespace = PathHelper.GetFileNameWithoutExtension(task.ProjectFile); + targetNamespace = FileSystemHelper.Path.GetFileNameWithoutExtension(task.ProjectFile); } } diff --git a/src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs b/src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs index ae730660e5..3d23539051 100644 --- a/src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs @@ -11,7 +11,7 @@ internal static class AssemblyInfoFileHelper { public static readonly string TempPath = MakeAndGetTempPath(); - private static string MakeAndGetTempPath() => PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionTask"); + private static string MakeAndGetTempPath() => FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "GitVersionTask"); public static string GetFileExtension(string language) => language switch { @@ -40,7 +40,7 @@ public static void CheckForInvalidFiles(IFileSystem fileSystem, IEnumerable me.Value.StartsWith("//") || me.Value.StartsWith("'") ? PathHelper.NewLine : string.Empty); + var noCommentsOrStrings = triviaRegex.Replace(allText, me => me.Value.StartsWith("//") || me.Value.StartsWith("'") ? FileSystemHelper.Path.NewLine : string.Empty); return attributeRegex.IsMatch(noCommentsOrStrings); } @@ -75,7 +75,7 @@ public static FileWriteInfo GetFileWriteInfo(this string? intermediateOutputPath if (intermediateOutputPath == null) { - fileName = $"{outputFileName}_{PathHelper.GetFileNameWithoutExtension(projectFile)}_{PathHelper.GetRandomFileName()}.g.{fileExtension}"; + fileName = $"{outputFileName}_{FileSystemHelper.Path.GetFileNameWithoutExtension(projectFile)}_{FileSystemHelper.Path.GetRandomFileName()}.g.{fileExtension}"; workingDirectory = TempPath; } else diff --git a/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs b/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs index 8b6fbd9fdd..166f4eb65d 100644 --- a/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs +++ b/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs @@ -20,7 +20,7 @@ public void WriteTo(LogLevel level, string message) private void WriteLogEntry(LogLevel level, string str) { - var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{str}{PathHelper.NewLine}"; + var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{str}{FileSystemHelper.Path.NewLine}"; switch (level) { case LogLevel.Fatal: diff --git a/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs b/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs index bf5ea3e1d5..7f10ab7ef6 100644 --- a/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs +++ b/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs @@ -20,10 +20,10 @@ public class AssemblyInfoFileUpdaterTests : TestBase private string workingDir; [OneTimeSetUp] - public void OneTimeSetUp() => workingDir = PathHelper.Combine(PathHelper.GetTempPath(), nameof(AssemblyInfoFileUpdaterTests)); + public void OneTimeSetUp() => workingDir = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), nameof(AssemblyInfoFileUpdaterTests)); [OneTimeTearDown] - public void OneTimeTearDown() => DirectoryHelper.DeleteDirectory(workingDir); + public void OneTimeTearDown() => FileSystemHelper.Directory.DeleteDirectory(workingDir); [SetUp] public void Setup() @@ -43,7 +43,7 @@ public void Setup() public void ShouldCreateAssemblyInfoFileWhenNotExistsAndEnsureAssemblyInfo(string fileExtension) { var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension; - var fullPath = PathHelper.Combine(workingDir, assemblyInfoFile); + var fullPath = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); var variables = this.variableProvider.GetVariablesFor( SemanticVersion.Parse("1.0.0", RegexPatterns.Configuration.DefaultTagPrefixPattern), EmptyConfigurationBuilder.New.Build(), 0); @@ -51,7 +51,7 @@ public void ShouldCreateAssemblyInfoFileWhenNotExistsAndEnsureAssemblyInfo(strin using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new(workingDir, true, assemblyInfoFile)); - this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); } [TestCase("cs")] @@ -59,8 +59,8 @@ public void ShouldCreateAssemblyInfoFileWhenNotExistsAndEnsureAssemblyInfo(strin [TestCase("vb")] public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo(string fileExtension) { - var assemblyInfoFile = PathHelper.Combine("src", "Project", "Properties", $"VersionAssemblyInfo.{fileExtension}"); - var fullPath = PathHelper.Combine(workingDir, assemblyInfoFile); + var assemblyInfoFile = FileSystemHelper.Path.Combine("src", "Project", "Properties", $"VersionAssemblyInfo.{fileExtension}"); + var fullPath = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); var variables = this.variableProvider.GetVariablesFor( SemanticVersion.Parse("1.0.0", RegexPatterns.Configuration.DefaultTagPrefixPattern), EmptyConfigurationBuilder.New.Build(), 0 ); @@ -68,7 +68,7 @@ public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new(workingDir, true, assemblyInfoFile)); - this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); } [TestCase("cs")] @@ -76,7 +76,7 @@ public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo [TestCase("vb")] public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInfo(string fileExtension) { - var assemblyInfoFiles = new HashSet { "AssemblyInfo." + fileExtension, PathHelper.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension) }; + var assemblyInfoFiles = new HashSet { "AssemblyInfo." + fileExtension, FileSystemHelper.Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension) }; var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", RegexPatterns.Configuration.DefaultTagPrefixPattern), EmptyConfigurationBuilder.New.Build(), 0); using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); @@ -84,8 +84,8 @@ public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInf foreach (var item in assemblyInfoFiles) { - var fullPath = PathHelper.Combine(workingDir, item); - this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + var fullPath = FileSystemHelper.Path.Combine(workingDir, item); + this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); } } @@ -95,7 +95,7 @@ public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInf public void ShouldNotCreateAssemblyInfoFileWhenNotExistsAndNotEnsureAssemblyInfo(string fileExtension) { var assemblyInfoFile = "NoVersionAssemblyInfo." + fileExtension; - var fullPath = PathHelper.Combine(workingDir, assemblyInfoFile); + var fullPath = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); var variables = this.variableProvider.GetVariablesFor( SemanticVersion.Parse("1.0.0", RegexPatterns.Configuration.DefaultTagPrefixPattern), EmptyConfigurationBuilder.New.Build(), 0 ); @@ -112,7 +112,7 @@ public void ShouldNotCreateAssemblyInfoFileForUnknownSourceCodeAndEnsureAssembly this.fileSystem = Substitute.For(); const string assemblyInfoFile = "VersionAssemblyInfo.js"; - var fullPath = PathHelper.Combine(workingDir, assemblyInfoFile); + var fullPath = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); var variables = this.variableProvider.GetVariablesFor( SemanticVersion.Parse("1.0.0", RegexPatterns.Configuration.DefaultTagPrefixPattern), EmptyConfigurationBuilder.New.Build(), 0 ); @@ -145,7 +145,7 @@ public void ShouldStartSearchFromWorkingDirectory() public void ShouldReplaceAssemblyVersion(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -165,7 +165,7 @@ public void ShouldReplaceAssemblyVersion(string fileExtension, string assemblyFi public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, (fs, variables) => { @@ -173,7 +173,7 @@ public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileEx assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.File.ReadAllText(fileName); - assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); }); } @@ -182,8 +182,8 @@ public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileEx [TestCase("vb", "\r\n\r\n")] public void ShouldReplaceAssemblyVersionInRelativePath(string fileExtension, string assemblyFileContent) { - var assemblyInfoFile = PathHelper.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var assemblyInfoFile = FileSystemHelper.Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -202,8 +202,8 @@ public void ShouldReplaceAssemblyVersionInRelativePath(string fileExtension, str [TestCase("vb", "\r\n\r\n")] public void ShouldReplaceAssemblyVersionInRelativePathWithWhiteSpace(string fileExtension, string assemblyFileContent) { - var assemblyInfoFile = PathHelper.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var assemblyInfoFile = FileSystemHelper.Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -223,7 +223,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithWhiteSpace(string file public void ShouldReplaceAssemblyVersionWithStar(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -243,7 +243,7 @@ public void ShouldReplaceAssemblyVersionWithStar(string fileExtension, string as public void ShouldReplaceAssemblyVersionWithAttributeSuffix(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { @@ -266,7 +266,7 @@ public void ShouldReplaceAssemblyVersionWithAttributeSuffix(string fileExtension public void ShouldAddAssemblyVersionIfMissingFromInfoFile(string fileExtension) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile("", fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -286,7 +286,7 @@ public void ShouldAddAssemblyVersionIfMissingFromInfoFile(string fileExtension) public void ShouldReplaceAlreadySubstitutedValues(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -306,7 +306,7 @@ public void ShouldReplaceAlreadySubstitutedValues(string fileExtension, string a public void ShouldReplaceAssemblyVersionWhenCreatingAssemblyVersionFileAndEnsureAssemblyInfo(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { @@ -325,8 +325,8 @@ public void ShouldReplaceAssemblyVersionWhenCreatingAssemblyVersionFileAndEnsure [TestCase("vb", "\r\n\r\n")] public void ShouldReplaceAssemblyVersionInRelativePathWithVariables(string fileExtension, string assemblyFileContent) { - var assemblyInfoFile = PathHelper.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var assemblyInfoFile = FileSystemHelper.Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -345,8 +345,8 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariables(string fileE [TestCase("vb", "\r\n\r\n")] public void ShouldReplaceAssemblyVersionInRelativePathWithVariablesAndWhiteSpace(string fileExtension, string assemblyFileContent) { - var assemblyInfoFile = PathHelper.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var assemblyInfoFile = FileSystemHelper.Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { @@ -366,7 +366,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariablesAndWhiteSpace public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { @@ -374,7 +374,7 @@ public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.File.ReadAllText(fileName); - assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); }); } @@ -384,7 +384,7 @@ public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { @@ -392,7 +392,7 @@ public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttri assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.File.ReadAllText(fileName); - assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); }); } @@ -402,7 +402,7 @@ public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttri public void ShouldNotAddAssemblyInformationalVersionWhenVersionSchemeIsNone(string fileExtension, string assemblyFileContent) { var assemblyInfoFile = "AssemblyInfo." + fileExtension; - var fileName = PathHelper.Combine(workingDir, assemblyInfoFile); + var fileName = FileSystemHelper.Path.Combine(workingDir, assemblyInfoFile); VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, (fs, variables) => { @@ -410,7 +410,7 @@ public void ShouldNotAddAssemblyInformationalVersionWhenVersionSchemeIsNone(stri assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.File.ReadAllText(fileName); - assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); }); } diff --git a/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs b/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs index 0d7fc9f14c..08893eeac1 100644 --- a/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs +++ b/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs @@ -34,11 +34,11 @@ public void ShouldCreateFile(string fileExtension) var fileSystem = sp.GetRequiredService(); - var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); + var directory = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); if (!fileSystem.Directory.Exists(directory)) fileSystem.Directory.CreateDirectory(directory); var fileName = "GitVersionInformation.g." + fileExtension; - var fullPath = PathHelper.Combine(directory, fileName); + var fullPath = FileSystemHelper.Path.Combine(directory, fileName); var variableProvider = sp.GetRequiredService(); var variables = variableProvider.GetVariablesFor(semanticVersion, EmptyConfigurationBuilder.New.Build(), 0); @@ -46,9 +46,9 @@ public void ShouldCreateFile(string fileExtension) generator.Execute(variables, new(directory, fileName, fileExtension)); - fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); - DirectoryHelper.DeleteDirectory(directory); + FileSystemHelper.Directory.DeleteDirectory(directory); } /// @@ -75,11 +75,11 @@ public void ShouldProperlyOutputNamespaceDeclaration(string fileExtension) var fileSystem = sp.GetRequiredService(); - var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); + var directory = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); if (!fileSystem.Directory.Exists(directory)) fileSystem.Directory.CreateDirectory(directory); var fileName = "GitVersionInformation.g." + fileExtension; - var fullPath = PathHelper.Combine(directory, fileName); + var fullPath = FileSystemHelper.Path.Combine(directory, fileName); var variableProvider = sp.GetRequiredService(); var variables = variableProvider.GetVariablesFor(semanticVersion, EmptyConfigurationBuilder.New.Build(), 0); @@ -87,8 +87,8 @@ public void ShouldProperlyOutputNamespaceDeclaration(string fileExtension) generator.Execute(variables, new(directory, fileName, fileExtension, targetNamespace)); - fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved", fileExtension))); - DirectoryHelper.DeleteDirectory(directory); + FileSystemHelper.Directory.DeleteDirectory(directory); } } diff --git a/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs b/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs index bca5e0cade..02fc6024b6 100644 --- a/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs +++ b/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs @@ -274,8 +274,8 @@ public void UpdateProjectXmlVersionElementWithMultipleVersionElementsLastOneIsMo """)] public void UpdateProjectFileAddsVersionToFile(string xml) { - var workingDirectory = PathHelper.GetTempPath(); - var fileName = PathHelper.Combine(workingDirectory, "TestProject.csproj"); + var workingDirectory = FileSystemHelper.Path.GetTempPath(); + var fileName = FileSystemHelper.Path.Combine(workingDirectory, "TestProject.csproj"); VerifyAssemblyInfoFile(xml, fileName, AssemblyVersioningScheme.MajorMinorPatch, (fs, variables) => { diff --git a/src/GitVersion.Output.Tests/Output/WixFileTests.cs b/src/GitVersion.Output.Tests/Output/WixFileTests.cs index cda4d0c1a4..1b923c75f5 100644 --- a/src/GitVersion.Output.Tests/Output/WixFileTests.cs +++ b/src/GitVersion.Output.Tests/Output/WixFileTests.cs @@ -16,10 +16,10 @@ internal class WixFileTests : TestBase private string workingDir; [OneTimeSetUp] - public void OneTimeSetUp() => workingDir = PathHelper.Combine(PathHelper.GetTempPath(), "WixFileTests"); + public void OneTimeSetUp() => workingDir = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "WixFileTests"); [OneTimeTearDown] - public void OneTimeTearDown() => DirectoryHelper.DeleteDirectory(workingDir); + public void OneTimeTearDown() => FileSystemHelper.Directory.DeleteDirectory(workingDir); [SetUp] public void Setup() => ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); @@ -57,10 +57,10 @@ public void UpdateWixVersionFile() wixVersionFileUpdater.Execute(versionVariables, new(workingDir)); - var file = PathHelper.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); + var file = FileSystemHelper.Path.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); fileSystem .File.ReadAllText(file) - .ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved"))); + .ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved"))); } [Test] @@ -95,7 +95,7 @@ public void UpdateWixVersionFileWhenFileAlreadyExists() using var wixVersionFileUpdater = sp.GetRequiredService(); // fake an already existing file - var file = PathHelper.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); + var file = FileSystemHelper.Path.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); if (!fileSystem.Directory.Exists(workingDir)) { fileSystem.Directory.CreateDirectory(workingDir); @@ -106,6 +106,6 @@ public void UpdateWixVersionFileWhenFileAlreadyExists() fileSystem .File.ReadAllText(file) - .ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved"))); + .ShouldMatchApproved(c => c.SubFolder(FileSystemHelper.Path.Combine("Approved"))); } } diff --git a/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs b/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs index b80c7a1669..d4cb0a2c86 100644 --- a/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs +++ b/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs @@ -154,7 +154,7 @@ private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) { foreach (var item in assemblyInfoFileNames) { - var fullPath = PathHelper.Combine(workingDirectory, item); + var fullPath = FileSystemHelper.Path.Combine(workingDirectory, item); if (EnsureVersionAssemblyInfoFile(fullPath, ensureAssemblyInfo)) { @@ -189,7 +189,7 @@ private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyI return false; } - var assemblyInfoSource = this.templateManager.GetTemplateFor(PathHelper.GetExtension(fullPath)!); + var assemblyInfoSource = this.templateManager.GetTemplateFor(FileSystemHelper.Path.GetExtension(fullPath)!); if (!assemblyInfoSource.IsNullOrWhiteSpace()) { diff --git a/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs index 163b0592a3..aa9789540c 100644 --- a/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs @@ -183,7 +183,7 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) { foreach (var item in assemblyInfoFileNames) { - var fullPath = PathHelper.Combine(workingDirectory, item); + var fullPath = FileSystemHelper.Path.Combine(workingDirectory, item); if (fileSystem.File.Exists(fullPath)) { diff --git a/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs b/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs index 6c6fe70625..1fd1a418c6 100644 --- a/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs +++ b/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs @@ -17,7 +17,7 @@ public void Execute(GitVersionVariables variables, GitVersionInfoContext context { var fileName = context.FileName; var directory = context.WorkingDirectory; - var filePath = PathHelper.Combine(directory, fileName); + var filePath = FileSystemHelper.Path.Combine(directory, fileName); string? originalFileContents = null; @@ -26,7 +26,7 @@ public void Execute(GitVersionVariables variables, GitVersionInfoContext context originalFileContents = this.fileSystem.File.ReadAllText(filePath); } - var fileExtension = PathHelper.GetExtension(filePath); + var fileExtension = FileSystemHelper.Path.GetExtension(filePath); ArgumentNullException.ThrowIfNull(fileExtension); var template = this.templateManager.GetTemplateFor(fileExtension); @@ -44,13 +44,13 @@ public void Execute(GitVersionVariables variables, GitVersionInfoContext context if (!string.IsNullOrWhiteSpace(targetNamespace) && fileExtension == ".cs") { indent = " "; - closeBracket = PathHelper.NewLine + "}"; - openBracket = PathHelper.NewLine + "{"; + closeBracket = FileSystemHelper.Path.NewLine + "}"; + openBracket = FileSystemHelper.Path.NewLine + "{"; indentation += " "; } var lines = variables.OrderBy(x => x.Key).Select(v => string.Format(indentation + addFormat, v.Key, v.Value)); - var members = string.Join(PathHelper.NewLine, lines); + var members = string.Join(FileSystemHelper.Path.NewLine, lines); var fileContents = string.Format(template, members, targetNamespace, openBracket, closeBracket, indent); @@ -64,7 +64,7 @@ public void Execute(GitVersionVariables variables, GitVersionInfoContext context string getTargetNamespace(string? extension) => extension switch { ".vb" => context.TargetNamespace ?? "Global", - ".cs" => context.TargetNamespace != null ? $"{PathHelper.NewLine}namespace {context.TargetNamespace}" : "", + ".cs" => context.TargetNamespace != null ? $"{FileSystemHelper.Path.NewLine}namespace {context.TargetNamespace}" : "", ".fs" => context.TargetNamespace ?? "global", _ => targetNamespaceSentinelValue, }; diff --git a/src/GitVersion.Output/TemplateManager.cs b/src/GitVersion.Output/TemplateManager.cs index da90e205aa..b8c8b205f5 100644 --- a/src/GitVersion.Output/TemplateManager.cs +++ b/src/GitVersion.Output/TemplateManager.cs @@ -57,7 +57,7 @@ public bool IsSupported(string fileExtension) { if (name.Contains(templateType.ToString()) && name.Contains(templateCategory)) { - var extension = PathHelper.GetExtension(name); + var extension = FileSystemHelper.Path.GetExtension(name); if (string.IsNullOrWhiteSpace(extension)) { continue; diff --git a/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs b/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs index a6d1b708fc..b7ecd65565 100644 --- a/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs +++ b/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs @@ -16,7 +16,7 @@ internal sealed class WixVersionFileUpdater(ILog log, IFileSystem fileSystem) : public void Execute(GitVersionVariables variables, WixVersionContext context) { - this.wixVersionFile = PathHelper.Combine(context.WorkingDirectory, WixVersionFileName); + this.wixVersionFile = FileSystemHelper.Path.Combine(context.WorkingDirectory, WixVersionFileName); this.log.Info("Updating GitVersion_WixVersion.wxi"); var doc = new XmlDocument(); diff --git a/src/GitVersion.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs b/src/GitVersion.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs index 1d97d7a79b..ebf88bf939 100644 --- a/src/GitVersion.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs +++ b/src/GitVersion.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs @@ -26,8 +26,8 @@ public BaseGitFlowRepositoryFixture(Action initialMainAction, strin private void SetupRepo(Action initialMainAction) { - var randomFile = PathHelper.Combine(Repository.Info.WorkingDirectory, Guid.NewGuid().ToString()); - File.WriteAllText(randomFile, string.Empty); + var randomFile = FileSystemHelper.Path.Combine(Repository.Info.WorkingDirectory, Guid.NewGuid().ToString()); + FileSystemHelper.File.WriteAllText(randomFile, string.Empty); Commands.Stage(Repository, randomFile); initialMainAction(Repository); diff --git a/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs index 4817162321..2f665ce557 100644 --- a/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs @@ -10,7 +10,7 @@ namespace GitVersion.Testing; public abstract class RepositoryFixtureBase : IDisposable { protected RepositoryFixtureBase(Func repositoryBuilder) - : this(repositoryBuilder(PathHelper.GetRepositoryTempPath())) + : this(repositoryBuilder(FileSystemHelper.Path.GetRepositoryTempPath())) { } @@ -45,12 +45,12 @@ protected virtual void Dispose(bool disposing) } Repository.Dispose(); - var directoryPath = PathHelper.GetFileName(RepositoryPath); + var directoryPath = FileSystemHelper.Path.GetFileName(RepositoryPath); try { Console.WriteLine("Cleaning up repository path at {0}", directoryPath); - DirectoryHelper.DeleteDirectory(RepositoryPath); + FileSystemHelper.Directory.DeleteDirectory(RepositoryPath); Console.WriteLine("Cleaned up repository path at {0}", directoryPath); } catch (Exception e) @@ -141,7 +141,7 @@ public void MergeTo(string branchName, bool removeBranchAfterMerging = false) /// public LocalRepositoryFixture CloneRepository() { - var localPath = PathHelper.GetRepositoryTempPath(); + var localPath = FileSystemHelper.Path.GetRepositoryTempPath(); Repository.Clone(RepositoryPath, localPath); Console.WriteLine($"Cloned repository to '{localPath}' from '{RepositoryPath}'"); return new LocalRepositoryFixture(new Repository(localPath)); diff --git a/src/GitVersion.Testing/GitTestExtensions.cs b/src/GitVersion.Testing/GitTestExtensions.cs index 1c5f1f3420..be1a0518cf 100644 --- a/src/GitVersion.Testing/GitTestExtensions.cs +++ b/src/GitVersion.Testing/GitTestExtensions.cs @@ -17,21 +17,20 @@ public static class GitTestExtensions FastForwardStrategy = FastForwardStrategy.NoFastForward }); - public static Commit[] MakeCommits(this IRepository repository, int numCommitsToMake) => Enumerable.Range(1, numCommitsToMake) - .Select(_ => repository.MakeACommit()) - .ToArray(); + public static Commit[] MakeCommits(this IRepository repository, int numCommitsToMake) + => [.. Enumerable.Range(1, numCommitsToMake).Select(_ => repository.MakeACommit())]; private static Commit CreateFileAndCommit(this IRepository repository, string relativeFileName, string? commitMessage = null) { - var randomFile = PathHelper.Combine(repository.Info.WorkingDirectory, relativeFileName); - if (File.Exists(randomFile)) + var randomFile = FileSystemHelper.Path.Combine(repository.Info.WorkingDirectory, relativeFileName); + if (FileSystemHelper.File.Exists(randomFile)) { - File.Delete(randomFile); + FileSystemHelper.File.Delete(randomFile); } var totalWidth = 36 + (_pad++ % 10); var contents = Guid.NewGuid().ToString().PadRight(totalWidth, '.'); - File.WriteAllText(randomFile, contents); + FileSystemHelper.File.WriteAllText(randomFile, contents); Commands.Stage(repository, randomFile); diff --git a/src/GitVersion.Testing/GitVersion.Testing.csproj b/src/GitVersion.Testing/GitVersion.Testing.csproj index f79daa6f8a..ebb1c208fc 100644 --- a/src/GitVersion.Testing/GitVersion.Testing.csproj +++ b/src/GitVersion.Testing/GitVersion.Testing.csproj @@ -4,11 +4,11 @@ + - - + From ad6f15246d82e6e393b97fb881869cd36ca7730f Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Wed, 16 Apr 2025 09:35:48 +0200 Subject: [PATCH 2/2] Refactor globbing resolution to support IFileSystem abstraction Reorganized globbing-related logic into the FileSystemGlobbing namespace. Introduced IFileSystem integration in GlobbingResolver and new wrapper classes for directory and file handling. Simplified service configuration using GitVersionAppModule. --- .../GitVersion.Common.csproj | 1 + .../ArgumentParserOnBuildServerTests.cs | 4 +- .../ArgumentParserTests.cs | 7 +- src/GitVersion.App/ArgumentParser.cs | 7 +- .../DirectoryInfoGlobbingWrapper.cs | 94 +++++++++++++++++++ .../FileInfoGlobbingWrapper.cs | 28 ++++++ .../FileSystemInfoGlobbingWrapper.cs | 20 ++++ .../FileSystemGlobbing/GlobbingResolver.cs | 17 ++++ .../IGlobbingResolver.cs | 2 +- .../FileSystemGlobbing/MatcherExtensions.cs | 76 +++++++++++++++ src/GitVersion.App/GitVersionAppModule.cs | 1 + src/GitVersion.App/GlobbingResolver.cs | 14 --- 12 files changed, 245 insertions(+), 26 deletions(-) create mode 100644 src/GitVersion.App/FileSystemGlobbing/DirectoryInfoGlobbingWrapper.cs create mode 100644 src/GitVersion.App/FileSystemGlobbing/FileInfoGlobbingWrapper.cs create mode 100644 src/GitVersion.App/FileSystemGlobbing/FileSystemInfoGlobbingWrapper.cs create mode 100644 src/GitVersion.App/FileSystemGlobbing/GlobbingResolver.cs rename src/GitVersion.App/{ => FileSystemGlobbing}/IGlobbingResolver.cs (73%) create mode 100644 src/GitVersion.App/FileSystemGlobbing/MatcherExtensions.cs delete mode 100644 src/GitVersion.App/GlobbingResolver.cs diff --git a/new-cli/GitVersion.Common/GitVersion.Common.csproj b/new-cli/GitVersion.Common/GitVersion.Common.csproj index 50d31943ff..91e48ec0d7 100644 --- a/new-cli/GitVersion.Common/GitVersion.Common.csproj +++ b/new-cli/GitVersion.Common/GitVersion.Common.csproj @@ -1,6 +1,7 @@ + diff --git a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs index 8be300083d..6d8537e276 100644 --- a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs @@ -1,5 +1,6 @@ using GitVersion.Agents; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using GitVersion.OutputVariables; using Microsoft.Extensions.DependencyInjection; @@ -15,8 +16,7 @@ public void SetUp() { var sp = ConfigureServices(services => { - services.AddSingleton(); - services.AddSingleton(); + services.AddModule(new GitVersionAppModule()); services.AddSingleton(); }); this.argumentParser = sp.GetRequiredService(); diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index ce806d2f12..82f7e5c8da 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -1,6 +1,7 @@ using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.VersionCalculation; @@ -18,11 +19,7 @@ public class ArgumentParserTests : TestBase [SetUp] public void SetUp() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule())); this.environment = sp.GetRequiredService(); this.argumentParser = sp.GetRequiredService(); this.fileSystem = sp.GetRequiredService(); diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index aae568d64b..5a62ad2c23 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -1,6 +1,7 @@ using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Extensions; +using GitVersion.FileSystemGlobbing; using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -152,11 +153,9 @@ private IEnumerable ResolveFiles(string workingDirectory, ISet? foreach (var file in assemblyInfoFiles) { - var paths = this.globbingResolver.Resolve(workingDirectory, file); - - foreach (var path in paths) + foreach (var path in this.globbingResolver.Resolve(workingDirectory, file)) { - yield return FileSystemHelper.Path.GetFullPath(FileSystemHelper.Path.Combine(workingDirectory, path)); + yield return path; } } } diff --git a/src/GitVersion.App/FileSystemGlobbing/DirectoryInfoGlobbingWrapper.cs b/src/GitVersion.App/FileSystemGlobbing/DirectoryInfoGlobbingWrapper.cs new file mode 100644 index 0000000000..bf6fbbb3dc --- /dev/null +++ b/src/GitVersion.App/FileSystemGlobbing/DirectoryInfoGlobbingWrapper.cs @@ -0,0 +1,94 @@ +using System.IO.Abstractions; + +namespace GitVersion.FileSystemGlobbing; + +internal sealed class DirectoryInfoGlobbingWrapper + : Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoBase +{ + private readonly IFileSystem fileSystem; + private readonly IDirectoryInfo directoryInfo; + private readonly bool isParentPath; + + public DirectoryInfoGlobbingWrapper(IFileSystem fileSystem, IDirectoryInfo directoryInfo) + : this(fileSystem, directoryInfo, isParentPath: false) + { + } + + private DirectoryInfoGlobbingWrapper( + IFileSystem fileSystem, + IDirectoryInfo directoryInfo, + bool isParentPath + ) + { + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.directoryInfo = directoryInfo ?? throw new ArgumentNullException(nameof(directoryInfo)); + this.isParentPath = isParentPath; + } + + public override string Name => this.isParentPath ? ".." : this.directoryInfo.Name; + + public override string FullName => this.directoryInfo.FullName; + + public override Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoBase? ParentDirectory => + this.directoryInfo.Parent is null + ? null + : new DirectoryInfoGlobbingWrapper(this.fileSystem, this.directoryInfo.Parent); + + public override IEnumerable EnumerateFileSystemInfos() + { + if (this.directoryInfo.Exists) + { + IEnumerable fileSystemInfos; + try + { + fileSystemInfos = this.directoryInfo.EnumerateFileSystemInfos( + "*", + SearchOption.TopDirectoryOnly + ); + } + catch (DirectoryNotFoundException) + { + yield break; + } + + foreach (var fileSystemInfo in fileSystemInfos) + { + yield return fileSystemInfo switch + { + IDirectoryInfo info => new DirectoryInfoGlobbingWrapper(this.fileSystem, info), + IFileInfo info => new FileInfoGlobbingWrapper(this.fileSystem, info), + _ => new FileSystemInfoGlobbingWrapper(this.fileSystem, fileSystemInfo), + }; + } + } + } + + public override Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoBase? GetDirectory(string path) + { + var parentPath = string.Equals(path, "..", StringComparison.Ordinal); + + if (parentPath) + { + return new DirectoryInfoGlobbingWrapper( + this.fileSystem, + this.fileSystem.DirectoryInfo.New(this.fileSystem.Path.Combine(this.directoryInfo.FullName, path)), + parentPath + ); + } + + var dirs = this.directoryInfo.GetDirectories(path); + + return dirs switch + { + { Length: 1 } => new DirectoryInfoGlobbingWrapper(this.fileSystem, dirs[0], parentPath), + { Length: 0 } => null, + _ => throw new InvalidOperationException($"More than one sub directories are found under {this.directoryInfo.FullName} with name {path}."), + }; + } + + public override Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileInfoBase GetFile(string path) + => new FileInfoGlobbingWrapper( + this.fileSystem, + this.fileSystem.FileInfo.New(this.fileSystem.Path.Combine(FullName, path)) + ); +} diff --git a/src/GitVersion.App/FileSystemGlobbing/FileInfoGlobbingWrapper.cs b/src/GitVersion.App/FileSystemGlobbing/FileInfoGlobbingWrapper.cs new file mode 100644 index 0000000000..cfd3e630da --- /dev/null +++ b/src/GitVersion.App/FileSystemGlobbing/FileInfoGlobbingWrapper.cs @@ -0,0 +1,28 @@ +using System.IO.Abstractions; +using GitVersion.Extensions; + +namespace GitVersion.FileSystemGlobbing; + +/// +/// Initialize a new instance +/// +/// The filesystem +/// The file +internal sealed class FileInfoGlobbingWrapper(IFileSystem fileSystem, IFileInfo fileInfo) + : Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileInfoBase +{ + private readonly IFileSystem fileSystem = fileSystem.NotNull(); + private readonly IFileInfo fileInfo = fileInfo.NotNull(); + + /// + public override string Name => this.fileInfo.Name; + + /// + public override string FullName => this.fileInfo.FullName; + + /// + public override Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoBase? ParentDirectory => + this.fileInfo.Directory is null + ? null + : new DirectoryInfoGlobbingWrapper(this.fileSystem, this.fileInfo.Directory); +} diff --git a/src/GitVersion.App/FileSystemGlobbing/FileSystemInfoGlobbingWrapper.cs b/src/GitVersion.App/FileSystemGlobbing/FileSystemInfoGlobbingWrapper.cs new file mode 100644 index 0000000000..3805e5726d --- /dev/null +++ b/src/GitVersion.App/FileSystemGlobbing/FileSystemInfoGlobbingWrapper.cs @@ -0,0 +1,20 @@ +using System.IO.Abstractions; +using GitVersion.Extensions; + +namespace GitVersion.FileSystemGlobbing; + +internal sealed class FileSystemInfoGlobbingWrapper(IFileSystem fileSystem, IFileSystemInfo fileSystemInfo) : Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileSystemInfoBase +{ + private readonly IFileSystem fileSystem = fileSystem.NotNull(); + private readonly IFileSystemInfo fileSystemInfo = fileSystemInfo.NotNull(); + + public override string Name => this.fileSystemInfo.Name; + + public override string FullName => this.fileSystemInfo.FullName; + + public override Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoBase ParentDirectory => + new DirectoryInfoGlobbingWrapper( + this.fileSystem, + this.fileSystem.DirectoryInfo.New(this.fileSystemInfo.FullName) + ); +} diff --git a/src/GitVersion.App/FileSystemGlobbing/GlobbingResolver.cs b/src/GitVersion.App/FileSystemGlobbing/GlobbingResolver.cs new file mode 100644 index 0000000000..fa4da4eb06 --- /dev/null +++ b/src/GitVersion.App/FileSystemGlobbing/GlobbingResolver.cs @@ -0,0 +1,17 @@ +using System.IO.Abstractions; +using GitVersion.Extensions; +using Microsoft.Extensions.FileSystemGlobbing; + +namespace GitVersion.FileSystemGlobbing; + +internal class GlobbingResolver(IFileSystem fileSystem) : IGlobbingResolver +{ + private readonly IFileSystem fileSystem = fileSystem.NotNull(); + + public IEnumerable Resolve(string workingDirectory, string pattern) + { + var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); + matcher.AddInclude(pattern); + return matcher.GetResultsInFullPath(this.fileSystem, workingDirectory); + } +} diff --git a/src/GitVersion.App/IGlobbingResolver.cs b/src/GitVersion.App/FileSystemGlobbing/IGlobbingResolver.cs similarity index 73% rename from src/GitVersion.App/IGlobbingResolver.cs rename to src/GitVersion.App/FileSystemGlobbing/IGlobbingResolver.cs index 6bfa777fb1..80da9c212c 100644 --- a/src/GitVersion.App/IGlobbingResolver.cs +++ b/src/GitVersion.App/FileSystemGlobbing/IGlobbingResolver.cs @@ -1,4 +1,4 @@ -namespace GitVersion; +namespace GitVersion.FileSystemGlobbing; internal interface IGlobbingResolver { diff --git a/src/GitVersion.App/FileSystemGlobbing/MatcherExtensions.cs b/src/GitVersion.App/FileSystemGlobbing/MatcherExtensions.cs new file mode 100644 index 0000000000..fa568b712b --- /dev/null +++ b/src/GitVersion.App/FileSystemGlobbing/MatcherExtensions.cs @@ -0,0 +1,76 @@ +using System.IO.Abstractions; +using Microsoft.Extensions.FileSystemGlobbing; + +namespace GitVersion.FileSystemGlobbing; + +internal static class MatcherExtensions +{ + public static PatternMatchingResult Execute( + this Matcher matcher, + IFileSystem fileSystem, + string directoryPath + ) + { + ArgumentNullException.ThrowIfNull(matcher); + ArgumentNullException.ThrowIfNull(fileSystem); + + return Execute(matcher, fileSystem, fileSystem.DirectoryInfo.New(directoryPath)); + } + + private static PatternMatchingResult Execute( + this Matcher matcher, + IFileSystem fileSystem, + IDirectoryInfo directoryInfo + ) + { + ArgumentNullException.ThrowIfNull(matcher); + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(directoryInfo); + + return matcher.Execute(new DirectoryInfoGlobbingWrapper(fileSystem, directoryInfo)); + } + + public static IEnumerable GetResultsInFullPath( + this Matcher matcher, + IFileSystem fileSystem, + string directoryPath + ) + { + ArgumentNullException.ThrowIfNull(matcher); + ArgumentNullException.ThrowIfNull(fileSystem); + + return GetResultsInFullPath( + matcher, + fileSystem, + fileSystem.DirectoryInfo.New(directoryPath) + ); + } + + private static IEnumerable GetResultsInFullPath( + this Matcher matcher, + IFileSystem fileSystem, + IDirectoryInfo directoryInfo + ) + { + ArgumentNullException.ThrowIfNull(matcher); + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(directoryInfo); + + var matches = Execute(matcher, fileSystem, directoryInfo); + + if (!matches.HasMatches) + { + return EmptyStringsEnumerable; + } + + var fsPath = fileSystem.Path; + var directoryFullName = directoryInfo.FullName; + + return matches.Files.Select(GetFullPath); + + string GetFullPath(FilePatternMatch match) => + fsPath.GetFullPath(fsPath.Combine(directoryFullName, match.Path)); + } + + private static readonly IEnumerable EmptyStringsEnumerable = []; +} diff --git a/src/GitVersion.App/GitVersionAppModule.cs b/src/GitVersion.App/GitVersionAppModule.cs index b635179377..c8cb45b42e 100644 --- a/src/GitVersion.App/GitVersionAppModule.cs +++ b/src/GitVersion.App/GitVersionAppModule.cs @@ -1,3 +1,4 @@ +using GitVersion.FileSystemGlobbing; using Microsoft.Extensions.DependencyInjection; namespace GitVersion; diff --git a/src/GitVersion.App/GlobbingResolver.cs b/src/GitVersion.App/GlobbingResolver.cs deleted file mode 100644 index f16423a78f..0000000000 --- a/src/GitVersion.App/GlobbingResolver.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Microsoft.Extensions.FileSystemGlobbing; - -namespace GitVersion; - -internal class GlobbingResolver : IGlobbingResolver -{ - private readonly Matcher matcher = new(StringComparison.OrdinalIgnoreCase); - - public IEnumerable Resolve(string workingDirectory, string pattern) - { - this.matcher.AddInclude(pattern); - return this.matcher.GetResultsInFullPath(workingDirectory); - } -}