diff --git a/.gitignore b/.gitignore index e5775f626a..6625c880d9 100644 --- a/.gitignore +++ b/.gitignore @@ -136,3 +136,5 @@ node_modules dogfood/ new-cli/log.txt + +new-cli/logs/ diff --git a/new-cli/.idea/.idea.GitVersion/.idea/icon.svg b/new-cli/.idea/.idea.GitVersion/.idea/icon.svg new file mode 100644 index 0000000000..f8bfb01f26 --- /dev/null +++ b/new-cli/.idea/.idea.GitVersion/.idea/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/new-cli/.idea/.idea.GitVersion/.idea/indexLayout.xml b/new-cli/.idea/.idea.GitVersion/.idea/indexLayout.xml new file mode 100644 index 0000000000..db942041e6 --- /dev/null +++ b/new-cli/.idea/.idea.GitVersion/.idea/indexLayout.xml @@ -0,0 +1,10 @@ + + + + + docs + + + + + \ No newline at end of file diff --git a/new-cli/Directory.Packages.props b/new-cli/Directory.Packages.props index eec8c27572..5a744aa636 100644 --- a/new-cli/Directory.Packages.props +++ b/new-cli/Directory.Packages.props @@ -21,6 +21,7 @@ + \ No newline at end of file diff --git a/new-cli/GitVersion.Common/GitVersion.Common.csproj b/new-cli/GitVersion.Common/GitVersion.Common.csproj index f224f9e121..50d31943ff 100644 --- a/new-cli/GitVersion.Common/GitVersion.Common.csproj +++ b/new-cli/GitVersion.Common/GitVersion.Common.csproj @@ -4,7 +4,6 @@ - diff --git a/new-cli/GitVersion.Core/CoreModule.cs b/new-cli/GitVersion.Core/CoreModule.cs index 4521f28dee..f3312b5dd2 100644 --- a/new-cli/GitVersion.Core/CoreModule.cs +++ b/new-cli/GitVersion.Core/CoreModule.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Infrastructure; namespace GitVersion; diff --git a/new-cli/GitVersion.Core/GitVersion.Core.csproj b/new-cli/GitVersion.Core/GitVersion.Core.csproj index b96d2f9f1a..47fe040631 100644 --- a/new-cli/GitVersion.Core/GitVersion.Core.csproj +++ b/new-cli/GitVersion.Core/GitVersion.Core.csproj @@ -8,13 +8,11 @@ + Infrastructure\Environment.cs - - Infrastructure\FileSystem.cs - diff --git a/new-cli/docs/calculate.rsp b/new-cli/docs/calculate.rsp index 7e0362931d..a8a006be0c 100644 --- a/new-cli/docs/calculate.rsp +++ b/new-cli/docs/calculate.rsp @@ -1 +1 @@ -calculate -l c:\logs\log.txt --work-dir C:\Projects\OSS\GitTools\GitVersion --verbosity verbose +calculate -l ./logs/log.txt --work-dir . --verbosity verbose diff --git a/new-cli/docs/output-project.rsp b/new-cli/docs/output-project.rsp index 8619d5df10..734d7e3736 100644 --- a/new-cli/docs/output-project.rsp +++ b/new-cli/docs/output-project.rsp @@ -1 +1 @@ -output --output-dir C:\Projects\OSS\GitTools\GitVersion --input-file version.json project --project-file project.csproj +output --output-dir ./output --input-file version.json project --project-file project.csproj diff --git a/new-cli/docs/output-wix.rsp b/new-cli/docs/output-wix.rsp index 25f543d648..91992af5b6 100644 --- a/new-cli/docs/output-wix.rsp +++ b/new-cli/docs/output-wix.rsp @@ -1 +1 @@ -output --output-dir C:\Projects\OSS\GitTools\GitVersion --input-file version.json wix --wix-file project.wix +output --output-dir ./output --input-file version.json wix --wix-file project.wix diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index 206e2aba10..eea058c3a0 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -36,7 +36,10 @@ + + + diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index c9d678043a..9120204927 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -283,12 +284,12 @@ public void UpdateAssemblyInfoWithFilename() using var repo = new EmptyRepositoryFixture(); var assemblyFile = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = File.Create(assemblyFile); + 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 => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] @@ -297,16 +298,16 @@ public void UpdateAssemblyInfoWithMultipleFilenames() using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = File.Create(assemblyFile1); + using var file = this.fileSystem.File.Create(assemblyFile1); var assemblyFile2 = PathHelper.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); - using var file2 = File.Create(assemblyFile2); + 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 => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("VersionAssemblyInfo.cs")); } [Test] @@ -315,16 +316,16 @@ public void UpdateProjectFilesWithMultipleFilenames() using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.csproj"); - using var file = File.Create(assemblyFile1); + using var file = this.fileSystem.File.Create(assemblyFile1); var assemblyFile2 = PathHelper.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); - using var file2 = File.Create(assemblyFile2); + 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 => Path.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); } [Test] @@ -333,23 +334,23 @@ public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = File.Create(assemblyFile1); + using var file = this.fileSystem.File.Create(assemblyFile1); var assemblyFile2 = PathHelper.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); - using var file2 = File.Create(assemblyFile2); + using var file2 = this.fileSystem.File.Create(assemblyFile2); var subdir = PathHelper.Combine(repo.RepositoryPath, "subdir"); - this.fileSystem.CreateDirectory(subdir); + this.fileSystem.Directory.CreateDirectory(subdir); var assemblyFile3 = PathHelper.Combine(subdir, "LocalAssemblyInfo.cs"); - using var file3 = File.Create(assemblyFile3); + 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 => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("LocalAssemblyInfo.cs")); + 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")); } [Test] @@ -358,15 +359,15 @@ public void UpdateAssemblyInfoWithRelativeFilename() using var repo = new EmptyRepositoryFixture(); var assemblyFile = PathHelper.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = File.Create(assemblyFile); + using var file = this.fileSystem.File.Create(assemblyFile); var targetPath = PathHelper.Combine(repo.RepositoryPath, "subdir1", "subdir2"); - this.fileSystem.CreateDirectory(targetPath); + 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 => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); + arguments.UpdateAssemblyInfoFileName.ShouldContain(x => PathHelper.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] @@ -765,9 +766,9 @@ public void ThrowIfConfigurationFileDoesNotExist(string configFile) => public void EnsureConfigurationFileIsSet() { var configFile = PathHelper.GetTempPath() + Guid.NewGuid() + ".yaml"; - File.WriteAllText(configFile, "next-version: 1.0.0"); + this.fileSystem.File.WriteAllText(configFile, "next-version: 1.0.0"); var arguments = this.argumentParser.ParseArguments($"-config {configFile}"); arguments.ConfigurationFile.ShouldBe(configFile); - File.Delete(configFile); + this.fileSystem.File.Delete(configFile); } } diff --git a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj index 111e288a9f..b5afc842c8 100644 --- a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj +++ b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj @@ -2,6 +2,7 @@ + @@ -15,7 +16,6 @@ - diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index 1fa2d6268c..cb663b43aa 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -49,7 +49,7 @@ public void WithEnv(params KeyValuePair[] envs) public Task Run(string arg) { - var args = arg.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); + var args = arg.Split([' '], StringSplitOptions.RemoveEmptyEntries).ToArray(); return Run(args); } diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index 7e273f99da..7686b77231 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Extensions; using GitVersion.Helpers; @@ -106,15 +107,15 @@ private void ValidateConfigurationFile(Arguments arguments) { if (arguments.ConfigurationFile.IsNullOrWhiteSpace()) return; - if (Path.IsPathRooted(arguments.ConfigurationFile)) + if (PathHelper.IsPathRooted(arguments.ConfigurationFile)) { - if (!this.fileSystem.Exists(arguments.ConfigurationFile)) throw new WarningException($"Could not find config file at '{arguments.ConfigurationFile}'"); - arguments.ConfigurationFile = Path.GetFullPath(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); } else { - var configFilePath = Path.GetFullPath(PathHelper.Combine(arguments.TargetPath, arguments.ConfigurationFile)); - if (!this.fileSystem.Exists(configFilePath)) throw new WarningException($"Could not find config file at '{configFilePath}'"); + var configFilePath = PathHelper.GetFullPath(PathHelper.Combine(arguments.TargetPath, arguments.ConfigurationFile)); + if (!this.fileSystem.File.Exists(configFilePath)) throw new WarningException($"Could not find config file at '{configFilePath}'"); arguments.ConfigurationFile = configFilePath; } } @@ -155,7 +156,7 @@ private IEnumerable ResolveFiles(string workingDirectory, ISet? foreach (var path in paths) { - yield return Path.GetFullPath(PathHelper.Combine(workingDirectory, path)); + yield return PathHelper.GetFullPath(PathHelper.Combine(workingDirectory, path)); } } } @@ -166,7 +167,7 @@ private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList this.log.Info(logMessage)); } - if (!this.fileSystem.DirectoryExists(workingDirectory)) + if (!this.fileSystem.Directory.Exists(workingDirectory)) { this.log.Warning($"The working directory '{workingDirectory}' does not exist."); } @@ -159,7 +160,7 @@ private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int e return false; } - private static void ConfigureLogging(GitVersionOptions gitVersionOptions, ILog log) + private static void ConfigureLogging(GitVersionOptions gitVersionOptions, ILog log, IFileSystem fileSystem) { if (gitVersionOptions.Output.Contains(OutputType.BuildServer) || gitVersionOptions.LogFilePath == "console") { @@ -168,7 +169,7 @@ private static void ConfigureLogging(GitVersionOptions gitVersionOptions, ILog l if (gitVersionOptions.LogFilePath != null && gitVersionOptions.LogFilePath != "console") { - log.AddLogAppender(new FileAppender(gitVersionOptions.LogFilePath)); + log.AddLogAppender(new FileAppender(fileSystem, gitVersionOptions.LogFilePath)); } } } diff --git a/src/GitVersion.App/GlobbingResolver.cs b/src/GitVersion.App/GlobbingResolver.cs index 43851b5435..d17606436a 100644 --- a/src/GitVersion.App/GlobbingResolver.cs +++ b/src/GitVersion.App/GlobbingResolver.cs @@ -13,5 +13,6 @@ public IEnumerable Resolve(string workingDirectory, string pattern) return this.matcher.Execute(GetDirectoryInfoWrapper(workingDirectory)).Files.Select(file => file.Path); } - protected virtual DirectoryInfoBase GetDirectoryInfoWrapper(string workingDirectory) => new DirectoryInfoWrapper(new DirectoryInfo(workingDirectory)); + private static DirectoryInfoWrapper GetDirectoryInfoWrapper(string workingDirectory) + => new(new DirectoryInfo(workingDirectory)); } diff --git a/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs index 3cae60d9ad..dbaef24ea1 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/BitBucketPipelinesTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -10,6 +11,7 @@ namespace GitVersion.Agents.Tests; public class BitBucketPipelinesTests : TestBase { private IEnvironment environment; + private IFileSystem fileSystem; private BitBucketPipelines buildServer; private IServiceProvider sp; @@ -18,6 +20,7 @@ public void SetEnvironmentVariableForTest() { this.sp = ConfigureServices(services => services.AddSingleton()); this.environment = this.sp.GetRequiredService(); + this.fileSystem = this.sp.GetRequiredService(); this.buildServer = this.sp.GetRequiredService(); this.environment.SetEnvironmentVariable(BitBucketPipelines.EnvironmentVariableName, "MyWorkspace"); @@ -117,7 +120,7 @@ public void GetCurrentBranchShouldHandlePullRequests() [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); var propertyFile = PathHelper.Combine(assemblyLocation, "gitversion.properties"); var ps1File = PathHelper.Combine(assemblyLocation, "gitversion.ps1"); @@ -128,8 +131,8 @@ public void WriteAllVariablesToTheTextWriter() } finally { - File.Delete(propertyFile); - File.Delete(ps1File); + this.fileSystem.File.Delete(propertyFile); + this.fileSystem.File.Delete(ps1File); } } @@ -156,18 +159,18 @@ private void AssertVariablesAreWrittenToFile(string propertyFile, string ps1File writes[1].ShouldBe("1.2.3-beta.1+5"); - File.Exists(propertyFile).ShouldBe(true); + this.fileSystem.File.Exists(propertyFile).ShouldBe(true); - var props = File.ReadAllText(propertyFile); + var props = this.fileSystem.File.ReadAllText(propertyFile); props.ShouldContain("export GITVERSION_MAJOR=1"); props.ShouldContain("export GITVERSION_MINOR=2"); props.ShouldContain("export GITVERSION_SHA=f28807e615e9f06aec8a33c87780374e0c1f6fb8"); props.ShouldContain("export GITVERSION_COMMITDATE=2022-04-06"); - File.Exists(ps1File).ShouldBe(true); + this.fileSystem.File.Exists(ps1File).ShouldBe(true); - var psProps = File.ReadAllText(ps1File); + var psProps = this.fileSystem.File.ReadAllText(ps1File); psProps.ShouldContain("$GITVERSION_MAJOR = \"1\""); psProps.ShouldContain("$GITVERSION_MINOR = \"2\""); diff --git a/src/GitVersion.BuildAgents.Tests/Agents/BuildServerBaseTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/BuildServerBaseTests.cs index 9666ef0e79..0042b69743 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/BuildServerBaseTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/BuildServerBaseTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Logging; @@ -48,7 +49,7 @@ public void BuildNumberIsFullSemVer() writes.ShouldNotContain(x => x != null && x.StartsWith("Executing GenerateSetVersionMessage for ")); } - private class BuildAgent(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) + private class BuildAgent(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { protected override string EnvironmentVariable => throw new NotImplementedException(); diff --git a/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs index cdc5de2b10..5b072bdf1e 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/CodeBuildTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -10,6 +11,7 @@ namespace GitVersion.Agents.Tests; public sealed class CodeBuildTests : TestBase { private IEnvironment environment; + private IFileSystem fileSystem; private IServiceProvider sp; private CodeBuild buildServer; @@ -18,6 +20,7 @@ public void SetUp() { this.sp = ConfigureServices(services => services.AddSingleton()); this.environment = this.sp.GetRequiredService(); + this.fileSystem = this.sp.GetRequiredService(); this.buildServer = this.sp.GetRequiredService(); } @@ -52,7 +55,7 @@ public void PicksUpBranchNameFromEnvironmentFromWebHook() [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); var f = PathHelper.Combine(assemblyLocation, "codebuild_this_file_should_be_deleted.properties"); @@ -62,7 +65,7 @@ public void WriteAllVariablesToTheTextWriter() } finally { - File.Delete(f); + this.fileSystem.File.Delete(f); } } @@ -92,9 +95,9 @@ private void AssertVariablesAreWrittenToFile(string file) writes[1].ShouldBe("1.2.3-beta.1+5"); - File.Exists(file).ShouldBe(true); + this.fileSystem.File.Exists(file).ShouldBe(true); - var props = File.ReadAllText(file); + var props = this.fileSystem.File.ReadAllText(file); props.ShouldContain("GitVersion_Major=1"); props.ShouldContain("GitVersion_Minor=2"); diff --git a/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs index 34aba8ec1b..f7df7ae10d 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/EnvRunTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using Microsoft.Extensions.DependencyInjection; @@ -10,6 +11,7 @@ public class EnvRunTests : TestBase private const string EnvVarName = "ENVRUN_DATABASE"; private string mFilePath; private IEnvironment environment; + private IFileSystem fileSystem; private EnvRun buildServer; [SetUp] @@ -17,19 +19,20 @@ public void SetEnvironmentVariableForTest() { var sp = ConfigureServices(services => services.AddSingleton()); this.environment = sp.GetRequiredService(); + this.fileSystem = sp.GetRequiredService(); 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.environment.SetEnvironmentVariable(EnvVarName, this.mFilePath); - File.OpenWrite(this.mFilePath).Dispose(); + this.fileSystem.File.OpenWrite(this.mFilePath).Dispose(); } [TearDown] public void ClearEnvironmentVariableForTest() { this.environment.SetEnvironmentVariable(EnvVarName, null); - File.Delete(this.mFilePath); + this.fileSystem.File.Delete(this.mFilePath); } [Test] diff --git a/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs index b5fd21fd0f..83c40c5d0f 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/GitHubActionsTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using Microsoft.Extensions.DependencyInjection; @@ -8,6 +9,7 @@ namespace GitVersion.Agents.Tests; public class GitHubActionsTests : TestBase { private IEnvironment environment; + private IFileSystem fileSystem; private GitHubActions buildServer; private string? githubSetEnvironmentTempFilePath; @@ -16,11 +18,12 @@ public void SetUp() { var sp = ConfigureServices(services => services.AddSingleton()); this.environment = sp.GetRequiredService(); + this.fileSystem = sp.GetRequiredService(); this.buildServer = sp.GetRequiredService(); this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true"); this.environment.SetEnvironmentVariable("GITHUB_REF_TYPE", "branch"); - this.githubSetEnvironmentTempFilePath = Path.GetTempFileName(); + this.githubSetEnvironmentTempFilePath = PathHelper.GetTempFileName(); this.environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, this.githubSetEnvironmentTempFilePath); } @@ -29,10 +32,10 @@ public void TearDown() { this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, null); this.environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, null); - if (this.githubSetEnvironmentTempFilePath == null || !File.Exists(this.githubSetEnvironmentTempFilePath)) + if (this.githubSetEnvironmentTempFilePath == null || !this.fileSystem.File.Exists(this.githubSetEnvironmentTempFilePath)) return; - File.Delete(this.githubSetEnvironmentTempFilePath); + this.fileSystem.File.Delete(this.githubSetEnvironmentTempFilePath); this.githubSetEnvironmentTempFilePath = null; } @@ -145,7 +148,7 @@ public void ShouldWriteIntegration() var expectedFileContents = new List { "GitVersion_Major=1.0.0" }; this.githubSetEnvironmentTempFilePath.ShouldNotBeNull(); - var actualFileContents = File.ReadAllLines(this.githubSetEnvironmentTempFilePath); + var actualFileContents = this.fileSystem.File.ReadAllLines(this.githubSetEnvironmentTempFilePath); actualFileContents.ShouldBe(expectedFileContents); } diff --git a/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs index 2e5eba6ea1..06f05ac711 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -9,16 +10,18 @@ namespace GitVersion.Agents.Tests; [TestFixture] public class GitLabCiTests : TestBase { + private IEnvironment environment; + private IFileSystem fileSystem; private IServiceProvider sp; private GitLabCi buildServer; - private IEnvironment environment; [SetUp] public void SetUp() { this.sp = ConfigureServices(services => services.AddSingleton()); - this.buildServer = this.sp.GetRequiredService(); this.environment = this.sp.GetRequiredService(); + this.fileSystem = this.sp.GetRequiredService(); + this.buildServer = this.sp.GetRequiredService(); this.environment.SetEnvironmentVariable(GitLabCi.EnvironmentVariableName, "true"); } @@ -92,7 +95,7 @@ public void GetCurrentBranchShouldHandlePullRequests(string branchName, string e [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); var f = PathHelper.Combine(assemblyLocation, "jenkins_this_file_should_be_deleted.properties"); @@ -102,7 +105,7 @@ public void WriteAllVariablesToTheTextWriter() } finally { - File.Delete(f); + this.fileSystem.File.Delete(f); } } @@ -132,9 +135,9 @@ private void AssertVariablesAreWrittenToFile(string file) writes[1].ShouldBe("1.2.3-beta.1+5"); - File.Exists(file).ShouldBe(true); + this.fileSystem.File.Exists(file).ShouldBe(true); - var props = File.ReadAllText(file); + var props = this.fileSystem.File.ReadAllText(file); props.ShouldContain("GitVersion_Major=1"); props.ShouldContain("GitVersion_Minor=2"); diff --git a/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs index 12ab86d632..451a1b4dd9 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/JenkinsTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -14,6 +15,7 @@ public class JenkinsTests : TestBase private const string localBranch = "GIT_LOCAL_BRANCH"; private const string pipelineBranch = "BRANCH_NAME"; private IEnvironment environment; + private IFileSystem fileSystem; private IServiceProvider sp; private Jenkins buildServer; @@ -22,6 +24,7 @@ public void SetUp() { this.sp = ConfigureServices(services => services.AddSingleton()); this.environment = this.sp.GetRequiredService(); + this.fileSystem = this.sp.GetRequiredService(); this.buildServer = this.sp.GetRequiredService(); } @@ -108,7 +111,7 @@ public void GenerateMessageTest() [Test] public void WriteAllVariablesToTheTextWriter() { - var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var assemblyLocation = PathHelper.GetDirectoryName(Assembly.GetExecutingAssembly().Location); assemblyLocation.ShouldNotBeNull(); var f = PathHelper.Combine(assemblyLocation, "gitlab_this_file_should_be_deleted.properties"); @@ -118,7 +121,7 @@ public void WriteAllVariablesToTheTextWriter() } finally { - File.Delete(f); + this.fileSystem.File.Delete(f); } } @@ -144,9 +147,9 @@ private void AssertVariablesAreWrittenToFile(string file) writes[1].ShouldBe("1.2.3-beta.1+5"); - File.Exists(file).ShouldBe(true); + this.fileSystem.File.Exists(file).ShouldBe(true); - var props = File.ReadAllText(file); + var props = this.fileSystem.File.ReadAllText(file); props.ShouldContain("GitVersion_Major=1"); props.ShouldContain("GitVersion_Minor=2"); diff --git a/src/GitVersion.BuildAgents/Agents/AppVeyor.cs b/src/GitVersion.BuildAgents/Agents/AppVeyor.cs index 580b9adc29..c3b73be7f9 100644 --- a/src/GitVersion.BuildAgents/Agents/AppVeyor.cs +++ b/src/GitVersion.BuildAgents/Agents/AppVeyor.cs @@ -1,10 +1,11 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class AppVeyor(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class AppVeyor(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "APPVEYOR"; diff --git a/src/GitVersion.BuildAgents/Agents/AzurePipelines.cs b/src/GitVersion.BuildAgents/Agents/AzurePipelines.cs index 31d44ea671..b6fca6b9ac 100644 --- a/src/GitVersion.BuildAgents/Agents/AzurePipelines.cs +++ b/src/GitVersion.BuildAgents/Agents/AzurePipelines.cs @@ -1,10 +1,11 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class AzurePipelines(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class AzurePipelines(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "TF_BUILD"; @@ -35,7 +36,7 @@ public override string GenerateSetVersionMessage(GitVersionVariables variables) if (buildNumberEnv == newBuildNumber) { var buildNumber = variables.FullSemVer.EndsWith("+0") - ? variables.FullSemVer.Substring(0, variables.FullSemVer.Length - 2) + ? variables.FullSemVer[..^2] : variables.FullSemVer; return $"##vso[build.updatebuildnumber]{buildNumber}"; diff --git a/src/GitVersion.BuildAgents/Agents/BitBucketPipelines.cs b/src/GitVersion.BuildAgents/Agents/BitBucketPipelines.cs index 61d62465f0..b2954465f5 100644 --- a/src/GitVersion.BuildAgents/Agents/BitBucketPipelines.cs +++ b/src/GitVersion.BuildAgents/Agents/BitBucketPipelines.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -12,7 +13,7 @@ internal class BitBucketPipelines : BuildAgentBase private string? propertyFile; private string? ps1File; - public BitBucketPipelines(IEnvironment environment, ILog log) : base(environment, log) + public BitBucketPipelines(IEnvironment environment, ILog log, IFileSystem fileSystem) : base(environment, log, fileSystem) { WithPropertyFile("gitversion.properties"); WithPowershellFile("gitversion.ps1"); @@ -54,13 +55,13 @@ public override void WriteIntegration(Action writer, GitVersionVariable .Select(variable => $"export GITVERSION_{variable.Key.ToUpperInvariant()}={variable.Value}") .ToList(); - File.WriteAllLines(this.propertyFile, exports); + this.FileSystem.File.WriteAllLines(this.propertyFile, exports); var psExports = variables .Select(variable => $"$GITVERSION_{variable.Key.ToUpperInvariant()} = \"{variable.Value}\"") .ToList(); - File.WriteAllLines(this.ps1File, psExports); + this.FileSystem.File.WriteAllLines(this.ps1File, psExports); } public override string? GetCurrentBranch(bool usingDynamicRepos) diff --git a/src/GitVersion.BuildAgents/Agents/BuildKite.cs b/src/GitVersion.BuildAgents/Agents/BuildKite.cs index 2b5a1bf12d..dbd0d58d2a 100644 --- a/src/GitVersion.BuildAgents/Agents/BuildKite.cs +++ b/src/GitVersion.BuildAgents/Agents/BuildKite.cs @@ -1,9 +1,10 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class BuildKite(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class BuildKite(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "BUILDKITE"; diff --git a/src/GitVersion.BuildAgents/Agents/CodeBuild.cs b/src/GitVersion.BuildAgents/Agents/CodeBuild.cs index 402c97f055..791ac37e85 100644 --- a/src/GitVersion.BuildAgents/Agents/CodeBuild.cs +++ b/src/GitVersion.BuildAgents/Agents/CodeBuild.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -10,7 +11,7 @@ internal sealed class CodeBuild : BuildAgentBase public const string WebHookEnvironmentVariableName = "CODEBUILD_WEBHOOK_HEAD_REF"; public const string SourceVersionEnvironmentVariableName = "CODEBUILD_SOURCE_VERSION"; - public CodeBuild(IEnvironment environment, ILog log) : base(environment, log) => WithPropertyFile("gitversion.properties"); + public CodeBuild(IEnvironment environment, ILog log, IFileSystem fileSystem) : base(environment, log, fileSystem) => WithPropertyFile("gitversion.properties"); public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; @@ -37,7 +38,7 @@ public override void WriteIntegration(Action writer, GitVersionVariable base.WriteIntegration(writer, variables, updateBuildNumber); writer($"Outputting variables to '{this.file}' ... "); - File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); + this.FileSystem.File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } public override bool PreventFetch() => true; diff --git a/src/GitVersion.BuildAgents/Agents/ContinuaCi.cs b/src/GitVersion.BuildAgents/Agents/ContinuaCi.cs index fa96cdc04b..08b90a6e5a 100644 --- a/src/GitVersion.BuildAgents/Agents/ContinuaCi.cs +++ b/src/GitVersion.BuildAgents/Agents/ContinuaCi.cs @@ -1,9 +1,10 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class ContinuaCi(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class ContinuaCi(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "ContinuaCI.Version"; diff --git a/src/GitVersion.BuildAgents/Agents/Drone.cs b/src/GitVersion.BuildAgents/Agents/Drone.cs index 2504ea927c..503815e33a 100644 --- a/src/GitVersion.BuildAgents/Agents/Drone.cs +++ b/src/GitVersion.BuildAgents/Agents/Drone.cs @@ -1,10 +1,11 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class Drone(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class Drone(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "DRONE"; protected override string EnvironmentVariable => EnvironmentVariableName; diff --git a/src/GitVersion.BuildAgents/Agents/EnvRun.cs b/src/GitVersion.BuildAgents/Agents/EnvRun.cs index 52092c8da1..171b945dfd 100644 --- a/src/GitVersion.BuildAgents/Agents/EnvRun.cs +++ b/src/GitVersion.BuildAgents/Agents/EnvRun.cs @@ -1,10 +1,11 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class EnvRun(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class EnvRun(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "ENVRUN_DATABASE"; protected override string EnvironmentVariable => EnvironmentVariableName; @@ -13,7 +14,7 @@ public override bool CanApplyToCurrentContext() var envRunDatabasePath = Environment.GetEnvironmentVariable(EnvironmentVariableName); if (!envRunDatabasePath.IsNullOrEmpty()) { - if (!File.Exists(envRunDatabasePath)) + if (!this.FileSystem.File.Exists(envRunDatabasePath)) { this.Log.Error($"The database file of EnvRun.exe was not found at {envRunDatabasePath}."); return false; diff --git a/src/GitVersion.BuildAgents/Agents/GitHubActions.cs b/src/GitVersion.BuildAgents/Agents/GitHubActions.cs index 7d5b8a9122..ff4a16d653 100644 --- a/src/GitVersion.BuildAgents/Agents/GitHubActions.cs +++ b/src/GitVersion.BuildAgents/Agents/GitHubActions.cs @@ -1,10 +1,11 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class GitHubActions(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class GitHubActions(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { // https://help.github.com/en/actions/automating-your-workflow-with-github-actions/using-environment-variables#default-environment-variables @@ -31,7 +32,7 @@ public override void WriteIntegration(Action writer, GitVersionVariable if (gitHubSetEnvFilePath != null) { writer($"Writing version variables to $GITHUB_ENV file for '{GetType().Name}'."); - using var streamWriter = File.AppendText(gitHubSetEnvFilePath); + using var streamWriter = this.FileSystem.File.AppendText(gitHubSetEnvFilePath); foreach (var (key, value) in variables) { if (!value.IsNullOrEmpty()) diff --git a/src/GitVersion.BuildAgents/Agents/GitLabCi.cs b/src/GitVersion.BuildAgents/Agents/GitLabCi.cs index 23c0e912a1..350b75d849 100644 --- a/src/GitVersion.BuildAgents/Agents/GitLabCi.cs +++ b/src/GitVersion.BuildAgents/Agents/GitLabCi.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -8,7 +9,7 @@ internal class GitLabCi : BuildAgentBase public const string EnvironmentVariableName = "GITLAB_CI"; private string? file; - public GitLabCi(IEnvironment environment, ILog log) : base(environment, log) => WithPropertyFile("gitversion.properties"); + public GitLabCi(IEnvironment environment, ILog log, IFileSystem fileSystem) : base(environment, log, fileSystem) => WithPropertyFile("gitversion.properties"); public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; @@ -44,6 +45,6 @@ public override void WriteIntegration(Action writer, GitVersionVariable base.WriteIntegration(writer, variables, updateBuildNumber); writer($"Outputting variables to '{this.file}' ... "); - File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); + this.FileSystem.File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } } diff --git a/src/GitVersion.BuildAgents/Agents/Jenkins.cs b/src/GitVersion.BuildAgents/Agents/Jenkins.cs index dfd45beb16..e23a8be632 100644 --- a/src/GitVersion.BuildAgents/Agents/Jenkins.cs +++ b/src/GitVersion.BuildAgents/Agents/Jenkins.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -10,7 +11,7 @@ internal class Jenkins : BuildAgentBase private string? file; protected override string EnvironmentVariable => EnvironmentVariableName; - public Jenkins(IEnvironment environment, ILog log) : base(environment, log) => WithPropertyFile("gitversion.properties"); + public Jenkins(IEnvironment environment, ILog log, IFileSystem fileSystem) : base(environment, log, fileSystem) => WithPropertyFile("gitversion.properties"); public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; @@ -43,6 +44,6 @@ public override void WriteIntegration(Action writer, GitVersionVariable base.WriteIntegration(writer, variables, updateBuildNumber); writer($"Outputting variables to '{this.file}' ... "); - File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); + this.FileSystem.File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } } diff --git a/src/GitVersion.BuildAgents/Agents/MyGet.cs b/src/GitVersion.BuildAgents/Agents/MyGet.cs index 42fc06de29..ea82a27056 100644 --- a/src/GitVersion.BuildAgents/Agents/MyGet.cs +++ b/src/GitVersion.BuildAgents/Agents/MyGet.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; @@ -5,7 +6,7 @@ namespace GitVersion.Agents; -internal class MyGet(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class MyGet(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "BuildRunner"; protected override string EnvironmentVariable => EnvironmentVariableName; diff --git a/src/GitVersion.BuildAgents/Agents/SpaceAutomation.cs b/src/GitVersion.BuildAgents/Agents/SpaceAutomation.cs index 10882a2fef..1518eea9a9 100644 --- a/src/GitVersion.BuildAgents/Agents/SpaceAutomation.cs +++ b/src/GitVersion.BuildAgents/Agents/SpaceAutomation.cs @@ -1,9 +1,10 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class SpaceAutomation(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class SpaceAutomation(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "JB_SPACE_PROJECT_KEY"; diff --git a/src/GitVersion.BuildAgents/Agents/TeamCity.cs b/src/GitVersion.BuildAgents/Agents/TeamCity.cs index 91d1915ba0..30bce327d3 100644 --- a/src/GitVersion.BuildAgents/Agents/TeamCity.cs +++ b/src/GitVersion.BuildAgents/Agents/TeamCity.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; @@ -5,7 +6,7 @@ namespace GitVersion.Agents; -internal class TeamCity(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class TeamCity(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "TEAMCITY_VERSION"; diff --git a/src/GitVersion.BuildAgents/Agents/TravisCI.cs b/src/GitVersion.BuildAgents/Agents/TravisCI.cs index 70bef8c2f6..ca4e0764a1 100644 --- a/src/GitVersion.BuildAgents/Agents/TravisCI.cs +++ b/src/GitVersion.BuildAgents/Agents/TravisCI.cs @@ -1,9 +1,10 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class TravisCi(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class TravisCi(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public const string EnvironmentVariableName = "TRAVIS"; protected override string EnvironmentVariable => EnvironmentVariableName; diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs index e89ac22636..3d83a38e23 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationFileLocatorTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Configuration.Tests.Configuration; using GitVersion.Core.Tests.Helpers; diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs index ca721c3a18..206b1573c6 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Runtime.CompilerServices; using GitVersion.Configuration; using GitVersion.Configuration.Tests.Configuration; diff --git a/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs b/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs index 6000db6c6c..e6f9932e03 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; @@ -14,13 +15,13 @@ public static IDisposable SetupConfigFile(this IFileSystem fileSystem, s var fullPath = PathHelper.Combine(path, fileName); var directory = PathHelper.GetDirectoryName(fullPath); - if (!fileSystem.DirectoryExists(directory)) + if (!fileSystem.Directory.Exists(directory)) { - fileSystem.CreateDirectory(directory); + fileSystem.Directory.CreateDirectory(directory); } - fileSystem.WriteAllText(fullPath, text); + fileSystem.File.WriteAllText(fullPath, text); - return Disposable.Create(fullPath, () => fileSystem.Delete(fullPath)); + return Disposable.Create(fullPath, () => fileSystem.File.Delete(fullPath)); } } diff --git a/src/GitVersion.Configuration/ConfigurationFileLocator.cs b/src/GitVersion.Configuration/ConfigurationFileLocator.cs index 0354d9a0c9..752a7b6af7 100644 --- a/src/GitVersion.Configuration/ConfigurationFileLocator.cs +++ b/src/GitVersion.Configuration/ConfigurationFileLocator.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; @@ -25,7 +26,7 @@ internal class ConfigurationFileLocator( public void Verify(string? workingDirectory, string? projectRootDirectory) { - if (Path.IsPathRooted(this.ConfigurationFile)) return; + if (PathHelper.IsPathRooted(this.ConfigurationFile)) return; if (PathHelper.Equal(workingDirectory, projectRootDirectory)) return; WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory); } @@ -43,7 +44,7 @@ from candidate in candidates foreach (var candidatePath in candidatePaths) { this.log.Debug($"Trying to find configuration file at '{candidatePath}'"); - if (fileSystem.Exists(candidatePath)) + if (fileSystem.File.Exists(candidatePath)) { this.log.Info($"Found configuration file at '{candidatePath}'"); return candidatePath; diff --git a/src/GitVersion.Configuration/ConfigurationProvider.cs b/src/GitVersion.Configuration/ConfigurationProvider.cs index cf1a89a74f..1a506c080a 100644 --- a/src/GitVersion.Configuration/ConfigurationProvider.cs +++ b/src/GitVersion.Configuration/ConfigurationProvider.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration.Workflows; using GitVersion.Extensions; using Microsoft.Extensions.Options; @@ -71,8 +72,8 @@ private IGitVersionConfiguration ProvideConfiguration(string? configFile, private IReadOnlyDictionary? ReadOverrideConfiguration(string? configFilePath) { - if (configFilePath == null || !fileSystem.Exists(configFilePath)) return null; - var content = fileSystem.ReadAllText(configFilePath); + if (configFilePath == null || !fileSystem.File.Exists(configFilePath)) return null; + var content = fileSystem.File.ReadAllText(configFilePath); return configurationSerializer.Deserialize>(content); } diff --git a/src/GitVersion.Configuration/VersionStrategiesConverter.cs b/src/GitVersion.Configuration/VersionStrategiesConverter.cs index 7d790154cf..b4144464d4 100644 --- a/src/GitVersion.Configuration/VersionStrategiesConverter.cs +++ b/src/GitVersion.Configuration/VersionStrategiesConverter.cs @@ -12,9 +12,9 @@ internal class VersionStrategiesConverter : IYamlTypeConverter public bool Accepts(Type type) => type == typeof(VersionStrategies[]); - public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) + public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { - List strategies = new(); + List strategies = []; if (parser.TryConsume(out var _)) { diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index 9fe51feda9..a8b0ca9985 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using Microsoft.Extensions.DependencyInjection; @@ -49,8 +50,8 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran gitPreparer.Prepare(); var fileSystem = sp.GetRequiredService(); - fileSystem.CreateDirectory(dynamicDirectory); - fileSystem.CreateDirectory(workingDirectory); + fileSystem.Directory.CreateDirectory(dynamicDirectory); + fileSystem.Directory.CreateDirectory(workingDirectory); var gitVersionCalculator = sp.GetRequiredService(); diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index f2dac1d3f8..6bb47da39c 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -1,6 +1,8 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using GitVersion.Git; using GitVersion.Helpers; using GitVersion.Logging; @@ -147,7 +149,7 @@ public void CacheFileExistsOnDisk() var cacheKey = cacheKeyFactory.Create(null); var cacheFileName = this.gitVersionCacheProvider.GetCacheFileName(cacheKey); - this.fileSystem.WriteAllText(cacheFileName, versionCacheFileContent); + this.fileSystem.File.WriteAllText(cacheFileName, versionCacheFileContent); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); @@ -199,7 +201,7 @@ public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDyn var cacheKeyFactory = this.sp.GetRequiredService(); var cacheKey = cacheKeyFactory.Create(null); var cacheFileName = this.gitVersionCacheProvider.GetCacheFileName(cacheKey); - this.fileSystem.WriteAllText(cacheFileName, versionCacheFileContent); + this.fileSystem.File.WriteAllText(cacheFileName, versionCacheFileContent); var cacheDirectory = this.gitVersionCacheProvider.GetCacheDirectory(); @@ -292,13 +294,13 @@ public void ConfigChangeInvalidatesCache(string configFileName) var cacheKey = cacheKeyFactory.Create(null); var cacheFileName = this.gitVersionCacheProvider.GetCacheFileName(cacheKey); - this.fileSystem.WriteAllText(cacheFileName, versionCacheFileContent); + this.fileSystem.File.WriteAllText(cacheFileName, versionCacheFileContent); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); var configPath = PathHelper.Combine(fixture.RepositoryPath, configFileName); - this.fileSystem.WriteAllText(configPath, "next-version: 5.0.0"); + this.fileSystem.File.WriteAllText(configPath, "next-version: 5.0.0"); gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: this.fileSystem); @@ -354,7 +356,7 @@ public void NoCacheBypassesCache() var cacheKey = cacheKeyFactory.Create(null); var cacheFileName = this.gitVersionCacheProvider.GetCacheFileName(cacheKey); - this.fileSystem.WriteAllText(cacheFileName, versionCacheFileContent); + this.fileSystem.File.WriteAllText(cacheFileName, versionCacheFileContent); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); @@ -478,8 +480,9 @@ public void GetDotGitDirectoryWorktree() public void CalculateVersionFromWorktreeHead() { // Setup + this.fileSystem = new FileSystem(); using var fixture = new EmptyRepositoryFixture(); - var repoDir = new DirectoryInfo(fixture.RepositoryPath); + var repoDir = fileSystem.DirectoryInfo.New(fixture.RepositoryPath); var worktreePath = PathHelper.Combine(repoDir.Parent?.FullName, $"{repoDir.Name}-v1"); fixture.Repository.MakeATaggedCommit("v1.0.0"); @@ -492,7 +495,7 @@ public void CalculateVersionFromWorktreeHead() var gitVersionOptions = new GitVersionOptions { WorkingDirectory = worktreeFixture.RepositoryPath }; - var sut = GetGitVersionCalculator(gitVersionOptions); + var sut = GetGitVersionCalculator(gitVersionOptions, fs: this.fileSystem); // Execute var version = sut.CalculateVersionVariables(); @@ -590,9 +593,9 @@ public void CalculateVersionVariables_ShallowFetch_ThrowException() exception?.Message.ShouldBe("Repository is a shallow clone. Git repositories must contain the full history. See https://gitversion.net/docs/reference/requirements#unshallow for more info."); } - private static string GetWorktreePath(EmptyRepositoryFixture fixture) + private string GetWorktreePath(EmptyRepositoryFixture fixture) { - var worktreePath = PathHelper.Combine(Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); + var worktreePath = PathHelper.Combine(this.fileSystem.Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); return worktreePath; } @@ -625,6 +628,10 @@ private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionO if (environment != null) services.AddSingleton(environment); var options = Options.Create(gitVersionOptions); services.AddSingleton(options); - services.AddSingleton(new GitRepositoryInfo(options)); + services.AddSingleton(sp => + { + var fs = sp.GetRequiredService(); + return new GitRepositoryInfo(fs, options); + }); }); } diff --git a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs index 35e976bcb6..c4c9e1140d 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using LibGit2Sharp; @@ -11,17 +12,20 @@ public class GitVersionTaskDirectoryTests : TestBase { private string gitDirectory; private string workDirectory; + private IFileSystem fileSystem; [SetUp] 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(Path.DirectorySeparatorChar); + this.gitDirectory = Repository.Init(this.workDirectory).TrimEnd(PathHelper.DirectorySeparatorChar); Assert.That(this.gitDirectory, Is.Not.Null); } [TearDown] - public void Cleanup() => Directory.Delete(this.workDirectory, true); + public void Cleanup() => this.fileSystem.Directory.Delete(this.workDirectory, true); [Test] public void FindsGitDirectory() @@ -43,7 +47,7 @@ public void FindsGitDirectory() public void FindsGitDirectoryInParent() { var childDir = PathHelper.Combine(this.workDirectory, "child"); - Directory.CreateDirectory(childDir); + 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 8ac444b4fd..fe753448a5 100644 --- a/src/GitVersion.Core.Tests/DocumentationTests.cs +++ b/src/GitVersion.Core.Tests/DocumentationTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -8,10 +9,15 @@ namespace GitVersion.Core.Tests; [TestFixture] public class DocumentationTests : TestBase { - private DirectoryInfo docsDirectory; + private IFileSystem fileSystem; + private IDirectoryInfo docsDirectory; [OneTimeSetUp] - public void OneTimeSetUp() => this.docsDirectory = GetDocsDirectory(); + public void OneTimeSetUp() + { + this.fileSystem = new FileSystem(); + this.docsDirectory = GetDocsDirectory(); + } [Test] public void ConfigurationDocumentationIsUpToDate() @@ -56,28 +62,28 @@ private string ReadDocumentationFile(string relativeDocumentationFilePath) { var documentationFilePath = PathHelper.Combine(this.docsDirectory.FullName, relativeDocumentationFilePath); // Normalize path separators and such. - documentationFilePath = new FileInfo(documentationFilePath).FullName; + documentationFilePath = fileSystem.FileInfo.New(documentationFilePath).FullName; - if (!File.Exists(documentationFilePath)) + if (!this.fileSystem.File.Exists(documentationFilePath)) { throw new FileNotFoundException($"The documentation file '{documentationFilePath}' couldn't be found.", documentationFilePath); } - return File.ReadAllText(documentationFilePath); + return this.fileSystem.File.ReadAllText(documentationFilePath); } - private static DirectoryInfo GetDocsDirectory() + private IDirectoryInfo GetDocsDirectory() { - var currentDirectory = new FileInfo(typeof(DocumentationTests).Assembly.Location).Directory; + var currentDirectory = this.fileSystem.FileInfo.New(typeof(DocumentationTests).Assembly.Location).Directory; while (currentDirectory != null) { - var docsDirectory = currentDirectory + var searchedDirectory = currentDirectory .EnumerateDirectories("docs", SearchOption.TopDirectoryOnly) .FirstOrDefault(); - if (docsDirectory != null) + if (searchedDirectory != null) { - currentDirectory = docsDirectory; + currentDirectory = searchedDirectory; break; } diff --git a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs b/src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs similarity index 99% rename from src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs rename to src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs index 7e20ec2aaf..97fdf611d9 100644 --- a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/GitRepositoryTestingExtensions.cs @@ -12,7 +12,7 @@ namespace GitVersion.Core.Tests; -public static class GitToolsTestingExtensions +public static class GitRepositoryTestingExtensions { private static int commitCount = 1; private static readonly DateTimeOffset when = DateTimeOffset.Now; diff --git a/src/GitVersion.Core.Tests/Extensions/GitVersionVariablesExtensions.cs b/src/GitVersion.Core.Tests/Extensions/GitVersionVariablesExtensions.cs index 063470e5a3..6d0ae5575e 100644 --- a/src/GitVersion.Core.Tests/Extensions/GitVersionVariablesExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/GitVersionVariablesExtensions.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.OutputVariables; namespace GitVersion.Core.Tests; diff --git a/src/GitVersion.Core.Tests/Extensions/MockCollectionExtensions.cs b/src/GitVersion.Core.Tests/Extensions/MockCollectionExtensions.cs index 7feb8ed156..81c3191326 100644 --- a/src/GitVersion.Core.Tests/Extensions/MockCollectionExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/MockCollectionExtensions.cs @@ -11,5 +11,9 @@ private static IEnumerator GetEnumerator(params T[] itemsToReturn) } public static void MockCollectionReturn(this IEnumerable items, params T[] itemsToReturn) - => items.GetEnumerator().Returns(_ => GetEnumerator(itemsToReturn)); + { + var enumerator = items.GetEnumerator(); + enumerator.Returns(_ => GetEnumerator(itemsToReturn)); + enumerator.Dispose(); + } } diff --git a/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs b/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs index eb76416658..045c930d87 100644 --- a/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs +++ b/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs @@ -42,8 +42,8 @@ private GitVersionContextBuilder WithBranch(string branchName) private GitVersionContextBuilder AddBranch(string branchName) { - var mockCommit = GitToolsTestingExtensions.CreateMockCommit(); - var mockBranch = GitToolsTestingExtensions.CreateMockBranch(branchName, mockCommit); + var mockCommit = GitRepositoryTestingExtensions.CreateMockCommit(); + var mockBranch = GitRepositoryTestingExtensions.CreateMockBranch(branchName, mockCommit); this.repository ??= CreateRepository(); @@ -71,8 +71,8 @@ public void Build() private static IGitRepository CreateRepository() { - var mockCommit = GitToolsTestingExtensions.CreateMockCommit(); - var mockBranch = GitToolsTestingExtensions.CreateMockBranch(TestBase.MainBranch, mockCommit); + var mockCommit = GitRepositoryTestingExtensions.CreateMockCommit(); + var mockBranch = GitRepositoryTestingExtensions.CreateMockBranch(TestBase.MainBranch, mockCommit); var branches = Substitute.For(); branches.MockCollectionReturn(mockBranch); diff --git a/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs b/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs index 755287a94d..e46989145f 100644 --- a/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs +++ b/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Configuration; using GitVersion.Extensions; diff --git a/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs b/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs deleted file mode 100644 index 5c81294ff3..0000000000 --- a/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using GitVersion.Core.Tests.Helpers; - -namespace GitVersion.Core.Tests.IntegrationTests; - -[TestFixture] -public class FileSystemTests : TestBase -{ - public string TempFilePath { get; set; } - - [SetUp] - public void CreateTempFile() => TempFilePath = Path.GetTempFileName(); - - [TearDown] - public void Cleanup() => File.Delete(TempFilePath); - - [TestCase("utf-32")] - [TestCase("utf-32BE")] - [TestCase("utf-16")] - [TestCase("utf-16BE")] - [TestCase("utf-8")] - public void WhenFileExistsWithEncodingPreambleEncodingIsPreservedAfterWriteAll(string encodingName) - { - var encoding = Encoding.GetEncoding(encodingName); - - File.WriteAllText(TempFilePath, "(-‸ლ)", encoding); - - var fileSystem = new FileSystem(); - fileSystem.WriteAllText(TempFilePath, @"¯\(◉◡◔)/¯"); - - using var stream = File.OpenRead(TempFilePath); - var preamble = encoding.GetPreamble(); - var bytes = new byte[preamble.Length]; - _ = stream.Read(bytes, 0, preamble.Length); - - bytes.ShouldBe(preamble); - } - - [Test] - public void WhenFileDoesNotExistCreateWithUtf8WithPreamble() - { - var encoding = Encoding.UTF8; - - var fileSystem = new FileSystem(); - fileSystem.WriteAllText(TempFilePath, "╚(ಠ_ಠ)=┐"); - - using var stream = File.OpenRead(TempFilePath); - var preamble = encoding.GetPreamble(); - var bytes = new byte[preamble.Length]; - _ = stream.Read(bytes, 0, preamble.Length); - - bytes.ShouldBe(preamble); - } -} diff --git a/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs index de62c1008f..17d9946478 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs @@ -1,10 +1,12 @@ using System.Globalization; +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.VersionCalculation; using LibGit2Sharp; +using Microsoft.Extensions.DependencyInjection; namespace GitVersion.Core.Tests.IntegrationTests; @@ -102,15 +104,17 @@ public void DoNotBlowUpWhenDevelopAndFeatureBranchPointAtSameCommit() [TestCase(false, 5)] public void HasDirtyFlagWhenUncommittedChangesAreInRepository(bool stageFile, int numberOfFiles) { + var sp = ConfigureServices(); + var fileSystem = sp.GetRequiredService(); using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); for (int i = 0; i < numberOfFiles; i++) { - var tempFile = Path.GetTempFileName(); - var repoFile = PathHelper.Combine(fixture.RepositoryPath, Path.GetFileNameWithoutExtension(tempFile) + ".txt"); - File.Move(tempFile, repoFile); - File.WriteAllText(repoFile, $"Hello world / testfile {i}"); + var tempFile = PathHelper.GetTempFileName(); + var repoFile = PathHelper.Combine(fixture.RepositoryPath, PathHelper.GetFileNameWithoutExtension(tempFile) + ".txt"); + fileSystem.File.Move(tempFile, repoFile); + fileSystem.File.WriteAllText(repoFile, $"Hello world / testfile {i}"); if (stageFile) Commands.Stage(fixture.Repository, repoFile); diff --git a/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs index 32a1c2b4f3..8d31541820 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/WorktreeScenarios.cs @@ -1,6 +1,8 @@ +using System.IO.Abstractions; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using LibGit2Sharp; +using Microsoft.Extensions.DependencyInjection; namespace GitVersion.Core.Tests.IntegrationTests; @@ -10,8 +12,10 @@ public class WorktreeScenarios : TestBase [Test] public void UseWorktreeRepositoryForVersion() { + var sp = ConfigureServices(); + var fileSystem = sp.GetRequiredService(); using var fixture = new EmptyRepositoryFixture(); - var repoDir = new DirectoryInfo(fixture.RepositoryPath); + var repoDir = fileSystem.DirectoryInfo.New(fixture.RepositoryPath); repoDir.Parent.ShouldNotBeNull(); var worktreePath = PathHelper.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1"); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/EffectiveBranchConfigurationFinderTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/EffectiveBranchConfigurationFinderTests.cs index 4a4b295da0..ba682c3543 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/EffectiveBranchConfigurationFinderTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/EffectiveBranchConfigurationFinderTests.cs @@ -14,7 +14,7 @@ public void When_getting_configurations_of_a_branch_without_versioning_mode_Give DeploymentMode versioningMode) { // Arrange - var branchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit()); + var branchMock = GitRepositoryTestingExtensions.CreateMockBranch("main", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithDeploymentMode(versioningMode) .WithBranch("main", builder => builder.WithDeploymentMode(null)) @@ -38,15 +38,15 @@ public void When_getting_configurations_of_a_branch_with_versioning_mode_Given_f DeploymentMode versioningMode) { // Arrange - var mainBranchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit()); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); + var mainBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("main", GitRepositoryTestingExtensions.CreateMockCommit()); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithDeploymentMode(null) .WithBranch("main", builder => builder.WithDeploymentMode(versioningMode)) .WithBranch("develop", builder => builder.WithDeploymentMode(null).WithIncrement(IncrementStrategy.Inherit)) .Build(); var repositoryStoreMock = Substitute.For(); - repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns(new[] { mainBranchMock }); + repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns([mainBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); @@ -64,8 +64,8 @@ public void When_getting_configurations_of_a_branch_with_versioning_mode_Given_p DeploymentMode versioningMode) { // Arrange - var mainBranchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit()); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); + var mainBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("main", GitRepositoryTestingExtensions.CreateMockCommit()); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithDeploymentMode(null) .WithBranch("main", builder => builder.WithDeploymentMode(versioningMode)) @@ -75,7 +75,7 @@ public void When_getting_configurations_of_a_branch_with_versioning_mode_Given_p .Build(); var repositoryStoreMock = Substitute.For(); - repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns(new[] { mainBranchMock }); + repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns([mainBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); @@ -99,8 +99,8 @@ public void When_getting_configurations_of_a_branch_with_versioning_mode_Given_p public void When_getting_configurations_of_a_branch_with_tag_alpha_Given_branch_which_inherits_from_parent_branch_Then_result_should_have_tag_alpha() { // Arrange - var mainBranchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit()); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); + var mainBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("main", GitRepositoryTestingExtensions.CreateMockCommit()); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithBranch("main", builder => builder.WithLabel(string.Empty)) .WithBranch("develop", builder => builder @@ -109,7 +109,7 @@ public void When_getting_configurations_of_a_branch_with_tag_alpha_Given_branch_ .Build(); var repositoryStoreMock = Substitute.For(); - repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns(new[] { mainBranchMock }); + repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns([mainBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); @@ -126,8 +126,8 @@ public void When_getting_configurations_of_a_branch_with_tag_alpha_Given_branch_ public void When_getting_configurations_of_a_branch_without_tag_Given_branch_which_inherits_from_parent_branch_Then_result_should_have_tag_from_parent() { // Arrange - var mainBranchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit()); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); + var mainBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("main", GitRepositoryTestingExtensions.CreateMockCommit()); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithBranch("main", builder => builder.WithLabel(string.Empty)) .WithBranch("develop", builder => builder @@ -136,7 +136,7 @@ public void When_getting_configurations_of_a_branch_without_tag_Given_branch_whi .Build(); var repositoryStoreMock = Substitute.For(); - repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns(new[] { mainBranchMock }); + repositoryStoreMock.GetSourceBranches(developBranchMock, configuration, Arg.Any>()).Returns([mainBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); @@ -154,7 +154,7 @@ public void When_getting_configurations_of_a_branch_without_tag_Given_branch_whi public void UsesFirstBranchConfigWhenMultipleMatch(string branchName, IncrementStrategy incrementStrategy, string label) { // Arrange - var releaseBranchMock = GitToolsTestingExtensions.CreateMockBranch(branchName, GitToolsTestingExtensions.CreateMockCommit()); + var releaseBranchMock = GitRepositoryTestingExtensions.CreateMockBranch(branchName, GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithoutBranches() .WithBranch("release/latest", builder => builder @@ -188,7 +188,7 @@ public void UsesFirstBranchConfigWhenMultipleMatch(string branchName, IncrementS public void When_getting_configurations_of_an_orphaned_branch_Given_fallback_configuration_with_increment_inherit_Then_result_should_be_empty() { // Arrange - var branchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); + var branchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(IncrementStrategy.Inherit) .WithBranch("develop", builder => builder.WithIncrement(IncrementStrategy.Inherit)) @@ -213,7 +213,7 @@ public void When_getting_configurations_of_an_orphaned_branch_Given_fallback_con IncrementStrategy fallbackIncrement) { // Arrange - var branchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); + var branchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(fallbackIncrement) .WithBranch("develop", builder => builder.WithIncrement(IncrementStrategy.Inherit)) @@ -236,7 +236,7 @@ public void When_getting_configurations_of_an_orphaned_branch_Given_fallback_con public void When_getting_configurations_of_an_unknown_branch_Given_fallback_and_unknown_configuration_with_increment_inherit_Then_result_should_be_empty() { // Arrange - var branchMock = GitToolsTestingExtensions.CreateMockBranch("unknown", GitToolsTestingExtensions.CreateMockCommit()); + var branchMock = GitRepositoryTestingExtensions.CreateMockBranch("unknown", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(IncrementStrategy.Inherit) .WithBranch("unknown", builder => builder.WithIncrement(IncrementStrategy.Inherit)) @@ -261,7 +261,7 @@ public void When_getting_configurations_of_an_unknown_branch_Given_fallback_conf IncrementStrategy fallbackIncrement) { // Arrange - var branchMock = GitToolsTestingExtensions.CreateMockBranch("unknown", GitToolsTestingExtensions.CreateMockCommit()); + var branchMock = GitRepositoryTestingExtensions.CreateMockBranch("unknown", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(fallbackIncrement) .WithBranch("unknown", builder => builder.WithIncrement(IncrementStrategy.Inherit)) @@ -285,14 +285,14 @@ public void When_getting_configurations_of_an_unknown_branch_Given_fallback_conf IncrementStrategy fallbackIncrement, IncrementStrategy developIncrement) { // Arrange - var unknownBranchMock = GitToolsTestingExtensions.CreateMockBranch("unknown", GitToolsTestingExtensions.CreateMockCommit()); + var unknownBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("unknown", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(fallbackIncrement) .WithBranch("develop", builder => builder.WithIncrement(developIncrement)) .Build(); var repositoryStoreMock = Substitute.For(); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); - repositoryStoreMock.GetSourceBranches(unknownBranchMock, configuration, Arg.Any>()).Returns(new[] { developBranchMock }); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); + repositoryStoreMock.GetSourceBranches(unknownBranchMock, configuration, Arg.Any>()).Returns([developBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); @@ -318,14 +318,14 @@ public void When_getting_configurations_of_an_unknown_branch_Given_fallback_conf IncrementStrategy fallbackIncrement) { // Arrange - var unknownBranchMock = GitToolsTestingExtensions.CreateMockBranch("unknown", GitToolsTestingExtensions.CreateMockCommit()); + var unknownBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("unknown", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(fallbackIncrement) .WithBranch("develop", builder => builder.WithIncrement(IncrementStrategy.Inherit)) .Build(); var repositoryStoreMock = Substitute.For(); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); - repositoryStoreMock.GetSourceBranches(unknownBranchMock, configuration, Arg.Any>()).Returns(new[] { developBranchMock }); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); + repositoryStoreMock.GetSourceBranches(unknownBranchMock, configuration, Arg.Any>()).Returns([developBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); @@ -353,14 +353,14 @@ public void When_getting_configurations_of_an_unknown_branch_Given_fallback_and_ IncrementStrategy developBranchIncrement) { // Arrange - var unknownBranchMock = GitToolsTestingExtensions.CreateMockBranch("unknown", GitToolsTestingExtensions.CreateMockCommit()); + var unknownBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("unknown", GitRepositoryTestingExtensions.CreateMockCommit()); var configuration = GitFlowConfigurationBuilder.New .WithIncrement(IncrementStrategy.Inherit) .WithBranch("develop", builder => builder.WithIncrement(developBranchIncrement)) .Build(); var repositoryStoreMock = Substitute.For(); - var developBranchMock = GitToolsTestingExtensions.CreateMockBranch("develop", GitToolsTestingExtensions.CreateMockCommit()); - repositoryStoreMock.GetSourceBranches(Arg.Any(), Arg.Any(), Arg.Any>()).Returns(new[] { developBranchMock }); + var developBranchMock = GitRepositoryTestingExtensions.CreateMockBranch("develop", GitRepositoryTestingExtensions.CreateMockCommit()); + repositoryStoreMock.GetSourceBranches(Arg.Any(), Arg.Any(), Arg.Any>()).Returns([developBranchMock]); var unitUnderTest = new EffectiveBranchConfigurationFinder(Substitute.For(), repositoryStoreMock); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/MinDateVersionFilterTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/MinDateVersionFilterTests.cs index bd5438ecc7..86f41c787c 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/MinDateVersionFilterTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/MinDateVersionFilterTests.cs @@ -18,7 +18,7 @@ public void VerifyNullGuard() [Test] public void WhenCommitShouldExcludeWithReason() { - var commit = GitToolsTestingExtensions.CreateMockCommit(); + var commit = GitRepositoryTestingExtensions.CreateMockCommit(); BaseVersion version = new("dummy", new SemanticVersion(1), commit); var futureDate = DateTimeOffset.UtcNow.AddYears(1); var sut = new MinDateVersionFilter(futureDate); @@ -30,7 +30,7 @@ public void WhenCommitShouldExcludeWithReason() [Test] public void WhenShaMismatchShouldNotExclude() { - var commit = GitToolsTestingExtensions.CreateMockCommit(); + var commit = GitRepositoryTestingExtensions.CreateMockCommit(); BaseVersion version = new("dummy", new SemanticVersion(1), commit); var pastDate = DateTimeOffset.UtcNow.AddYears(-1); var sut = new MinDateVersionFilter(pastDate); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs index 86be277b52..69b95b9f20 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs @@ -9,8 +9,8 @@ public class ShaVersionFilterTests : TestBase [Test] public void VerifyNullGuard() { - var commit = GitToolsTestingExtensions.CreateMockCommit(); - var sut = new ShaVersionFilter(new[] { commit.Sha }); + var commit = GitRepositoryTestingExtensions.CreateMockCommit(); + var sut = new ShaVersionFilter([commit.Sha]); Should.Throw(() => sut.Exclude(null!, out _)); } @@ -18,9 +18,9 @@ public void VerifyNullGuard() [Test] public void WhenShaMatchShouldExcludeWithReason() { - var commit = GitToolsTestingExtensions.CreateMockCommit(); + var commit = GitRepositoryTestingExtensions.CreateMockCommit(); BaseVersion version = new("dummy", new SemanticVersion(1), commit); - var sut = new ShaVersionFilter(new[] { commit.Sha }); + var sut = new ShaVersionFilter([commit.Sha]); sut.Exclude(version, out var reason).ShouldBeTrue(); reason.ShouldNotBeNullOrWhiteSpace(); @@ -29,7 +29,7 @@ public void WhenShaMatchShouldExcludeWithReason() [Test] public void WhenShaMismatchShouldNotExclude() { - var commit = GitToolsTestingExtensions.CreateMockCommit(); + var commit = GitRepositoryTestingExtensions.CreateMockCommit(); BaseVersion version = new("dummy", new SemanticVersion(1), commit); var sut = new ShaVersionFilter(["mismatched"]); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/Strategies/ConfiguredNextVersionVersionStrategyTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/Strategies/ConfiguredNextVersionVersionStrategyTests.cs index 369124aae4..bd06aceb05 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/Strategies/ConfiguredNextVersionVersionStrategyTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/Strategies/ConfiguredNextVersionVersionStrategyTests.cs @@ -81,7 +81,7 @@ public void ConfiguredNextVersionTestShouldFail(string nextVersion, SemanticVers contextBuilder.ServicesProvider.ShouldNotBeNull(); var strategy = contextBuilder.ServicesProvider.GetServiceForType(); var context = contextBuilder.ServicesProvider.GetRequiredService>().Value; - var branchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit()); + var branchMock = GitRepositoryTestingExtensions.CreateMockBranch("main", GitRepositoryTestingExtensions.CreateMockCommit()); strategy.ShouldNotBeNull(); return strategy.GetBaseVersions(context.Configuration.GetEffectiveBranchConfiguration(branchMock)).SingleOrDefault(); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs index 0f34c39434..fccd3fcd36 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs @@ -15,11 +15,11 @@ public void ShouldNotAllowIncrementOfVersion() { // When a branch is merged in you want to start building stable packages of that version // So we shouldn't bump the version - var mockCommit = GitToolsTestingExtensions.CreateMockCommit(); + var mockCommit = GitRepositoryTestingExtensions.CreateMockCommit(); mockCommit.Message.Returns("Merge branch 'release-0.1.5'"); mockCommit.Parents.Returns(GetParents(true)); - var mockBranch = GitToolsTestingExtensions.CreateMockBranch(MainBranch, mockCommit); + var mockBranch = GitRepositoryTestingExtensions.CreateMockBranch(MainBranch, mockCommit); var branches = Substitute.For(); branches.MockCollectionReturn(mockBranch); @@ -154,11 +154,11 @@ public void TakesVersionFromMergeOfConfiguredReleaseBranch(string message, strin private static void AssertMergeMessage(string message, string? expectedVersion, IEnumerable parents, IReadOnlyDictionary? configuration = null) { - var commit = GitToolsTestingExtensions.CreateMockCommit(); + var commit = GitRepositoryTestingExtensions.CreateMockCommit(); commit.Message.Returns(message); commit.Parents.Returns(parents); - var mockBranch = GitToolsTestingExtensions.CreateMockBranch(MainBranch, commit, GitToolsTestingExtensions.CreateMockCommit()); + var mockBranch = GitRepositoryTestingExtensions.CreateMockBranch(MainBranch, commit, GitRepositoryTestingExtensions.CreateMockCommit()); var mockRepository = Substitute.For(); mockRepository.Head.Returns(mockBranch); diff --git a/src/GitVersion.Core/Agents/BuildAgentBase.cs b/src/GitVersion.Core/Agents/BuildAgentBase.cs index 29840605bb..c30dd82949 100644 --- a/src/GitVersion.Core/Agents/BuildAgentBase.cs +++ b/src/GitVersion.Core/Agents/BuildAgentBase.cs @@ -1,13 +1,15 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal abstract class BuildAgentBase(IEnvironment environment, ILog log) : ICurrentBuildAgent +internal abstract class BuildAgentBase(IEnvironment environment, ILog log, IFileSystem fileSystem) : ICurrentBuildAgent { protected readonly ILog Log = log.NotNull(); - protected IEnvironment Environment { get; } = environment.NotNull(); + protected readonly IEnvironment Environment = environment.NotNull(); + protected readonly IFileSystem FileSystem = fileSystem.NotNull(); protected abstract string EnvironmentVariable { get; } public virtual bool IsDefault => false; diff --git a/src/GitVersion.Core/Agents/LocalBuild.cs b/src/GitVersion.Core/Agents/LocalBuild.cs index 11a636b352..bb14a6d815 100644 --- a/src/GitVersion.Core/Agents/LocalBuild.cs +++ b/src/GitVersion.Core/Agents/LocalBuild.cs @@ -1,9 +1,10 @@ +using System.IO.Abstractions; using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersion.Agents; -internal class LocalBuild(IEnvironment environment, ILog log) : BuildAgentBase(environment, log) +internal class LocalBuild(IEnvironment environment, ILog log, IFileSystem fileSystem) : BuildAgentBase(environment, log, fileSystem) { public override bool IsDefault => true; diff --git a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs deleted file mode 100644 index 7678d8c373..0000000000 --- a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace GitVersion; - -public interface IFileSystem -{ - void Copy(string from, string to, bool overwrite); - void Move(string from, string to); - bool Exists(string file); - void Delete(string path); - string ReadAllText(string path); - void WriteAllText(string? file, string fileContents); - void WriteAllText(string? file, string fileContents, Encoding encoding); - Stream OpenWrite(string path); - Stream OpenRead(string path); - void CreateDirectory(string path); - bool DirectoryExists(string path); - string[] GetFiles(string path); - string[] GetDirectories(string path); - IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption); - long GetLastDirectoryWrite(string path); - long GetLastWriteTime(string path); -} diff --git a/src/GitVersion.Core/Core/FileSystem.cs b/src/GitVersion.Core/Core/FileSystem.cs deleted file mode 100644 index 1187b06528..0000000000 --- a/src/GitVersion.Core/Core/FileSystem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using GitVersion.Helpers; - -namespace GitVersion; - -internal class FileSystem : IFileSystem -{ - public void Copy(string from, string to, bool overwrite) => File.Copy(from, to, overwrite); - - public void Move(string from, string to) => File.Move(from, to); - - public bool Exists(string file) => File.Exists(file); - - public void Delete(string path) => File.Delete(path); - - public string ReadAllText(string path) => File.ReadAllText(path); - - public void WriteAllText(string? file, string fileContents) - { - // Opinionated decision to use UTF8 with BOM when creating new files or when the existing - // encoding was not easily detected due to the file not having an encoding preamble. - var encoding = EncodingHelper.DetectEncoding(file) ?? Encoding.UTF8; - WriteAllText(file, fileContents, encoding); - } - - public void WriteAllText(string? file, string fileContents, Encoding encoding) - { - ArgumentException.ThrowIfNullOrWhiteSpace(file); - - File.WriteAllText(file, fileContents, encoding); - } - - public Stream OpenWrite(string path) => File.OpenWrite(path); - - public Stream OpenRead(string path) => File.OpenRead(path); - - public void CreateDirectory(string path) => Directory.CreateDirectory(path); - - public bool DirectoryExists(string path) => Directory.Exists(path); - - public string[] GetFiles(string path) => Directory.GetFiles(path); - - public string[] GetDirectories(string path) => Directory.GetDirectories(path); - - public IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption) - { - ArgumentException.ThrowIfNullOrWhiteSpace(directory); - - return Directory.EnumerateFiles(directory, searchPattern, searchOption); - } - - public long GetLastWriteTime(string path) => File.GetLastWriteTime(path).Ticks; - - public long GetLastDirectoryWrite(string path) => new DirectoryInfo(path) - .GetDirectories("*.*", SearchOption.AllDirectories) - .Select(d => d.LastWriteTimeUtc) - .DefaultIfEmpty() - .Max() - .Ticks; -} diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index f159e05a0d..a1fffa9746 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Configuration; using GitVersion.Extensions; @@ -118,7 +119,7 @@ private void CreateDynamicRepository(string? targetBranch) { throw new("Dynamic Git repositories should have a path specified"); } - if (!this.fileSystem.DirectoryExists(gitDirectory)) + if (!this.fileSystem.Directory.Exists(gitDirectory)) { CloneRepository(gitVersionOptions.RepositoryInfo.TargetUrl, gitDirectory, authentication); } diff --git a/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs b/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs index a1e0b4bf7a..65b6d0cb67 100644 --- a/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs +++ b/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Core; using GitVersion.Extensions; using GitVersion.Git; @@ -99,7 +100,7 @@ public static bool IsReleaseBranch(this IGitVersionConfiguration configuration, foreach (var groupName in regex.GetGroupNames()) { var groupValue = match.Groups[groupName].Value; - Lazy escapedGroupValueLazy = new(() => EscapeInvalidCharaters(groupValue)); + Lazy escapedGroupValueLazy = new(() => EscapeInvalidCharacters(groupValue)); var placeholder = $"{{{groupName}}}"; int index, startIndex = 0; while ((index = label.IndexOf(placeholder, startIndex, StringComparison.InvariantCulture)) >= 0) @@ -114,33 +115,33 @@ public static bool IsReleaseBranch(this IGitVersionConfiguration configuration, return label; } - private static string EscapeInvalidCharaters(string groupValue) => groupValue.RegexReplace(@"[^a-zA-Z0-9-]", "-"); + private static string EscapeInvalidCharacters(string groupValue) => groupValue.RegexReplace("[^a-zA-Z0-9-]", "-"); - public static (string GitDirectory, string WorkingTreeDirectory)? FindGitDir(this IFileSystem fileSystem, string path) + public static (string GitDirectory, string WorkingTreeDirectory)? FindGitDir(this IFileSystem fileSystem, string? path) { string? startingDir = path; while (startingDir is not null) { var dirOrFilePath = PathHelper.Combine(startingDir, ".git"); - if (fileSystem.DirectoryExists(dirOrFilePath)) + if (fileSystem.Directory.Exists(dirOrFilePath)) { - return (dirOrFilePath, Path.GetDirectoryName(dirOrFilePath)!); + return (dirOrFilePath, PathHelper.GetDirectoryName(dirOrFilePath)); } - if (fileSystem.Exists(dirOrFilePath)) + if (fileSystem.File.Exists(dirOrFilePath)) { string? relativeGitDirPath = ReadGitDirFromFile(dirOrFilePath); if (!string.IsNullOrWhiteSpace(relativeGitDirPath)) { - var fullGitDirPath = Path.GetFullPath(PathHelper.Combine(startingDir, relativeGitDirPath)); - if (fileSystem.DirectoryExists(fullGitDirPath)) + var fullGitDirPath = PathHelper.GetFullPath(PathHelper.Combine(startingDir, relativeGitDirPath)); + if (fileSystem.Directory.Exists(fullGitDirPath)) { - return (fullGitDirPath, Path.GetDirectoryName(dirOrFilePath)!); + return (fullGitDirPath, PathHelper.GetDirectoryName(dirOrFilePath)); } } } - startingDir = Path.GetDirectoryName(startingDir); + startingDir = PathHelper.GetDirectoryName(startingDir); } return null; diff --git a/src/GitVersion.Core/Extensions/FileSystemExtensions.cs b/src/GitVersion.Core/Extensions/FileSystemExtensions.cs new file mode 100644 index 0000000000..213eea6a76 --- /dev/null +++ b/src/GitVersion.Core/Extensions/FileSystemExtensions.cs @@ -0,0 +1,13 @@ +using System.IO.Abstractions; + +namespace GitVersion.Extensions; + +public static class FileSystemExtensions +{ + public static long GetLastDirectoryWrite(this IFileSystem fileSystem, string path) => fileSystem.DirectoryInfo.New(path) + .GetDirectories("*.*", SearchOption.AllDirectories) + .Select(d => d.LastWriteTimeUtc) + .DefaultIfEmpty() + .Max() + .Ticks; +} diff --git a/src/GitVersion.Core/GitVersion.Core.csproj b/src/GitVersion.Core/GitVersion.Core.csproj index a11a076110..bc311c70f1 100644 --- a/src/GitVersion.Core/GitVersion.Core.csproj +++ b/src/GitVersion.Core/GitVersion.Core.csproj @@ -15,6 +15,7 @@ + diff --git a/src/GitVersion.Core/GitVersionCommonModule.cs b/src/GitVersion.Core/GitVersionCommonModule.cs index a4e0b53642..767b780e52 100644 --- a/src/GitVersion.Core/GitVersionCommonModule.cs +++ b/src/GitVersion.Core/GitVersionCommonModule.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Logging; using Microsoft.Extensions.DependencyInjection; diff --git a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs b/src/GitVersion.Core/Helpers/DirectoryHelper.cs similarity index 59% rename from src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs rename to src/GitVersion.Core/Helpers/DirectoryHelper.cs index d7c6f74f02..357815c5e1 100644 --- a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersion.Core/Helpers/DirectoryHelper.cs @@ -1,40 +1,7 @@ -using GitVersion.Helpers; +namespace GitVersion.Helpers; -namespace GitVersion.Core.Tests.Helpers; - -public static class DirectoryHelper +internal static class DirectoryHelper { - private static readonly Dictionary ToRename = new() - { - { "gitted", ".git" }, - { "gitmodules", ".gitmodules" } - }; - - public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) - { - // From http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c/58779#58779 - - foreach (var dir in source.GetDirectories()) - { - CopyFilesRecursively(dir, target.CreateSubdirectory(Rename(dir.Name))); - } - foreach (var file in source.GetFiles()) - { - file.CopyTo(PathHelper.Combine(target.FullName, Rename(file.Name))); - } - } - - private static string Rename(string name) => ToRename.GetValueOrDefault(name, name); - - public static void DeleteSubDirectories(string parentPath) - { - var dirs = Directory.GetDirectories(parentPath); - foreach (var dir in dirs) - { - DeleteDirectory(dir); - } - } - public static void DeleteDirectory(string directoryPath) { // From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502 @@ -73,7 +40,7 @@ public static void DeleteDirectory(string directoryPath) "{0}Known and common causes include:" + "{0}- Windows Search Indexer (go to the Indexing Options, in the Windows Control Panel, and exclude the bin folder of LibGit2Sharp.Tests)" + "{0}- Antivirus (exclude the bin folder of LibGit2Sharp.Tests from the paths scanned by your real-time antivirus){0}", - PathHelper.NewLine, Path.GetFullPath(directoryPath))); + PathHelper.NewLine, PathHelper.GetFullPath(directoryPath))); } } } diff --git a/src/GitVersion.Core/Helpers/EncodingHelper.cs b/src/GitVersion.Core/Helpers/EncodingHelper.cs deleted file mode 100644 index 8f0e3af85f..0000000000 --- a/src/GitVersion.Core/Helpers/EncodingHelper.cs +++ /dev/null @@ -1,95 +0,0 @@ -namespace GitVersion.Helpers; - -public static class EncodingHelper -{ - private static IList? encodingsWithPreambles; - - private static int maxPreambleLength; - - /// - /// Detects the encoding of a file if and only if it includes a preamble . - /// - /// The file name to check the encoding of. - /// The encoding of the file if it has a preamble otherwise null. - public static Encoding? DetectEncoding(string? filename) - { - if (string.IsNullOrEmpty(filename) || !File.Exists(filename)) - { - return null; - } - - if (encodingsWithPreambles == null) - { - ScanEncodings(); - } - - using var stream = File.OpenRead(filename); - // No bytes? No encoding! - if (stream.Length == 0) - { - return null; - } - - // Read the minimum amount necessary. - var length = stream.Length > maxPreambleLength ? maxPreambleLength : stream.Length; - - var bytes = new byte[length]; - _ = stream.Read(bytes, 0, (int)length); - return DetectEncoding(bytes); - } - - /// - /// Returns the first encoding where all the preamble bytes match exactly. - /// - /// The bytes to check for a matching preamble. - /// The encoding that has a matching preamble or null if one was not found. - public static Encoding? DetectEncoding(IList bytes) - { - if (bytes.Count == 0) - { - return null; - } - - if (encodingsWithPreambles == null) - { - ScanEncodings(); - } - - return encodingsWithPreambles?.FirstOrDefault(encoding => PreambleMatches(encoding, bytes)); - } - - /// - /// Returns an ordered list of encodings that have preambles ordered by the length of the - /// preamble longest to shortest. This prevents a short preamble masking a longer one - /// later in the list. - /// - /// An ordered list of encodings and corresponding preambles. - private static void ScanEncodings() - { - var encodings = (Encoding.GetEncodings()); - encodingsWithPreambles = (from info in encodings - let encoding = info.GetEncoding() - let preamble = encoding.GetPreamble() - where preamble.Length > 0 - orderby preamble.Length descending - select encoding).ToList(); - - var encodingWithLongestPreamble = encodingsWithPreambles.FirstOrDefault(); - maxPreambleLength = encodingWithLongestPreamble?.GetPreamble().Length ?? 0; - } - - /// - /// Verifies that all bytes of an encoding's preamble are present at the beginning of some sample data. - /// - /// The encoding to check against. - /// The data to test. - /// A boolean indicating if a preamble match was found. - private static bool PreambleMatches(Encoding encoding, IList data) - { - var preamble = encoding.GetPreamble(); - if (preamble.Length > data.Count) - return false; - - return !preamble.Where((preambleByte, index) => data[index] != preambleByte).Any(); - } -} diff --git a/src/GitVersion.Core/Helpers/PathHelper.cs b/src/GitVersion.Core/Helpers/PathHelper.cs index 3c9d853a1d..42c69c0f41 100644 --- a/src/GitVersion.Core/Helpers/PathHelper.cs +++ b/src/GitVersion.Core/Helpers/PathHelper.cs @@ -5,6 +5,7 @@ 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) @@ -33,13 +34,19 @@ public static string GetDirectoryName(string? path) return Path.GetDirectoryName(path)!; } - public static string GetFullPath(string? path) + public static string GetFileName(string? path) { ArgumentNullException.ThrowIfNull(path, nameof(path)); - return Path.GetFullPath(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); @@ -79,4 +86,10 @@ public static bool Equal(string? path, string? otherPath) => 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/PublicAPI.Shipped.txt b/src/GitVersion.Core/PublicAPI.Shipped.txt index e8e7ed46a5..646e2c5952 100644 --- a/src/GitVersion.Core/PublicAPI.Shipped.txt +++ b/src/GitVersion.Core/PublicAPI.Shipped.txt @@ -331,7 +331,6 @@ GitVersion.GitVersionOptions.WixInfo.get -> GitVersion.WixInfo! GitVersion.GitVersionOptions.WorkingDirectory.get -> string! GitVersion.GitVersionOptions.WorkingDirectory.set -> void GitVersion.Helpers.Disposable -GitVersion.Helpers.EncodingHelper GitVersion.Helpers.IDisposable GitVersion.Helpers.IDisposable.Value.get -> T GitVersion.Helpers.LambdaEqualityHelper @@ -352,23 +351,6 @@ GitVersion.IConverterContext.WorkingDirectory.get -> string! GitVersion.IEnvironment GitVersion.IEnvironment.GetEnvironmentVariable(string! variableName) -> string? GitVersion.IEnvironment.SetEnvironmentVariable(string! variableName, string? value) -> void -GitVersion.IFileSystem -GitVersion.IFileSystem.Copy(string! from, string! to, bool overwrite) -> void -GitVersion.IFileSystem.CreateDirectory(string! path) -> void -GitVersion.IFileSystem.Delete(string! path) -> void -GitVersion.IFileSystem.DirectoryEnumerateFiles(string? directory, string! searchPattern, System.IO.SearchOption searchOption) -> System.Collections.Generic.IEnumerable! -GitVersion.IFileSystem.DirectoryExists(string! path) -> bool -GitVersion.IFileSystem.Exists(string! file) -> bool -GitVersion.IFileSystem.GetDirectories(string! path) -> string![]! -GitVersion.IFileSystem.GetFiles(string! path) -> string![]! -GitVersion.IFileSystem.GetLastDirectoryWrite(string! path) -> long -GitVersion.IFileSystem.GetLastWriteTime(string! path) -> long -GitVersion.IFileSystem.Move(string! from, string! to) -> void -GitVersion.IFileSystem.OpenRead(string! path) -> System.IO.Stream! -GitVersion.IFileSystem.OpenWrite(string! path) -> System.IO.Stream! -GitVersion.IFileSystem.ReadAllText(string! path) -> string! -GitVersion.IFileSystem.WriteAllText(string? file, string! fileContents, System.Text.Encoding! encoding) -> void -GitVersion.IFileSystem.WriteAllText(string? file, string! fileContents) -> void GitVersion.IGitPreparer GitVersion.IGitPreparer.EnsureLocalBranchExistsForCurrentBranch(GitVersion.Git.IRemote! remote, string! currentBranch) -> void GitVersion.IGitPreparer.Prepare() -> void @@ -778,8 +760,6 @@ static GitVersion.Git.ReferenceName.operator ==(GitVersion.Git.ReferenceName? le static GitVersion.Git.ReferenceName.Parse(string! canonicalName) -> GitVersion.Git.ReferenceName! static GitVersion.Helpers.Disposable.Create(System.Action! disposer) -> System.IDisposable! static GitVersion.Helpers.Disposable.Create(T value, System.Action! disposer) -> GitVersion.Helpers.IDisposable! -static GitVersion.Helpers.EncodingHelper.DetectEncoding(string? filename) -> System.Text.Encoding? -static GitVersion.Helpers.EncodingHelper.DetectEncoding(System.Collections.Generic.IList! bytes) -> System.Text.Encoding? static GitVersion.Helpers.ServiceMessageEscapeHelper.EscapeValue(string? value) -> string? static GitVersion.Logging.LogExtensions.Debug(this GitVersion.Logging.ILog! log, GitVersion.Logging.LogAction! logAction) -> void static GitVersion.Logging.LogExtensions.Debug(this GitVersion.Logging.ILog! log, GitVersion.Logging.Verbosity verbosity, GitVersion.Logging.LogAction! logAction) -> void diff --git a/src/GitVersion.Core/PublicAPI.Unshipped.txt b/src/GitVersion.Core/PublicAPI.Unshipped.txt index 7dc5c58110..57bf801923 100644 --- a/src/GitVersion.Core/PublicAPI.Unshipped.txt +++ b/src/GitVersion.Core/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +GitVersion.Extensions.FileSystemExtensions +static GitVersion.Extensions.FileSystemExtensions.GetLastDirectoryWrite(this System.IO.Abstractions.IFileSystem! fileSystem, string! path) -> long diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs index c91350e733..b024a27a22 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Security.Cryptography; using GitVersion.Common; using GitVersion.Configuration; @@ -57,7 +58,7 @@ private List CalculateDirectoryContents(string root) // examined for files. var dirs = new Stack(); - if (!this.fileSystem.DirectoryExists(root)) + if (!this.fileSystem.Directory.Exists(root)) { throw new DirectoryNotFoundException($"Root directory does not exist: {root}"); } @@ -68,13 +69,13 @@ private List CalculateDirectoryContents(string root) { var currentDir = dirs.Pop(); - var di = new DirectoryInfo(currentDir); + var di = this.fileSystem.DirectoryInfo.New(currentDir); result.Add(di.Name); string[] subDirs; try { - subDirs = this.fileSystem.GetDirectories(currentDir); + subDirs = this.fileSystem.Directory.GetDirectories(currentDir); } // An UnauthorizedAccessException exception will be thrown if we do not have // discovery permission on a folder or file. It may or may not be acceptable @@ -99,7 +100,7 @@ private List CalculateDirectoryContents(string root) string[] files; try { - files = this.fileSystem.GetFiles(currentDir); + files = this.fileSystem.Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { @@ -116,9 +117,9 @@ private List CalculateDirectoryContents(string root) { try { - if (!this.fileSystem.Exists(file)) continue; - result.Add(Path.GetFileName(file)); - result.Add(this.fileSystem.ReadAllText(file)); + if (!this.fileSystem.File.Exists(file)) continue; + result.Add(PathHelper.GetFileName(file)); + result.Add(this.fileSystem.File.ReadAllText(file)); } catch (IOException e) { @@ -174,9 +175,9 @@ private string GetConfigFileHash() var configFilePath = this.configFileLocator.GetConfigurationFile(workingDirectory) ?? this.configFileLocator.GetConfigurationFile(projectRootDirectory); if (configFilePath == null) return string.Empty; - if (!this.fileSystem.Exists(configFilePath)) return string.Empty; + if (!this.fileSystem.File.Exists(configFilePath)) return string.Empty; - var configFileContent = this.fileSystem.ReadAllText(configFilePath); + var configFileContent = this.fileSystem.File.ReadAllText(configFilePath); return GetHash(configFileContent); } diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs index 63a67e6afb..59363dc86f 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheProvider.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Git; using GitVersion.Helpers; @@ -46,7 +47,7 @@ public void WriteVariablesToDiskCache(GitVersionVariables versionVariables) var cacheFileName = GetCacheFileName(cacheKey); using (this.log.IndentLog($"Loading version variables from disk cache file {cacheFileName}")) { - if (!this.fileSystem.Exists(cacheFileName)) + if (!this.fileSystem.File.Exists(cacheFileName)) { this.log.Info($"Cache file {cacheFileName} not found."); return null; @@ -63,7 +64,7 @@ public void WriteVariablesToDiskCache(GitVersionVariables versionVariables) this.log.Info(ex.ToString()); try { - this.fileSystem.Delete(cacheFileName); + this.fileSystem.File.Delete(cacheFileName); } catch (Exception deleteEx) { @@ -92,7 +93,7 @@ private string PrepareCacheDirectory() var cacheDir = GetCacheDirectory(); // If the cacheDir already exists, CreateDirectory just won't do anything (it won't fail). @asbjornu - this.fileSystem.CreateDirectory(cacheDir); + this.fileSystem.Directory.CreateDirectory(cacheDir); return cacheDir; } diff --git a/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/BaseVersion.cs b/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/BaseVersion.cs index 16aec5ce62..28a574b6a0 100644 --- a/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/BaseVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/VersionSearchStrategies/BaseVersion.cs @@ -55,9 +55,7 @@ public override string ToString() stringBuilder.Append($"{Source}: "); stringBuilder.Append(Operator.ForceIncrement ? "Force version increment " : "Version increment "); - if (SemanticVersion is not null) - stringBuilder.Append($"'{SemanticVersion:f}' "); - + stringBuilder.Append($"'{SemanticVersion:f}' "); stringBuilder.Append($"+semver '{Operator.Increment}'"); if (Operator.Label is null) diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index c429db97cf..d5df195240 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; using LibGit2Sharp; @@ -7,17 +8,18 @@ namespace GitVersion.Git; internal class GitRepositoryInfo : IGitRepositoryInfo { - private readonly IOptions options; - private GitVersionOptions gitVersionOptions => this.options.Value; + private readonly IFileSystem fileSystem; + private readonly GitVersionOptions gitVersionOptions; private readonly Lazy dynamicGitRepositoryPath; private readonly Lazy dotGitDirectory; private readonly Lazy gitRootPath; private readonly Lazy projectRootDirectory; - public GitRepositoryInfo(IOptions options) + public GitRepositoryInfo(IFileSystem fileSystem, IOptions options) { - this.options = options.NotNull(); + this.fileSystem = fileSystem.NotNull(); + this.gitVersionOptions = options.NotNull().Value; this.dynamicGitRepositoryPath = new(GetDynamicGitRepositoryPath); this.dotGitDirectory = new(GetDotGitDirectory); @@ -38,12 +40,12 @@ public GitRepositoryInfo(IOptions options) var targetUrl = repositoryInfo.TargetUrl; var clonePath = repositoryInfo.ClonePath; - var userTemp = clonePath ?? Path.GetTempPath(); + var userTemp = clonePath ?? PathHelper.GetTempPath(); var repositoryName = targetUrl.Split('/', '\\').Last().Replace(".git", string.Empty); var possiblePath = PathHelper.Combine(userTemp, repositoryName); // Verify that the existing directory is ok for us to use - if (Directory.Exists(possiblePath) && !GitRepoHasMatchingRemote(possiblePath, targetUrl)) + if (this.fileSystem.Directory.Exists(possiblePath) && !GitRepoHasMatchingRemote(possiblePath, targetUrl)) { var i = 1; var originalPath = possiblePath; @@ -51,7 +53,7 @@ public GitRepositoryInfo(IOptions options) do { possiblePath = $"{originalPath}_{i++}"; - possiblePathExists = Directory.Exists(possiblePath); + possiblePathExists = this.fileSystem.Directory.Exists(possiblePath); } while (possiblePathExists && !GitRepoHasMatchingRemote(possiblePath, targetUrl)); } @@ -69,9 +71,9 @@ public GitRepositoryInfo(IOptions options) if (gitDirectory.IsNullOrEmpty()) throw new DirectoryNotFoundException("Cannot find the .git directory"); - var directoryInfo = Directory.GetParent(gitDirectory) ?? 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")) - ? Directory.GetParent(directoryInfo.FullName)?.FullName + ? this.fileSystem.Directory.GetParent(directoryInfo.FullName)?.FullName : gitDirectory; } diff --git a/src/GitVersion.LibGit2Sharp/Git/Remote.cs b/src/GitVersion.LibGit2Sharp/Git/Remote.cs index a41d7d5e80..9b409824e7 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Remote.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Remote.cs @@ -23,7 +23,7 @@ public IEnumerable RefSpecs { var refSpecs = this.innerRemote.RefSpecs; return refSpecs is null - ? Enumerable.Empty() + ? [] : new RefSpecCollection((LibGit2Sharp.RefSpecCollection)refSpecs); } } diff --git a/src/GitVersion.MsBuild.Tests/FileHelperTests.cs b/src/GitVersion.MsBuild.Tests/AssemblyInfoFileHelperTests.cs similarity index 69% rename from src/GitVersion.MsBuild.Tests/FileHelperTests.cs rename to src/GitVersion.MsBuild.Tests/AssemblyInfoFileHelperTests.cs index 6056bc5202..ddb4139b33 100644 --- a/src/GitVersion.MsBuild.Tests/FileHelperTests.cs +++ b/src/GitVersion.MsBuild.Tests/AssemblyInfoFileHelperTests.cs @@ -1,7 +1,7 @@ namespace GitVersion.MsBuild.Tests; [TestFixture] -public class FileHelperTests +public class AssemblyInfoFileHelperTests { [Test] [TestCase("C#", "cs")] @@ -12,11 +12,11 @@ public void GetFileExtensionShouldReturnCorrectExtension(string language, string { if (expectedExtension != null) { - Assert.That(FileHelper.GetFileExtension(language), Is.EqualTo(expectedExtension)); + Assert.That(AssemblyInfoFileHelper.GetFileExtension(language), Is.EqualTo(expectedExtension)); } else { - Assert.That((TestDelegate)(() => FileHelper.GetFileExtension(language)), Throws.ArgumentException.With.Message.EqualTo($"Unknown language detected: '{language}'")); + Assert.That((TestDelegate)(() => AssemblyInfoFileHelper.GetFileExtension(language)), Throws.ArgumentException.With.Message.EqualTo($"Unknown language detected: '{language}'")); } } @@ -35,10 +35,10 @@ public void GetFileWriteInfoShouldCreateConstantNamedFileWhenIntermediateOutputP [Test] public void GetFileWriteInfoShouldCreateRandomNamedFileWhenNoIntermediateOutputPath() { - var fileInfo = FileHelper.GetFileWriteInfo(null, "C#", "MyProject.csproj", "GeneratedVersionInformation"); + var fileInfo = AssemblyInfoFileHelper.GetFileWriteInfo(null, "C#", "MyProject.csproj", "GeneratedVersionInformation"); Assert.Multiple(() => { - Assert.That(fileInfo.WorkingDirectory, Is.EqualTo(FileHelper.TempPath)); + Assert.That(fileInfo.WorkingDirectory, Is.EqualTo(AssemblyInfoFileHelper.TempPath)); Assert.That(fileInfo.FileName, Does.StartWith("GeneratedVersionInformation_MyProject_").And.EndsWith(".g.cs")); Assert.That(fileInfo.FileExtension, Is.EqualTo("cs")); }); diff --git a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj index 428b5be4a2..42bf2b0fa1 100644 --- a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj +++ b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj @@ -26,13 +26,12 @@ - - + diff --git a/src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs b/src/GitVersion.MsBuild.Tests/Helpers/GitRepositoryTestingExtensions.cs similarity index 96% rename from src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs rename to src/GitVersion.MsBuild.Tests/Helpers/GitRepositoryTestingExtensions.cs index 73aff7d672..1e6069f57d 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/GitRepositoryTestingExtensions.cs @@ -6,7 +6,7 @@ namespace GitVersion.MsBuild.Tests.Helpers; -public static class GitToolsTestingExtensions +public static class GitRepositoryTestingExtensions { /// /// Simulates running on build server diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs index b05fe01433..c0a0bc82b0 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs @@ -22,7 +22,7 @@ public class MsBuildExeFixture public MsBuildExeFixture(RepositoryFixtureBase fixture, string workingDirectory = "", string language = "C#") { - var projectExtension = FileHelper.GetProjectExtension(language); + var projectExtension = AssemblyInfoFileHelper.GetProjectExtension(language); this.fixture = fixture; this.ProjectPath = PathHelper.Combine(workingDirectory, $"app.{projectExtension}"); diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index 2c9ac2b028..0e8eac0e9a 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -23,7 +23,7 @@ public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBa task.VersionFile = versionFile; - var result = task.Execute(); + var result = GitVersionTasks.Execute(task); return new MsBuildTaskFixtureResult(fixture) { diff --git a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs index 5eb2c3f2f9..2efca18ee2 100644 --- a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs +++ b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs @@ -1,6 +1,8 @@ +using System.IO.Abstractions; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using GitVersion.MsBuild.Tests.Mocks; +using Microsoft.Extensions.DependencyInjection; namespace GitVersion.MsBuild.Tests; @@ -9,25 +11,28 @@ public class InvalidFileCheckerTests : TestBase { private string projectDirectory; private string projectFile; + private IFileSystem fileSystem; [SetUp] 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"); - Directory.CreateDirectory(this.projectDirectory); + this.fileSystem.Directory.CreateDirectory(this.projectDirectory); - File.Create(this.projectFile).Close(); + this.fileSystem.File.Create(this.projectFile).Close(); } [TearDown] - public void Cleanup() => Directory.Delete(this.projectDirectory, true); + public void Cleanup() => this.fileSystem.Directory.Delete(this.projectDirectory, true); [Test] public void VerifyIgnoreNonAssemblyInfoFile() { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "SomeOtherFile.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "SomeOtherthis.fileSystem.File.cs"))) { writer.Write(""" @@ -39,13 +44,13 @@ public void VerifyIgnoreNonAssemblyInfoFile() """); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "SomeOtherFile.cs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "SomeOtherthis.fileSystem.File.cs" }], this.projectFile); } [Test] public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -57,7 +62,7 @@ public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileV """, attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile), attribute); + var ex = Assert.Throws(() => AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile), attribute); ex.ShouldNotBeNull(); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs")); } @@ -65,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 = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -78,7 +83,7 @@ public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "As """, attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile), attribute); + var ex = Assert.Throws(() => AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile), attribute); ex.ShouldNotBeNull(); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs")); } @@ -86,7 +91,7 @@ public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "As [Test] public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -98,13 +103,13 @@ public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVer """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -115,13 +120,13 @@ public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion" """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); } [Test] public void VerifyStringWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -136,13 +141,13 @@ public class Temp """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); } [Test] public void VerifyIdentifierWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(""" @@ -156,13 +161,13 @@ public class {0} """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.cs" }], this.projectFile); } [Test] public void VerifyAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -174,7 +179,7 @@ Imports System.Reflection """, attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile), attribute); + var ex = Assert.Throws(() => AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile), attribute); ex.ShouldNotBeNull(); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb")); } @@ -182,7 +187,7 @@ Imports System.Reflection [Test] public void VerifyUnformattedAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -195,7 +200,7 @@ Imports System.Reflection """, attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile), attribute); + var ex = Assert.Throws(() => AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile), attribute); ex.ShouldNotBeNull(); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb")); } @@ -203,7 +208,7 @@ Imports System.Reflection [Test] public void VerifyCommentWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -215,13 +220,13 @@ Imports System.Reflection """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -232,13 +237,13 @@ Imports System.Reflection """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); } [Test] public void VerifyStringWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -252,13 +257,13 @@ End Class """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); } [Test] public void VerifyIdentifierWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(""" @@ -271,13 +276,13 @@ End Class """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.vb" }], this.projectFile); } [Test] public void VerifyAttributeFoundFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -289,7 +294,7 @@ open System.Reflection """, attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile), attribute); + var ex = Assert.Throws(() => AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile), attribute); ex.ShouldNotBeNull(); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.fs")); } @@ -297,7 +302,7 @@ open System.Reflection [Test] public void VerifyUnformattedAttributeFoundFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -310,7 +315,7 @@ open System.Reflection """, attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile), attribute); + var ex = Assert.Throws(() => AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile), attribute); ex.ShouldNotBeNull(); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.fs")); } @@ -318,7 +323,7 @@ open System.Reflection [Test] public void VerifyCommentWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -330,13 +335,13 @@ open System.Reflection """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -347,13 +352,13 @@ open System.Reflection """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); } [Test] public void VerifyStringWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -366,13 +371,13 @@ type Temp() = """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); } [Test] public void VerifyIdentifierWorksFSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) + using (var writer = this.fileSystem.File.CreateText(PathHelper.Combine(this.projectDirectory, "AssemblyInfo.fs"))) { writer.Write(""" @@ -384,6 +389,6 @@ open System.Reflection """, attribute); } - FileHelper.CheckForInvalidFiles([new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, [new MockTaskItem { ItemSpec = "AssemblyInfo.fs" }], this.projectFile); } } diff --git a/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs index a98a3d224e..9a2892572b 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs @@ -1,4 +1,3 @@ -using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using GitVersion.MsBuild.Tasks; using GitVersion.MsBuild.Tests.Helpers; @@ -22,7 +21,7 @@ public class GenerateGitVersionInformationTest : TestTaskBase [TestCaseSource(nameof(Languages))] public void GenerateGitVersionInformationTaskShouldCreateFile(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new GenerateGitVersionInformation { Language = language }; using var result = ExecuteMsBuildTask(task); @@ -32,7 +31,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFile(string language) result.Task.GitVersionInformationFilePath.ShouldNotBeNull(); result.Task.GitVersionInformationFilePath.ShouldMatch($@"GitVersionInformation.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.GitVersionInformationFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); @@ -43,7 +42,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFile(string language) [TestCaseSource(nameof(Languages))] public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServer(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new GenerateGitVersionInformation { Language = language }; using var result = ExecuteMsBuildTaskInAzurePipeline(task); @@ -53,7 +52,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServer(strin result.Task.GitVersionInformationFilePath.ShouldNotBeNull(); result.Task.GitVersionInformationFilePath.ShouldMatch($@"GitVersionInformation.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.GitVersionInformationFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "0")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "1")); @@ -66,7 +65,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuild( { const string taskName = nameof(GenerateGitVersionInformation); const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, language), language); @@ -77,10 +76,10 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuild( result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); @@ -93,7 +92,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildI { const string taskName = nameof(GenerateGitVersionInformation); const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, language), language); @@ -104,10 +103,10 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildI result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "0")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "1")); @@ -118,7 +117,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildI [TestCaseSource(nameof(Languages))] public void GenerateGitVersionInformationTaskShouldCreateFileWhenIntermediateOutputPathDoesNotExist(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new GenerateGitVersionInformation { Language = language, IntermediateOutputPath = Guid.NewGuid().ToString("N") }; using var result = ExecuteMsBuildTask(task); @@ -128,7 +127,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenIntermediateOut result.Task.GitVersionInformationFilePath.ShouldNotBeNull(); result.Task.GitVersionInformationFilePath.ShouldMatch($@"GitVersionInformation.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.GitVersionInformationFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); @@ -140,7 +139,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenIntermediateOut [TestCaseSource(nameof(Languages))] public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServerWhenIntermediateOutputPathDoesNotExist(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new GenerateGitVersionInformation { Language = language, IntermediateOutputPath = Guid.NewGuid().ToString("N") }; using var result = ExecuteMsBuildTaskInAzurePipeline(task); @@ -150,7 +149,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServerWhenIn result.Task.GitVersionInformationFilePath.ShouldNotBeNull(); result.Task.GitVersionInformationFilePath.ShouldMatch($@"GitVersionInformation.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.GitVersionInformationFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "0")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "1")); @@ -166,7 +165,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); var randDir = Guid.NewGuid().ToString("N"); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => { var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); @@ -179,10 +178,10 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); @@ -197,7 +196,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); var randDir = Guid.NewGuid().ToString("N"); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => { var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); @@ -210,10 +209,10 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "0")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "1")); @@ -228,7 +227,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); var randDir = Guid.NewGuid().ToString("N"); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => { var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); @@ -241,10 +240,10 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); TestContext.Out.WriteLine(fileContent); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); @@ -261,7 +260,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); var randDir = Guid.NewGuid().ToString("N"); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => { var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); @@ -274,10 +273,10 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"GitVersionInformation.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "0")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "1")); @@ -289,7 +288,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA [TestCaseSource(nameof(Languages))] public void GenerateGitVersionInformationTaskShouldCreateFileWithUseProjectNamespaceSetAndRootNamespaceUnSet(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new GenerateGitVersionInformation { Language = language, @@ -303,7 +302,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWithUseProjectNames result.Task.GitVersionInformationFilePath.ShouldNotBeNull(); result.Task.GitVersionInformationFilePath.ShouldMatch($@"GitVersionInformation.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.GitVersionInformationFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); @@ -315,7 +314,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWithUseProjectNames [TestCaseSource(nameof(Languages))] public void GenerateGitVersionInformationTaskShouldCreateFileWithUseProjectNamespaceSetAndRootNamespaceIsSet(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new GenerateGitVersionInformation { Language = language, @@ -330,7 +329,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWithUseProjectNames result.Task.GitVersionInformationFilePath.ShouldNotBeNull(); result.Task.GitVersionInformationFilePath.ShouldMatch($@"GitVersionInformation.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.GitVersionInformationFilePath); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Major), "1")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Minor), "2")); fileContent.ShouldMatch(string.Format(regexPattern, nameof(GitVersionVariables.Patch), "4")); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs index ed19e7ad0c..fc155e8bb3 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs @@ -1,17 +1,26 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; -using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.MsBuild.Tests.Helpers; -using GitVersion.Output; using LibGit2Sharp; using Microsoft.Build.Utilities.ProjectCreation; +using Microsoft.Extensions.DependencyInjection; namespace GitVersion.MsBuild.Tests.Tasks; public class TestTaskBase : TestBase { + protected IFileSystem FileSystem; + + [SetUp] + public void SetUp() + { + var sp = ConfigureServices(); + this.FileSystem = sp.GetRequiredService(); + } + private static readonly IDictionary env = new Dictionary { { AzurePipelines.EnvironmentVariableName, "true" }, @@ -22,7 +31,6 @@ protected static MsBuildTaskFixtureResult ExecuteMsBuildTask(T task) where { var fixture = CreateLocalRepositoryFixture(); task.SolutionDirectory = fixture.RepositoryPath; - AddOverrides(task); var msbuildFixture = new MsBuildTaskFixture(fixture); var result = msbuildFixture.Execute(task); if (!result.Success) Console.WriteLine(result.Log); @@ -46,7 +54,6 @@ protected static MsBuildTaskFixtureResult ExecuteMsBuildTaskInAzurePipeline ExecuteMsBuildTaskInGitHubActions("GITHUB_ACTIONS", "true")); var result = msbuildFixture.Execute(task); if (!result.Success) Console.WriteLine(result.Log); @@ -92,12 +98,6 @@ protected static MsBuildExeFixtureResult ExecuteMsBuildExeInAzurePipeline(Action if (!result.MsBuild.OverallSuccess) Console.WriteLine(result.Output); return result; } - private static void AddOverrides(GitVersionTaskBase task) => - task.WithOverrides(services => - { - services.AddModule(new GitVersionBuildAgentsModule()); - services.AddModule(new GitVersionOutputModule()); - }); private static EmptyRepositoryFixture CreateLocalRepositoryFixture() { diff --git a/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs index 651f9895e5..71cf8d8b7a 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs @@ -1,4 +1,3 @@ -using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; using GitVersion.MsBuild.Tasks; using GitVersion.MsBuild.Tests.Helpers; @@ -20,7 +19,7 @@ public class UpdateAssemblyInfoTaskTest : TestTaskBase [TestCaseSource(nameof(Languages))] public void UpdateAssemblyInfoTaskShouldCreateFile(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new UpdateAssemblyInfo { Language = language }; using var result = ExecuteMsBuildTask(task); @@ -30,14 +29,14 @@ public void UpdateAssemblyInfoTaskShouldCreateFile(string language) result.Task.AssemblyInfoTempFilePath.ShouldNotBeNull(); result.Task.AssemblyInfoTempFilePath.ShouldMatch($@"AssemblyInfo.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.AssemblyInfoTempFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.AssemblyInfoTempFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.2.4.0"")"); } [TestCaseSource(nameof(Languages))] public void UpdateAssemblyInfoTaskShouldCreateFileInBuildServer(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new UpdateAssemblyInfo { Language = language }; using var result = ExecuteMsBuildTaskInAzurePipeline(task); @@ -47,7 +46,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileInBuildServer(string language) result.Task.AssemblyInfoTempFilePath.ShouldNotBeNull(); result.Task.AssemblyInfoTempFilePath.ShouldMatch($@"AssemblyInfo.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.AssemblyInfoTempFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.AssemblyInfoTempFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.0.1.0"")"); } @@ -57,7 +56,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuild(string lang const string taskName = nameof(UpdateAssemblyInfo); const string outputProperty = nameof(UpdateAssemblyInfo.AssemblyInfoTempFilePath); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty, language), language); @@ -67,10 +66,10 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuild(string lang result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.2.4.0"")"); } @@ -80,7 +79,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildInBuildServe const string taskName = nameof(UpdateAssemblyInfo); const string outputProperty = nameof(UpdateAssemblyInfo.AssemblyInfoTempFilePath); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty, language), language); @@ -90,17 +89,17 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildInBuildServe result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.0.1.0"")"); } [TestCaseSource(nameof(Languages))] public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoesNotExist(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new UpdateAssemblyInfo { Language = language, IntermediateOutputPath = Guid.NewGuid().ToString("N") }; using var result = ExecuteMsBuildTask(task); @@ -110,7 +109,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoes result.Task.AssemblyInfoTempFilePath.ShouldNotBeNull(); result.Task.AssemblyInfoTempFilePath.ShouldMatch($@"AssemblyInfo.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.AssemblyInfoTempFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.AssemblyInfoTempFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.2.4.0"")"); DirectoryHelper.DeleteDirectory(task.IntermediateOutputPath); } @@ -118,7 +117,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoes [TestCaseSource(nameof(Languages))] public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoesNotExistInBuildServer(string language) { - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); var task = new UpdateAssemblyInfo { Language = language, IntermediateOutputPath = Guid.NewGuid().ToString("N") }; using var result = ExecuteMsBuildTaskInAzurePipeline(task); @@ -128,7 +127,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenIntermediateOutputPathDoes result.Task.AssemblyInfoTempFilePath.ShouldNotBeNull(); result.Task.AssemblyInfoTempFilePath.ShouldMatch($@"AssemblyInfo.*\.g\.{extension}"); - var fileContent = File.ReadAllText(result.Task.AssemblyInfoTempFilePath); + var fileContent = this.FileSystem.File.ReadAllText(result.Task.AssemblyInfoTempFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.0.1.0"")"); DirectoryHelper.DeleteDirectory(task.IntermediateOutputPath); } @@ -140,7 +139,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi const string outputProperty = nameof(UpdateAssemblyInfo.AssemblyInfoTempFilePath); var randDir = Guid.NewGuid().ToString("N"); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExe(project => { var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); @@ -153,10 +152,10 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.2.4.0"")"); } @@ -167,7 +166,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi const string outputProperty = nameof(UpdateAssemblyInfo.AssemblyInfoTempFilePath); var randDir = Guid.NewGuid().ToString("N"); - var extension = FileHelper.GetFileExtension(language); + var extension = AssemblyInfoFileHelper.GetFileExtension(language); using var result = ExecuteMsBuildExeInAzurePipeline(project => { var intermediateOutputPath = PathHelper.Combine("$(MSBuildProjectDirectory)", randDir); @@ -180,10 +179,10 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildAndIntermedi result.MsBuild.ShouldAllBe(x => x.Succeeded); result.Output.ShouldNotBeNullOrWhiteSpace(); - var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); + var generatedFilePath = PathHelper.Combine(PathHelper.GetDirectoryName(result.ProjectPath), randDir, $"AssemblyInfo.g.{extension}"); result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}"); - var fileContent = File.ReadAllText(generatedFilePath); + var fileContent = this.FileSystem.File.ReadAllText(generatedFilePath); fileContent.ShouldContain(@"assembly: AssemblyVersion(""1.0.1.0"")"); } diff --git a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs index a941917b96..d45eff7758 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs @@ -74,21 +74,17 @@ public void WriteVersionInfoTaskShouldLogOutputVariablesToBuildOutputInGitHubAct envFilePath = $"{PathHelper.GetTempPath()}/github-env.txt"; SysEnv.SetEnvironmentVariable("GITHUB_ENV", envFilePath); - if (File.Exists(envFilePath)) - { - File.Delete(envFilePath); - } - var task = new WriteVersionInfoToBuildLog(); using var result = ExecuteMsBuildTaskInGitHubActions(task); result.Success.ShouldBe(true); result.Errors.ShouldBe(0); - string content = File.ReadAllText(envFilePath); + + string content = this.FileSystem.File.ReadAllText(envFilePath); content.ShouldContain("GitVersion_SemVer=1.0.1"); - File.Delete(envFilePath); + this.FileSystem.File.Delete(envFilePath); } [Test] diff --git a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj index 033f10f2b4..a2d4f5176a 100644 --- a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj +++ b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj @@ -19,6 +19,7 @@ + diff --git a/src/GitVersion.MsBuild/GitVersionTaskBase.cs b/src/GitVersion.MsBuild/GitVersionTaskBase.cs index 1be2bafb80..a7fb78a9ac 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskBase.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskBase.cs @@ -1,6 +1,5 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; -using Microsoft.Extensions.DependencyInjection; namespace GitVersion.MsBuild; @@ -18,11 +17,5 @@ public abstract class GitVersionTaskBase : ITask public TaskLoggingHelper Log { get; } - public bool Execute() => OnExecute(); - - protected abstract bool OnExecute(); - - public Action? Overrides { get; set; } - - public void WithOverrides(Action overrides) => Overrides = overrides; + public bool Execute() => GitVersionTasks.Execute(this); } diff --git a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs index d51d364d95..a5c7ed5e25 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Helpers; @@ -34,21 +35,20 @@ public void GetVersion(GetVersion task) public void UpdateAssemblyInfo(UpdateAssemblyInfo task) { var versionVariables = GitVersionVariables(task); - DeleteTempFiles(); - FileHelper.CheckForInvalidFiles(task.CompileFiles, task.ProjectFile); + AssemblyInfoFileHelper.CheckForInvalidFiles(this.fileSystem, task.CompileFiles, task.ProjectFile); if (!string.IsNullOrEmpty(task.IntermediateOutputPath)) { // Ensure provided output path exists first. Fixes issue #2815. - fileSystem.CreateDirectory(task.IntermediateOutputPath); + fileSystem.Directory.CreateDirectory(task.IntermediateOutputPath); } var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "AssemblyInfo"); task.AssemblyInfoTempFilePath = PathHelper.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - if (!this.fileSystem.DirectoryExists(fileWriteInfo.WorkingDirectory)) + if (!this.fileSystem.Directory.Exists(fileWriteInfo.WorkingDirectory)) { - this.fileSystem.CreateDirectory(fileWriteInfo.WorkingDirectory); + this.fileSystem.Directory.CreateDirectory(fileWriteInfo.WorkingDirectory); } var gitVersionOptions = this.options.Value; gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory; @@ -66,15 +66,15 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) if (!string.IsNullOrEmpty(task.IntermediateOutputPath)) { // Ensure provided output path exists first. Fixes issue #2815. - fileSystem.CreateDirectory(task.IntermediateOutputPath); + fileSystem.Directory.CreateDirectory(task.IntermediateOutputPath); } var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "GitVersionInformation"); task.GitVersionInformationFilePath = PathHelper.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - if (!this.fileSystem.DirectoryExists(fileWriteInfo.WorkingDirectory)) + if (!this.fileSystem.Directory.Exists(fileWriteInfo.WorkingDirectory)) { - this.fileSystem.CreateDirectory(fileWriteInfo.WorkingDirectory); + this.fileSystem.Directory.CreateDirectory(fileWriteInfo.WorkingDirectory); } var gitVersionOptions = this.options.Value; gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory; @@ -90,7 +90,7 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) targetNamespace = task.RootNamespace; if (string.IsNullOrWhiteSpace(targetNamespace)) { - targetNamespace = Path.GetFileNameWithoutExtension(task.ProjectFile); + targetNamespace = PathHelper.GetFileNameWithoutExtension(task.ProjectFile); } } @@ -108,28 +108,5 @@ public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) gitVersionOutputTool.OutputVariables(versionVariables, configuration.UpdateBuildNumber); } - private void DeleteTempFiles() - { - var tempPath = FileHelper.TempPath; - if (!this.fileSystem.DirectoryExists(tempPath)) - { - return; - } - - foreach (var file in this.fileSystem.GetFiles(tempPath)) - { - if (this.fileSystem.GetLastWriteTime(file) >= DateTime.Now.AddDays(-1).Ticks) - continue; - try - { - this.fileSystem.Delete(file); - } - catch (UnauthorizedAccessException) - { - //ignore contention - } - } - } - private GitVersionVariables GitVersionVariables(GitVersionTaskBase task) => serializer.FromFile(task.VersionFile); } diff --git a/src/GitVersion.MsBuild/GitVersionTasks.cs b/src/GitVersion.MsBuild/GitVersionTasks.cs index c2facf75d9..7a32e88101 100644 --- a/src/GitVersion.MsBuild/GitVersionTasks.cs +++ b/src/GitVersion.MsBuild/GitVersionTasks.cs @@ -11,24 +11,27 @@ namespace GitVersion.MsBuild; internal static class GitVersionTasks { - public static bool GetVersion(GetVersion task) => ExecuteGitVersionTask(task, executor => executor.GetVersion(task)); - - public static bool UpdateAssemblyInfo(UpdateAssemblyInfo task) => ExecuteGitVersionTask(task, executor => executor.UpdateAssemblyInfo(task)); - - public static bool GenerateGitVersionInformation(GenerateGitVersionInformation task) => ExecuteGitVersionTask(task, executor => executor.GenerateGitVersionInformation(task)); - - public static bool WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) => ExecuteGitVersionTask(task, executor => executor.WriteVersionInfoToBuildLog(task)); + public static bool Execute(GitVersionTaskBase task) + { + var serviceProvider = BuildServiceProvider(task); + var executor = serviceProvider.GetRequiredService(); + return task switch + { + GetVersion getVersion => ExecuteGitVersionTask(getVersion, () => executor.GetVersion(getVersion)), + UpdateAssemblyInfo updateAssemblyInfo => ExecuteGitVersionTask(updateAssemblyInfo, () => executor.UpdateAssemblyInfo(updateAssemblyInfo)), + GenerateGitVersionInformation generateGitVersionInformation => ExecuteGitVersionTask(generateGitVersionInformation, () => executor.GenerateGitVersionInformation(generateGitVersionInformation)), + WriteVersionInfoToBuildLog writeVersionInfoToBuildLog => ExecuteGitVersionTask(writeVersionInfoToBuildLog, () => executor.WriteVersionInfoToBuildLog(writeVersionInfoToBuildLog)), + _ => throw new NotSupportedException($"Task type {task.GetType().Name} is not supported") + }; + } - private static bool ExecuteGitVersionTask(T task, Action action) + private static bool ExecuteGitVersionTask(T task, Action action) where T : GitVersionTaskBase { var taskLog = task.Log; try { - var sp = BuildServiceProvider(task); - var gitVersionTaskExecutor = sp.GetRequiredService(); - - action(gitVersionTaskExecutor); + action(); } catch (WarningException errorException) { @@ -75,7 +78,6 @@ private static IServiceProvider BuildServiceProvider(GitVersionTaskBase task) services.AddModule(new GitVersionOutputModule()); services.AddModule(new GitVersionMsBuildModule()); services.AddSingleton(new MsBuildAdapter(task.Log)); - task.Overrides?.Invoke(services); var sp = services.BuildServiceProvider(); Configure(sp, task); diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs similarity index 66% rename from src/GitVersion.MsBuild/Helpers/FileHelper.cs rename to src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs index ce3d1e9da7..ae730660e5 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/AssemblyInfoFileHelper.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Text.RegularExpressions; using GitVersion.Helpers; using Microsoft.Build.Framework; @@ -6,11 +7,11 @@ namespace GitVersion.MsBuild; -internal static class FileHelper +internal static class AssemblyInfoFileHelper { public static readonly string TempPath = MakeAndGetTempPath(); - private static string MakeAndGetTempPath() => PathHelper.Combine(Path.GetTempPath(), "GitVersionTask"); + private static string MakeAndGetTempPath() => PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionTask"); public static string GetFileExtension(string language) => language switch { @@ -28,18 +29,18 @@ internal static class FileHelper _ => throw new ArgumentException($"Unknown language detected: '{language}'") }; - public static void CheckForInvalidFiles(IEnumerable compileFiles, string projectFile) + public static void CheckForInvalidFiles(IFileSystem fileSystem, IEnumerable compileFiles, string projectFile) { - var invalidCompileFile = GetInvalidFiles(compileFiles, projectFile).FirstOrDefault(); + var invalidCompileFile = GetInvalidFiles(fileSystem, compileFiles, projectFile).FirstOrDefault(); if (invalidCompileFile != null) { throw new WarningException("File contains assembly version attributes which conflict with the attributes generated by GitVersion " + invalidCompileFile); } } - private static bool FileContainsVersionAttribute(string compileFile, string projectFile) + private static bool FileContainsVersionAttribute(IFileSystem fileSystem, string compileFile, string projectFile) { - var compileFileExtension = Path.GetExtension(compileFile); + var compileFileExtension = PathHelper.GetExtension(compileFile); var (attributeRegex, triviaRegex) = compileFileExtension switch { @@ -49,23 +50,23 @@ private static bool FileContainsVersionAttribute(string compileFile, string proj _ => throw new WarningException("File with name containing AssemblyInfo could not be checked for assembly version attributes which conflict with the attributes generated by GitVersion " + compileFile) }; - return FileContainsVersionAttribute(compileFile, projectFile, attributeRegex, triviaRegex); + return FileContainsVersionAttribute(fileSystem, compileFile, projectFile, attributeRegex, triviaRegex); } - private static bool FileContainsVersionAttribute(string compileFile, string projectFile, Regex attributeRegex, Regex triviaRegex) + private static bool FileContainsVersionAttribute(IFileSystem fileSystem, string compileFile, string projectFile, Regex attributeRegex, Regex triviaRegex) { - var combine = PathHelper.Combine(Path.GetDirectoryName(projectFile), compileFile); - var allText = File.ReadAllText(combine); + var combine = PathHelper.Combine(PathHelper.GetDirectoryName(projectFile), compileFile); + var allText = fileSystem.File.ReadAllText(combine); allText += PathHelper.NewLine; // Always add a new line, this handles the case for when a file ends with the EOF marker and no new line. var noCommentsOrStrings = triviaRegex.Replace(allText, me => me.Value.StartsWith("//") || me.Value.StartsWith("'") ? PathHelper.NewLine : string.Empty); return attributeRegex.IsMatch(noCommentsOrStrings); } - private static IEnumerable GetInvalidFiles(IEnumerable compileFiles, string projectFile) + private static IEnumerable GetInvalidFiles(IFileSystem fileSystem, IEnumerable compileFiles, string projectFile) => compileFiles.Select(x => x.ItemSpec) .Where(compileFile => compileFile.Contains("AssemblyInfo")) - .Where(s => FileContainsVersionAttribute(s, projectFile)); + .Where(filePath => FileContainsVersionAttribute(fileSystem, filePath, projectFile)); public static FileWriteInfo GetFileWriteInfo(this string? intermediateOutputPath, string language, string projectFile, string outputFileName) { @@ -74,7 +75,7 @@ public static FileWriteInfo GetFileWriteInfo(this string? intermediateOutputPath if (intermediateOutputPath == null) { - fileName = $"{outputFileName}_{Path.GetFileNameWithoutExtension(projectFile)}_{Path.GetRandomFileName()}.g.{fileExtension}"; + fileName = $"{outputFileName}_{PathHelper.GetFileNameWithoutExtension(projectFile)}_{PathHelper.GetRandomFileName()}.g.{fileExtension}"; workingDirectory = TempPath; } else diff --git a/src/GitVersion.MsBuild/PublicAPI.Shipped.txt b/src/GitVersion.MsBuild/PublicAPI.Shipped.txt index b395a292de..3325cd24ce 100644 --- a/src/GitVersion.MsBuild/PublicAPI.Shipped.txt +++ b/src/GitVersion.MsBuild/PublicAPI.Shipped.txt @@ -1,5 +1,4 @@ #nullable enable -abstract GitVersion.MsBuild.GitVersionTaskBase.OnExecute() -> bool GitVersion.MsBuild.GitVersionMsBuildModule GitVersion.MsBuild.GitVersionMsBuildModule.GitVersionMsBuildModule() -> void GitVersion.MsBuild.GitVersionMsBuildModule.RegisterTypes(Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> void @@ -11,13 +10,10 @@ GitVersion.MsBuild.GitVersionTaskBase.GitVersionTaskBase() -> void GitVersion.MsBuild.GitVersionTaskBase.HostObject.get -> Microsoft.Build.Framework.ITaskHost! GitVersion.MsBuild.GitVersionTaskBase.HostObject.set -> void GitVersion.MsBuild.GitVersionTaskBase.Log.get -> Microsoft.Build.Utilities.TaskLoggingHelper! -GitVersion.MsBuild.GitVersionTaskBase.Overrides.get -> System.Action? -GitVersion.MsBuild.GitVersionTaskBase.Overrides.set -> void GitVersion.MsBuild.GitVersionTaskBase.SolutionDirectory.get -> string! GitVersion.MsBuild.GitVersionTaskBase.SolutionDirectory.set -> void GitVersion.MsBuild.GitVersionTaskBase.VersionFile.get -> string! GitVersion.MsBuild.GitVersionTaskBase.VersionFile.set -> void -GitVersion.MsBuild.GitVersionTaskBase.WithOverrides(System.Action! overrides) -> void GitVersion.MsBuild.Tasks.GenerateGitVersionInformation GitVersion.MsBuild.Tasks.GenerateGitVersionInformation.GenerateGitVersionInformation() -> void GitVersion.MsBuild.Tasks.GenerateGitVersionInformation.GitVersionInformationFilePath.get -> string! @@ -98,7 +94,3 @@ GitVersion.MsBuild.Tasks.UpdateAssemblyInfo.ProjectFile.set -> void GitVersion.MsBuild.Tasks.UpdateAssemblyInfo.UpdateAssemblyInfo() -> void GitVersion.MsBuild.Tasks.WriteVersionInfoToBuildLog GitVersion.MsBuild.Tasks.WriteVersionInfoToBuildLog.WriteVersionInfoToBuildLog() -> void -override GitVersion.MsBuild.Tasks.GenerateGitVersionInformation.OnExecute() -> bool -override GitVersion.MsBuild.Tasks.GetVersion.OnExecute() -> bool -override GitVersion.MsBuild.Tasks.UpdateAssemblyInfo.OnExecute() -> bool -override GitVersion.MsBuild.Tasks.WriteVersionInfoToBuildLog.OnExecute() -> bool diff --git a/src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs b/src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs index 92c0fb95af..b192216a1c 100644 --- a/src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs +++ b/src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs @@ -19,6 +19,4 @@ public class GenerateGitVersionInformation : GitVersionTaskBase [Output] public string GitVersionInformationFilePath { get; set; } - - protected override bool OnExecute() => GitVersionTasks.GenerateGitVersionInformation(this); } diff --git a/src/GitVersion.MsBuild/Tasks/GetVersion.cs b/src/GitVersion.MsBuild/Tasks/GetVersion.cs index 3fca217eef..2a3e695a99 100644 --- a/src/GitVersion.MsBuild/Tasks/GetVersion.cs +++ b/src/GitVersion.MsBuild/Tasks/GetVersion.cs @@ -78,6 +78,4 @@ public class GetVersion : GitVersionTaskBase [Output] public string UncommittedChanges { get; set; } - - protected override bool OnExecute() => GitVersionTasks.GetVersion(this); } diff --git a/src/GitVersion.MsBuild/Tasks/UpdateAssemblyInfo.cs b/src/GitVersion.MsBuild/Tasks/UpdateAssemblyInfo.cs index 41fefe580d..b243cfa606 100644 --- a/src/GitVersion.MsBuild/Tasks/UpdateAssemblyInfo.cs +++ b/src/GitVersion.MsBuild/Tasks/UpdateAssemblyInfo.cs @@ -18,6 +18,4 @@ public class UpdateAssemblyInfo : GitVersionTaskBase [Output] public string AssemblyInfoTempFilePath { get; set; } - - protected override bool OnExecute() => GitVersionTasks.UpdateAssemblyInfo(this); } diff --git a/src/GitVersion.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs b/src/GitVersion.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs index b92f7dd187..3ee822c61e 100644 --- a/src/GitVersion.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs +++ b/src/GitVersion.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs @@ -1,6 +1,3 @@ namespace GitVersion.MsBuild.Tasks; -public class WriteVersionInfoToBuildLog : GitVersionTaskBase -{ - protected override bool OnExecute() => GitVersionTasks.WriteVersionInfoToBuildLog(this); -} +public class WriteVersionInfoToBuildLog : GitVersionTaskBase; diff --git a/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs b/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs index 557d7d1abd..bf5ea3e1d5 100644 --- a/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs +++ b/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -50,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.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); } [TestCase("cs")] @@ -67,7 +68,7 @@ public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new(workingDir, true, assemblyInfoFile)); - this.fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); } [TestCase("cs")] @@ -84,7 +85,7 @@ public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInf foreach (var item in assemblyInfoFiles) { var fullPath = PathHelper.Combine(workingDir, item); - this.fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + this.fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); } } @@ -102,7 +103,7 @@ public void ShouldNotCreateAssemblyInfoFileWhenNotExistsAndNotEnsureAssemblyInfo using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - this.fileSystem.Exists(fullPath).ShouldBeFalse(); + this.fileSystem.File.Exists(fullPath).ShouldBeFalse(); } [Test] @@ -119,7 +120,7 @@ public void ShouldNotCreateAssemblyInfoFileForUnknownSourceCodeAndEnsureAssembly using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new(workingDir, true, assemblyInfoFile)); - this.fileSystem.Received(0).WriteAllText(fullPath, Arg.Any()); + this.fileSystem.Received(1).File.WriteAllText(fullPath, Arg.Any()); } [Test] @@ -135,7 +136,7 @@ public void ShouldStartSearchFromWorkingDirectory() using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, [.. assemblyInfoFiles])); - this.fileSystem.Received().DirectoryEnumerateFiles(Arg.Is(workingDir), Arg.Any(), Arg.Any()); + this.fileSystem.Received(1).Directory.EnumerateFiles(Arg.Is(workingDir), Arg.Any(), Arg.Any()); } [TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]")] @@ -151,7 +152,7 @@ public void ShouldReplaceAssemblyVersion(string fileExtension, string assemblyFi using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -171,7 +172,7 @@ public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileEx using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - assemblyFileContent = fs.ReadAllText(fileName); + assemblyFileContent = fs.File.ReadAllText(fileName); assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); }); } @@ -189,7 +190,7 @@ public void ShouldReplaceAssemblyVersionInRelativePath(string fileExtension, str using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -209,7 +210,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithWhiteSpace(string file using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -229,7 +230,7 @@ public void ShouldReplaceAssemblyVersionWithStar(string fileExtension, string as using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -249,7 +250,7 @@ public void ShouldReplaceAssemblyVersionWithAttributeSuffix(string fileExtension using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => !s.Contains(@"AssemblyVersionAttribute(""1.0.0.0"")") && !s.Contains(@"AssemblyInformationalVersionAttribute(""1.0.0.0"")") && !s.Contains(@"AssemblyFileVersionAttribute(""1.0.0.0"")") && @@ -272,7 +273,7 @@ public void ShouldAddAssemblyVersionIfMissingFromInfoFile(string fileExtension) using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -292,7 +293,7 @@ public void ShouldReplaceAlreadySubstitutedValues(string fileExtension, string a using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -312,7 +313,7 @@ public void ShouldReplaceAssemblyVersionWhenCreatingAssemblyVersionFileAndEnsure using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.1.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -332,7 +333,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariables(string fileE using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -352,7 +353,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariablesAndWhiteSpace using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - fs.Received().WriteAllText(fileName, Arg.Is(s => + fs.Received().File.WriteAllText(fileName, Arg.Is(s => s.Contains(@"AssemblyVersion(""2.3.0.0"")") && s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") && s.Contains(@"AssemblyFileVersion(""2.3.1.0"")"))); @@ -372,7 +373,7 @@ public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - assemblyFileContent = fs.ReadAllText(fileName); + assemblyFileContent = fs.File.ReadAllText(fileName); assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); }); } @@ -390,7 +391,7 @@ public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttri using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - assemblyFileContent = fs.ReadAllText(fileName); + assemblyFileContent = fs.File.ReadAllText(fileName); assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); }); } @@ -408,7 +409,7 @@ public void ShouldNotAddAssemblyInformationalVersionWhenVersionSchemeIsNone(stri using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new(workingDir, false, assemblyInfoFile)); - assemblyFileContent = fs.ReadAllText(fileName); + assemblyFileContent = fs.File.ReadAllText(fileName); assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); }); } @@ -419,20 +420,23 @@ private void VerifyAssemblyInfoFile( AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch, Action? verify = null) { - this.fileSystem = Substitute.For(); + var file = Substitute.For(); var version = new SemanticVersion { BuildMetaData = new("versionSourceHash", 3, "foo", "hash", "shortHash", DateTimeOffset.Now, 0), Major = 2, Minor = 3, Patch = 1 }; - this.fileSystem.Exists(fileName).Returns(true); - this.fileSystem.ReadAllText(fileName).Returns(assemblyFileContent); - this.fileSystem.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => + file.Exists(fileName).Returns(true); + file.ReadAllText(fileName).Returns(assemblyFileContent); + file.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => { assemblyFileContent = c.ArgAt(1); - this.fileSystem.ReadAllText(fileName).Returns(assemblyFileContent); + file.ReadAllText(fileName).Returns(assemblyFileContent); }); var configuration = EmptyConfigurationBuilder.New.WithAssemblyVersioningScheme(versioningScheme).Build(); var variables = this.variableProvider.GetVariablesFor(version, configuration, 0); + this.fileSystem = Substitute.For(); + this.fileSystem.File.Returns(file); + this.fileSystem.FileInfo.Returns(new FileSystem().FileInfo); verify?.Invoke(this.fileSystem, variables); } } diff --git a/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs b/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs index 284f3d6b65..0d7fc9f14c 100644 --- a/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs +++ b/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -34,8 +35,8 @@ public void ShouldCreateFile(string fileExtension) var fileSystem = sp.GetRequiredService(); var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); - if (!fileSystem.DirectoryExists(directory)) - fileSystem.CreateDirectory(directory); + if (!fileSystem.Directory.Exists(directory)) + fileSystem.Directory.CreateDirectory(directory); var fileName = "GitVersionInformation.g." + fileExtension; var fullPath = PathHelper.Combine(directory, fileName); @@ -45,7 +46,7 @@ public void ShouldCreateFile(string fileExtension) generator.Execute(variables, new(directory, fileName, fileExtension)); - fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); DirectoryHelper.DeleteDirectory(directory); } @@ -75,8 +76,8 @@ public void ShouldProperlyOutputNamespaceDeclaration(string fileExtension) var fileSystem = sp.GetRequiredService(); var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); - if (!fileSystem.DirectoryExists(directory)) - fileSystem.CreateDirectory(directory); + if (!fileSystem.Directory.Exists(directory)) + fileSystem.Directory.CreateDirectory(directory); var fileName = "GitVersionInformation.g." + fileExtension; var fullPath = PathHelper.Combine(directory, fileName); @@ -86,7 +87,7 @@ public void ShouldProperlyOutputNamespaceDeclaration(string fileExtension) generator.Execute(variables, new(directory, fileName, fileExtension, targetNamespace)); - fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); + fileSystem.File.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved", fileExtension))); DirectoryHelper.DeleteDirectory(directory); } diff --git a/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs b/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs index 4665479e8f..bca5e0cade 100644 --- a/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs +++ b/src/GitVersion.Output.Tests/Output/ProjectFileUpdaterTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Xml.Linq; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; @@ -293,7 +294,7 @@ public void UpdateProjectFileAddsVersionToFile(string xml) """; - var transformedXml = fs.ReadAllText(fileName); + var transformedXml = fs.File.ReadAllText(fileName); transformedXml.ShouldBe(XElement.Parse(expectedXml).ToString()); }); } @@ -304,20 +305,23 @@ private void VerifyAssemblyInfoFile( AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch, Action? verify = null) { - this.fileSystem = Substitute.For(); + var file = Substitute.For(); var version = new SemanticVersion { BuildMetaData = new("versionSourceHash", 3, "foo", "hash", "shortHash", DateTimeOffset.Now, 0), Major = 2, Minor = 3, Patch = 1 }; - this.fileSystem.Exists(fileName).Returns(true); - this.fileSystem.ReadAllText(fileName).Returns(projectFileContent); - this.fileSystem.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => + file.Exists(fileName).Returns(true); + file.ReadAllText(fileName).Returns(projectFileContent); + file.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => { projectFileContent = c.ArgAt(1); - this.fileSystem.ReadAllText(fileName).Returns(projectFileContent); + file.ReadAllText(fileName).Returns(projectFileContent); }); var configuration = EmptyConfigurationBuilder.New.WithAssemblyVersioningScheme(versioningScheme).Build(); var variables = this.variableProvider.GetVariablesFor(version, configuration, 0); + this.fileSystem = Substitute.For(); + this.fileSystem.File.Returns(file); + this.fileSystem.FileInfo.Returns(new FileSystem().FileInfo); verify?.Invoke(this.fileSystem, variables); } } diff --git a/src/GitVersion.Output.Tests/Output/WixFileTests.cs b/src/GitVersion.Output.Tests/Output/WixFileTests.cs index ebd91284f2..cda4d0c1a4 100644 --- a/src/GitVersion.Output.Tests/Output/WixFileTests.cs +++ b/src/GitVersion.Output.Tests/Output/WixFileTests.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Helpers; @@ -58,7 +59,7 @@ public void UpdateWixVersionFile() var file = PathHelper.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); fileSystem - .ReadAllText(file) + .File.ReadAllText(file) .ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved"))); } @@ -95,16 +96,16 @@ public void UpdateWixVersionFileWhenFileAlreadyExists() // fake an already existing file var file = PathHelper.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); - if (!fileSystem.DirectoryExists(workingDir)) + if (!fileSystem.Directory.Exists(workingDir)) { - fileSystem.CreateDirectory(workingDir); + fileSystem.Directory.CreateDirectory(workingDir); } - fileSystem.WriteAllText(file, new('x', 1024 * 1024)); + fileSystem.File.WriteAllText(file, new('x', 1024 * 1024)); wixVersionFileUpdater.Execute(versionVariables, new(workingDir)); fileSystem - .ReadAllText(file) + .File.ReadAllText(file) .ShouldMatchApproved(c => c.SubFolder(PathHelper.Combine("Approved"))); } } diff --git a/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs b/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs index e445500585..b80c7a1669 100644 --- a/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs +++ b/src/GitVersion.Output/AssemblyInfo/AssemblyInfoFileUpdater.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Text.RegularExpressions; using GitVersion.Core; using GitVersion.Extensions; @@ -44,21 +45,21 @@ public void Execute(GitVersionVariables variables, AssemblyInfoContext context) { var localAssemblyInfo = assemblyInfoFile.FullName; var backupAssemblyInfo = localAssemblyInfo + ".bak"; - fileSystem.Copy(localAssemblyInfo, backupAssemblyInfo, true); + fileSystem.File.Copy(localAssemblyInfo, backupAssemblyInfo, true); this.restoreBackupTasks.Add(() => { - if (fileSystem.Exists(localAssemblyInfo)) + if (fileSystem.File.Exists(localAssemblyInfo)) { - fileSystem.Delete(localAssemblyInfo); + fileSystem.File.Delete(localAssemblyInfo); } - fileSystem.Move(backupAssemblyInfo, localAssemblyInfo); + fileSystem.File.Move(backupAssemblyInfo, localAssemblyInfo); }); - this.cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo)); + this.cleanupBackupTasks.Add(() => fileSystem.File.Delete(backupAssemblyInfo)); - var originalFileContents = fileSystem.ReadAllText(localAssemblyInfo); + var originalFileContents = fileSystem.File.ReadAllText(localAssemblyInfo); var fileContents = originalFileContents; var appendedAttributes = false; @@ -85,7 +86,7 @@ public void Execute(GitVersionVariables variables, AssemblyInfoContext context) if (originalFileContents != fileContents) { - fileSystem.WriteAllText(localAssemblyInfo, fileContents); + fileSystem.File.WriteAllText(localAssemblyInfo, fileContents); } } CommitChanges(); @@ -143,7 +144,7 @@ private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRe return inputString; } - private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) + private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) { var workingDirectory = context.WorkingDirectory; var ensureAssemblyInfo = context.EnsureAssemblyInfo; @@ -157,15 +158,15 @@ private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) if (EnsureVersionAssemblyInfoFile(fullPath, ensureAssemblyInfo)) { - yield return new FileInfo(fullPath); + yield return fileSystem.FileInfo.New(fullPath); } } } else { - foreach (var item in fileSystem.DirectoryEnumerateFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories)) + foreach (var item in fileSystem.Directory.EnumerateFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories)) { - var assemblyInfoFile = new FileInfo(item); + var assemblyInfoFile = fileSystem.FileInfo.New(item); if (this.templateManager.IsSupported(assemblyInfoFile.Extension)) { @@ -178,7 +179,7 @@ private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyInfo) { fullPath = fullPath.NotNull(); - if (fileSystem.Exists(fullPath)) + if (fileSystem.File.Exists(fullPath)) { return true; } @@ -188,18 +189,18 @@ private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyI return false; } - var assemblyInfoSource = this.templateManager.GetTemplateFor(Path.GetExtension(fullPath)); + var assemblyInfoSource = this.templateManager.GetTemplateFor(PathHelper.GetExtension(fullPath)!); if (!assemblyInfoSource.IsNullOrWhiteSpace()) { - var fileInfo = new FileInfo(fullPath); + var fileInfo = fileSystem.FileInfo.New(fullPath); - if (fileInfo.Directory != null && !fileSystem.DirectoryExists(fileInfo.Directory.FullName)) + if (fileInfo.Directory != null && !fileSystem.Directory.Exists(fileInfo.Directory.FullName)) { - fileSystem.CreateDirectory(fileInfo.Directory.FullName); + fileSystem.Directory.CreateDirectory(fileInfo.Directory.FullName); } - fileSystem.WriteAllText(fullPath, assemblyInfoSource); + fileSystem.File.WriteAllText(fullPath, assemblyInfoSource); return true; } diff --git a/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs index 8588f27153..163b0592a3 100644 --- a/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Output/AssemblyInfo/ProjectFileUpdater.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Xml.Linq; using GitVersion.Extensions; using GitVersion.Helpers; @@ -37,7 +38,7 @@ public void Execute(GitVersionVariables variables, AssemblyInfoContext context) { var localProjectFile = projectFile.FullName; - var originalFileContents = fileSystem.ReadAllText(localProjectFile); + var originalFileContents = fileSystem.File.ReadAllText(localProjectFile); XElement fileXml; try { @@ -57,19 +58,19 @@ public void Execute(GitVersionVariables variables, AssemblyInfoContext context) log.Debug($"Update file: {localProjectFile}"); var backupProjectFile = localProjectFile + ".bak"; - fileSystem.Copy(localProjectFile, backupProjectFile, true); + fileSystem.File.Copy(localProjectFile, backupProjectFile, true); this.restoreBackupTasks.Add(() => { - if (fileSystem.Exists(localProjectFile)) + if (fileSystem.File.Exists(localProjectFile)) { - fileSystem.Delete(localProjectFile); + fileSystem.File.Delete(localProjectFile); } - fileSystem.Move(backupProjectFile, localProjectFile); + fileSystem.File.Move(backupProjectFile, localProjectFile); }); - this.cleanupBackupTasks.Add(() => fileSystem.Delete(backupProjectFile)); + this.cleanupBackupTasks.Add(() => fileSystem.File.Delete(backupProjectFile)); if (!assemblyVersion.IsNullOrWhiteSpace()) { @@ -94,7 +95,7 @@ public void Execute(GitVersionVariables variables, AssemblyInfoContext context) var outputXmlString = fileXml.ToString(); if (originalFileContents != outputXmlString) { - fileSystem.WriteAllText(localProjectFile, outputXmlString); + fileSystem.File.WriteAllText(localProjectFile, outputXmlString); } } @@ -173,7 +174,7 @@ private void CommitChanges() this.restoreBackupTasks.Clear(); } - private IEnumerable GetProjectFiles(AssemblyInfoContext context) + private IEnumerable GetProjectFiles(AssemblyInfoContext context) { var workingDirectory = context.WorkingDirectory; var assemblyInfoFileNames = new HashSet(context.AssemblyInfoFiles); @@ -184,9 +185,9 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) { var fullPath = PathHelper.Combine(workingDirectory, item); - if (fileSystem.Exists(fullPath)) + if (fileSystem.File.Exists(fullPath)) { - yield return new FileInfo(fullPath); + yield return fileSystem.FileInfo.New(fullPath); } else { @@ -196,9 +197,9 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) } else { - foreach (var item in fileSystem.DirectoryEnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories).Where(IsSupportedProjectFile)) + foreach (var item in fileSystem.Directory.EnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories).Where(IsSupportedProjectFile)) { - var assemblyInfoFile = new FileInfo(item); + var assemblyInfoFile = fileSystem.FileInfo.New(item); yield return assemblyInfoFile; } diff --git a/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs b/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs index 683ede16e3..6c6fe70625 100644 --- a/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs +++ b/src/GitVersion.Output/GitVersionInfo/GitVersionInfoGenerator.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.OutputVariables; @@ -20,12 +21,14 @@ public void Execute(GitVersionVariables variables, GitVersionInfoContext context string? originalFileContents = null; - if (File.Exists(filePath)) + if (this.fileSystem.File.Exists(filePath)) { - originalFileContents = this.fileSystem.ReadAllText(filePath); + originalFileContents = this.fileSystem.File.ReadAllText(filePath); } - var fileExtension = Path.GetExtension(filePath); + var fileExtension = PathHelper.GetExtension(filePath); + ArgumentNullException.ThrowIfNull(fileExtension); + var template = this.templateManager.GetTemplateFor(fileExtension); var addFormat = this.templateManager.GetAddFormatFor(fileExtension); var targetNamespace = getTargetNamespace(fileExtension); @@ -53,12 +56,12 @@ public void Execute(GitVersionVariables variables, GitVersionInfoContext context if (fileContents != originalFileContents) { - this.fileSystem.WriteAllText(filePath, fileContents); + this.fileSystem.File.WriteAllText(filePath, fileContents); } return; - string getTargetNamespace(string extension) => extension switch + string getTargetNamespace(string? extension) => extension switch { ".vb" => context.TargetNamespace ?? "Global", ".cs" => context.TargetNamespace != null ? $"{PathHelper.NewLine}namespace {context.TargetNamespace}" : "", diff --git a/src/GitVersion.Output/OutputGenerator/OutputGenerator.cs b/src/GitVersion.Output/OutputGenerator/OutputGenerator.cs index 24a715e95d..1da7fe356e 100644 --- a/src/GitVersion.Output/OutputGenerator/OutputGenerator.cs +++ b/src/GitVersion.Output/OutputGenerator/OutputGenerator.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Agents; using GitVersion.Extensions; using GitVersion.Helpers; @@ -38,7 +39,7 @@ public void Execute(GitVersionVariables variables, OutputContext context) var retryOperation = new RetryAction(); retryOperation.Execute(() => { - if (context.OutputFile != null) this.fileSystem.WriteAllText(context.OutputFile, json); + if (context.OutputFile != null) this.fileSystem.File.WriteAllText(context.OutputFile, json); }); } diff --git a/src/GitVersion.Output/Serializer/VersionVariableSerializer.cs b/src/GitVersion.Output/Serializer/VersionVariableSerializer.cs index b6243ea2aa..7941b971c2 100644 --- a/src/GitVersion.Output/Serializer/VersionVariableSerializer.cs +++ b/src/GitVersion.Output/Serializer/VersionVariableSerializer.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using System.Text.Encodings.Web; using GitVersion.Extensions; using GitVersion.Helpers; @@ -83,14 +84,14 @@ private static GitVersionVariables FromDictionary(IEnumerable new() { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, Converters = { new VersionVariablesJsonStringConverter() } }; diff --git a/src/GitVersion.Output/TemplateManager.cs b/src/GitVersion.Output/TemplateManager.cs index 7eb60d3d54..da90e205aa 100644 --- a/src/GitVersion.Output/TemplateManager.cs +++ b/src/GitVersion.Output/TemplateManager.cs @@ -1,4 +1,5 @@ using GitVersion.Extensions; +using GitVersion.Helpers; namespace GitVersion.Output; @@ -13,7 +14,7 @@ internal class TemplateManager(TemplateType templateType) private readonly Dictionary templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(tuple => tuple.ext, tuple => tuple.name, StringComparer.OrdinalIgnoreCase); private readonly Dictionary addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(tuple => tuple.ext, tuple => tuple.name, StringComparer.OrdinalIgnoreCase); - public string? GetTemplateFor(string fileExtension) + public string? GetTemplateFor(string? fileExtension) { ArgumentNullException.ThrowIfNull(fileExtension); @@ -27,7 +28,7 @@ internal class TemplateManager(TemplateType templateType) return result; } - public string? GetAddFormatFor(string fileExtension) + public string? GetAddFormatFor(string? fileExtension) { ArgumentNullException.ThrowIfNull(fileExtension); @@ -56,7 +57,12 @@ public bool IsSupported(string fileExtension) { if (name.Contains(templateType.ToString()) && name.Contains(templateCategory)) { - yield return (ext: Path.GetExtension(name), name); + var extension = PathHelper.GetExtension(name); + if (string.IsNullOrWhiteSpace(extension)) + { + continue; + } + yield return (ext: extension, name); } } } diff --git a/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs b/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs index 4f76e347ac..a6d1b708fc 100644 --- a/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs +++ b/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs @@ -1,3 +1,4 @@ +using System.IO.Abstractions; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; @@ -25,16 +26,16 @@ public void Execute(GitVersionVariables variables, WixVersionContext context) var root = doc.DocumentElement; doc.InsertBefore(xmlDecl, root); - if (this.fileSystem.Exists(this.wixVersionFile)) + if (this.fileSystem.File.Exists(this.wixVersionFile)) { - this.fileSystem.Delete(this.wixVersionFile); + this.fileSystem.File.Delete(this.wixVersionFile); } - if (!this.fileSystem.DirectoryExists(context.WorkingDirectory)) + if (!this.fileSystem.Directory.Exists(context.WorkingDirectory)) { - this.fileSystem.CreateDirectory(context.WorkingDirectory); + this.fileSystem.Directory.CreateDirectory(context.WorkingDirectory); } - using var fs = this.fileSystem.OpenWrite(this.wixVersionFile); + using var fs = this.fileSystem.File.OpenWrite(this.wixVersionFile); doc.Save(fs); } diff --git a/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs index 1ac92f2086..4817162321 100644 --- a/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitVersion.Testing/Fixtures/RepositoryFixtureBase.cs @@ -1,5 +1,4 @@ using GitVersion.Helpers; -using GitVersion.Testing.Internal; using LibGit2Sharp; using Shouldly; @@ -46,7 +45,7 @@ protected virtual void Dispose(bool disposing) } Repository.Dispose(); - var directoryPath = Path.GetFileName(RepositoryPath); + var directoryPath = PathHelper.GetFileName(RepositoryPath); try { diff --git a/src/GitVersion.Testing/GitVersion.Testing.csproj b/src/GitVersion.Testing/GitVersion.Testing.csproj index 48fca60324..f79daa6f8a 100644 --- a/src/GitVersion.Testing/GitVersion.Testing.csproj +++ b/src/GitVersion.Testing/GitVersion.Testing.csproj @@ -4,8 +4,18 @@ + + + + + + + + + + diff --git a/src/GitVersion.Testing/Helpers/DirectoryHelper.cs b/src/GitVersion.Testing/Helpers/DirectoryHelper.cs deleted file mode 100644 index d8137e267d..0000000000 --- a/src/GitVersion.Testing/Helpers/DirectoryHelper.cs +++ /dev/null @@ -1,79 +0,0 @@ -using GitVersion.Helpers; - -namespace GitVersion.Testing.Internal; - -internal static class DirectoryHelper -{ - private static readonly Dictionary ToRename = new() - { - { "gitted", ".git" }, - { "gitmodules", ".gitmodules" } - }; - - public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) - { - // From http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c/58779#58779 - - foreach (var dir in source.GetDirectories()) - { - CopyFilesRecursively(dir, target.CreateSubdirectory(Rename(dir.Name))); - } - - foreach (var file in source.GetFiles()) - { - file.CopyTo(PathHelper.Combine(target.FullName, Rename(file.Name))); - } - } - - private static string Rename(string name) => ToRename.GetValueOrDefault(name, name); - - public static void DeleteSubDirectories(string parentPath) - { - var dirs = Directory.GetDirectories(parentPath); - foreach (var dir in dirs) - { - DeleteDirectory(dir); - } - } - - 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}", - SysEnv.NewLine, Path.GetFullPath(directoryPath))); - } - } -}