From 2305b7cef270b6e248e6e123f3f33f130ee19fbd Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Mon, 18 Nov 2024 13:21:49 +0100 Subject: [PATCH 1/5] removed TestFileSystem and usage --- .../GitVersion.App.Tests.csproj | 2 - .../ConfigurationProviderTests.cs | 3 +- .../Configuration/Extensions.cs | 6 ++ .../Core/DynamicRepositoryTests.cs | 6 +- .../Helpers/GitVersionCoreTestModule.cs | 2 +- .../Helpers/TestFileSystem.cs | 96 ------------------- .../Helpers/TestStream.cs | 38 -------- src/GitVersion.Core/Helpers/PathHelper.cs | 7 ++ .../Caching/GitVersionCacheKeyFactory.cs | 2 +- .../GitVersion.MsBuild.Tests.csproj | 2 - .../Output/AssemblyInfoFileUpdaterTests.cs | 4 +- .../Output/WixFileTests.cs | 4 + .../WixUpdater/WixVersionFileUpdater.cs | 10 +- src/GitVersion.sln.DotSettings | 13 +-- 14 files changed, 39 insertions(+), 156 deletions(-) delete mode 100644 src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs delete mode 100644 src/GitVersion.Core.Tests/Helpers/TestStream.cs diff --git a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj index 0d2f6f3e71..111e288a9f 100644 --- a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj +++ b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj @@ -19,9 +19,7 @@ - - diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs index 9ece53a3f5..f693649640 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs @@ -285,7 +285,8 @@ public void NoWarnOnGitVersionYmlFile() this.configurationProvider.ProvideForDirectory(this.repoPath); - stringLogger.Length.ShouldBe(0); + var filePath = PathHelper.Combine(this.repoPath, ConfigurationFileLocator.DefaultFileName); + stringLogger.ShouldContain($"Found configuration file at '{filePath}'"); } [Test] diff --git a/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs b/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs index 96db0f145c..6000db6c6c 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/Extensions.cs @@ -13,6 +13,12 @@ public static IDisposable SetupConfigFile(this IFileSystem fileSystem, s } var fullPath = PathHelper.Combine(path, fileName); + var directory = PathHelper.GetDirectoryName(fullPath); + if (!fileSystem.DirectoryExists(directory)) + { + fileSystem.CreateDirectory(directory); + } + fileSystem.WriteAllText(fullPath, text); return Disposable.Create(fullPath, () => fileSystem.Delete(fullPath)); diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index 0535fc714e..ff6db85e6e 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -23,7 +23,7 @@ private static void ClearReadOnly(DirectoryInfo parentDirectory) } } - [OneTimeSetUp] + [SetUp] public void CreateTemporaryRepository() { // Note: we can't use guid because paths will be too long @@ -41,15 +41,15 @@ public void CreateTemporaryRepository() Directory.CreateDirectory(this.workDirectory); } - [OneTimeTearDown] + [TearDown] public void Cleanup() { } // Note: use same name twice to see if changing commits works on same (cached) repository [NonParallelizable] - [TestCase("GV_main", "https://github.com/GitTools/GitVersion", MainBranch, "efddf2f92c539a9c27f1904d952dcab8fb955f0e", "5.8.2-56")] [TestCase("GV_main", "https://github.com/GitTools/GitVersion", MainBranch, "2dc142a4a4df77db61a00d9fb7510b18b3c2c85a", "5.8.2-47")] + [TestCase("GV_main", "https://github.com/GitTools/GitVersion", MainBranch, "efddf2f92c539a9c27f1904d952dcab8fb955f0e", "5.8.2-56")] public void FindsVersionInDynamicRepo(string name, string url, string targetBranch, string commitId, string expectedFullSemVer) { var root = PathHelper.Combine(this.workDirectory, name); diff --git a/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs b/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs index e6410ceb26..755287a94d 100644 --- a/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs +++ b/src/GitVersion.Core.Tests/Helpers/GitVersionCoreTestModule.cs @@ -17,7 +17,7 @@ public void RegisterTypes(IServiceCollection services) services.AddModule(new GitVersionConfigurationModule()); services.AddModule(new GitVersionCoreModule()); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); } diff --git a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs deleted file mode 100644 index 06a4f74ee4..0000000000 --- a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs +++ /dev/null @@ -1,96 +0,0 @@ -using GitVersion.Helpers; - -namespace GitVersion.Core.Tests.Helpers; - -public class TestFileSystem : IFileSystem -{ - private readonly Dictionary fileSystem = new(SysEnv.OSVersion.Platform == PlatformID.Unix ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); - - public void Copy(string from, string to, bool overwrite) - { - var fromPath = Path.GetFullPath(from); - var toPath = Path.GetFullPath(to); - if (this.fileSystem.ContainsKey(toPath)) - { - if (overwrite) - this.fileSystem.Remove(toPath); - else - throw new IOException("File already exists"); - } - - if (!this.fileSystem.TryGetValue(fromPath, out var source)) - throw new FileNotFoundException($"The source file '{fromPath}' was not found", from); - - this.fileSystem.Add(toPath, source); - } - - public void Move(string from, string to) - { - var fromPath = Path.GetFullPath(from); - Copy(from, to, false); - this.fileSystem.Remove(fromPath); - } - - public bool Exists(string file) - { - var path = Path.GetFullPath(file); - return this.fileSystem.ContainsKey(path); - } - - public void Delete(string path) - { - var fullPath = Path.GetFullPath(path); - this.fileSystem.Remove(fullPath); - } - - public string ReadAllText(string path) - { - var fullPath = Path.GetFullPath(path); - if (!this.fileSystem.TryGetValue(fullPath, out var content)) - throw new FileNotFoundException($"The file '{fullPath}' was not found", fullPath); - - var encoding = EncodingHelper.DetectEncoding(content) ?? Encoding.UTF8; - return encoding.GetString(content); - } - - public void WriteAllText(string? file, string fileContents) - { - var path = Path.GetFullPath(file ?? throw new ArgumentNullException(nameof(file))); - var encoding = fileSystem.TryGetValue(path, out var value) ? EncodingHelper.DetectEncoding(value) ?? Encoding.UTF8 - : Encoding.UTF8; - WriteAllText(path, fileContents, encoding); - } - - public void WriteAllText(string? file, string fileContents, Encoding encoding) - { - var path = Path.GetFullPath(file ?? throw new ArgumentNullException(nameof(file))); - this.fileSystem[path] = encoding.GetBytes(fileContents); - } - - public IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption) => throw new NotImplementedException(); - - public Stream OpenWrite(string path) => new TestStream(path, this); - - public Stream OpenRead(string path) - { - var fullPath = Path.GetFullPath(path); - if (!this.fileSystem.TryGetValue(fullPath, out var content)) - throw new FileNotFoundException("File not found.", fullPath); - - return new MemoryStream(content); - } - - public void CreateDirectory(string path) - { - var fullPath = Path.GetFullPath(path); - this.fileSystem[fullPath] = []; - } - - public bool DirectoryExists(string path) - { - var fullPath = Path.GetFullPath(path); - return this.fileSystem.ContainsKey(fullPath); - } - - public long GetLastDirectoryWrite(string path) => 1; -} diff --git a/src/GitVersion.Core.Tests/Helpers/TestStream.cs b/src/GitVersion.Core.Tests/Helpers/TestStream.cs deleted file mode 100644 index 836a45474f..0000000000 --- a/src/GitVersion.Core.Tests/Helpers/TestStream.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace GitVersion.Core.Tests.Helpers; - -public class TestStream(string path, IFileSystem testFileSystem) : Stream -{ - private readonly MemoryStream underlying = new(); - - protected override void Dispose(bool disposing) - { - Flush(); - base.Dispose(disposing); - } - - public override void Flush() - { - this.underlying.Position = 0; - var readToEnd = new StreamReader(this.underlying).ReadToEnd(); - testFileSystem.WriteAllText(path, readToEnd); - } - - public override long Seek(long offset, SeekOrigin origin) => this.underlying.Seek(offset, origin); - - public override void SetLength(long value) => this.underlying.SetLength(value); - - public override int Read(byte[] buffer, int offset, int count) => this.underlying.Read(buffer, offset, count); - - public override void Write(byte[] buffer, int offset, int count) => this.underlying.Write(buffer, offset, count); - - public override bool CanRead => this.underlying.CanRead; - public override bool CanSeek => this.underlying.CanSeek; - public override bool CanWrite => this.underlying.CanWrite; - public override long Length => this.underlying.Length; - - public override long Position - { - get => this.underlying.Position; - set => this.underlying.Position = value; - } -} diff --git a/src/GitVersion.Core/Helpers/PathHelper.cs b/src/GitVersion.Core/Helpers/PathHelper.cs index caafb1b703..3c9d853a1d 100644 --- a/src/GitVersion.Core/Helpers/PathHelper.cs +++ b/src/GitVersion.Core/Helpers/PathHelper.cs @@ -26,6 +26,13 @@ public static string GetTempPath() public static string GetRepositoryTempPath() => Combine(GetTempPath(), "TestRepositories", Guid.NewGuid().ToString()); + public static string GetDirectoryName(string? path) + { + ArgumentNullException.ThrowIfNull(path, nameof(path)); + + return Path.GetDirectoryName(path)!; + } + public static string GetFullPath(string? path) { ArgumentNullException.ThrowIfNull(path, nameof(path)); diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs index f2cd6919a1..c24047a798 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs @@ -118,7 +118,7 @@ private List CalculateDirectoryContents(string root) { var fi = new FileInfo(file); result.Add(fi.Name); - result.Add(File.ReadAllText(file)); + result.Add(this.fileSystem.ReadAllText(file)); } catch (IOException e) { diff --git a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj index b7677e977d..428b5be4a2 100644 --- a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj +++ b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj @@ -31,9 +31,7 @@ - - diff --git a/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs b/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs index 8ce95285be..557d7d1abd 100644 --- a/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs +++ b/src/GitVersion.Output.Tests/Output/AssemblyInfoFileUpdaterTests.cs @@ -19,7 +19,7 @@ public class AssemblyInfoFileUpdaterTests : TestBase private string workingDir; [OneTimeSetUp] - public void OneTimeSetUp() => workingDir = PathHelper.Combine(PathHelper.GetTempPath(), "AssemblyInfoFileUpdaterTests"); + public void OneTimeSetUp() => workingDir = PathHelper.Combine(PathHelper.GetTempPath(), nameof(AssemblyInfoFileUpdaterTests)); [OneTimeTearDown] public void OneTimeTearDown() => DirectoryHelper.DeleteDirectory(workingDir); @@ -93,7 +93,7 @@ public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInf [TestCase("vb")] public void ShouldNotCreateAssemblyInfoFileWhenNotExistsAndNotEnsureAssemblyInfo(string fileExtension) { - var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension; + var assemblyInfoFile = "NoVersionAssemblyInfo." + fileExtension; var fullPath = PathHelper.Combine(workingDir, assemblyInfoFile); var variables = this.variableProvider.GetVariablesFor( SemanticVersion.Parse("1.0.0", RegexPatterns.Configuration.DefaultTagPrefixPattern), EmptyConfigurationBuilder.New.Build(), 0 diff --git a/src/GitVersion.Output.Tests/Output/WixFileTests.cs b/src/GitVersion.Output.Tests/Output/WixFileTests.cs index 4d41fec15b..ebd91284f2 100644 --- a/src/GitVersion.Output.Tests/Output/WixFileTests.cs +++ b/src/GitVersion.Output.Tests/Output/WixFileTests.cs @@ -95,6 +95,10 @@ public void UpdateWixVersionFileWhenFileAlreadyExists() // fake an already existing file var file = PathHelper.Combine(workingDir, WixVersionFileUpdater.WixVersionFileName); + if (!fileSystem.DirectoryExists(workingDir)) + { + fileSystem.CreateDirectory(workingDir); + } fileSystem.WriteAllText(file, new('x', 1024 * 1024)); wixVersionFileUpdater.Execute(versionVariables, new(workingDir)); diff --git a/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs b/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs index 3d2dfe0104..4f76e347ac 100644 --- a/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs +++ b/src/GitVersion.Output/WixUpdater/WixVersionFileUpdater.cs @@ -25,7 +25,15 @@ public void Execute(GitVersionVariables variables, WixVersionContext context) var root = doc.DocumentElement; doc.InsertBefore(xmlDecl, root); - this.fileSystem.Delete(this.wixVersionFile); + if (this.fileSystem.Exists(this.wixVersionFile)) + { + this.fileSystem.Delete(this.wixVersionFile); + } + + if (!this.fileSystem.DirectoryExists(context.WorkingDirectory)) + { + this.fileSystem.CreateDirectory(context.WorkingDirectory); + } using var fs = this.fileSystem.OpenWrite(this.wixVersionFile); doc.Save(fs); } diff --git a/src/GitVersion.sln.DotSettings b/src/GitVersion.sln.DotSettings index 9d9eae6664..970fd59ec8 100644 --- a/src/GitVersion.sln.DotSettings +++ b/src/GitVersion.sln.DotSettings @@ -707,16 +707,11 @@ II.2.12 <HandlesEvent /> True True True - - - True + True False - - - - - <data /> + <data /> <data><IncludeFilters /><ExcludeFilters /></data> True True - True + True + True From 62f782fa39603f0a32c304889eaa6b0df19cc1ca Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Wed, 27 Nov 2024 05:28:23 +0100 Subject: [PATCH 2/5] Fix repo setup logic in DynamicRepositoryTests code cleanup --- .../Core/DynamicRepositoryTests.cs | 31 ++++--------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index ff6db85e6e..3a97ddbe3b 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -10,39 +10,20 @@ public class DynamicRepositoryTests : TestBase { private string? workDirectory; - private static void ClearReadOnly(DirectoryInfo parentDirectory) - { - parentDirectory.Attributes = FileAttributes.Normal; - foreach (var fi in parentDirectory.GetFiles()) - { - fi.Attributes = FileAttributes.Normal; - } - foreach (var di in parentDirectory.GetDirectories()) - { - ClearReadOnly(di); - } - } - [SetUp] - public void CreateTemporaryRepository() + public void SetUp() { - // Note: we can't use guid because paths will be too long + // // Note: we can't use guid because paths will be too long this.workDirectory = PathHelper.Combine(Path.GetTempPath(), "GV"); - // Clean directory upfront, some build agents are having troubles - if (Directory.Exists(this.workDirectory)) + if (!Directory.Exists(this.workDirectory)) { - var di = new DirectoryInfo(this.workDirectory); - ClearReadOnly(di); - - Directory.Delete(this.workDirectory, true); + Directory.CreateDirectory(this.workDirectory); } - - Directory.CreateDirectory(this.workDirectory); } [TearDown] - public void Cleanup() + public void TearDown() { } @@ -64,7 +45,7 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran TargetBranch = targetBranch, CommitId = commitId }, - Settings = { NoFetch = false }, + Settings = { NoFetch = false, NoCache = true }, WorkingDirectory = workingDirectory }; var options = Options.Create(gitVersionOptions); From 5147e957b93a1a1dfce8c45a7f4a9bfd28d19854 Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Wed, 27 Nov 2024 08:52:30 +0100 Subject: [PATCH 3/5] Refactor file system operations to use IFileSystem interface Replaced direct file and directory operations with IFileSystem methods. This change standardizes file system interactions and simplifies dependency injection across the codebase. --- .../ArgumentParserTests.cs | 7 +++-- src/GitVersion.App/ArgumentParser.cs | 15 ++++++--- src/GitVersion.App/GitVersionExecutor.cs | 4 ++- .../ConfigurationProvider.cs | 2 +- .../Core/DynamicRepositoryTests.cs | 18 +++-------- .../Core/GitVersionExecutorTests.cs | 12 +++++-- .../Core/Abstractions/IFileSystem.cs | 4 ++- src/GitVersion.Core/Core/FileSystem.cs | 18 ++++++----- src/GitVersion.Core/Core/GitPreparer.cs | 4 ++- .../Extensions/ConfigurationExtensions.cs | 8 ++--- src/GitVersion.Core/PublicAPI.Unshipped.txt | 2 ++ .../Caching/GitVersionCacheKeyFactory.cs | 6 ++-- .../GitVersionTaskExecutor.cs | 24 +++++++++++++- src/GitVersion.MsBuild/Helpers/FileHelper.cs | 31 +++---------------- .../Output/GitVersionInfoGeneratorTests.cs | 30 +++++++++--------- 15 files changed, 102 insertions(+), 83 deletions(-) diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index b8650499c8..6569742bb3 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -12,6 +12,7 @@ public class ArgumentParserTests : TestBase { private IEnvironment environment; private IArgumentParser argumentParser; + private IFileSystem fileSystem; [SetUp] public void SetUp() @@ -23,6 +24,7 @@ public void SetUp() }); this.environment = sp.GetRequiredService(); this.argumentParser = sp.GetRequiredService(); + this.fileSystem = sp.GetRequiredService(); } [Test] @@ -337,7 +339,8 @@ public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() using var file2 = File.Create(assemblyFile2); var subdir = PathHelper.Combine(repo.RepositoryPath, "subdir"); - Directory.CreateDirectory(subdir); + + this.fileSystem.CreateDirectory(subdir); var assemblyFile3 = PathHelper.Combine(subdir, "LocalAssemblyInfo.cs"); using var file3 = File.Create(assemblyFile3); @@ -358,7 +361,7 @@ public void UpdateAssemblyInfoWithRelativeFilename() using var file = File.Create(assemblyFile); var targetPath = PathHelper.Combine(repo.RepositoryPath, "subdir1", "subdir2"); - Directory.CreateDirectory(targetPath); + this.fileSystem.CreateDirectory(targetPath); var arguments = this.argumentParser.ParseArguments($"-targetpath {targetPath} -updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index dc16d9d7ca..11f4a4ac37 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -6,10 +6,15 @@ namespace GitVersion; -internal class ArgumentParser(IEnvironment environment, ICurrentBuildAgent buildAgent, IConsole console, IGlobbingResolver globbingResolver) +internal class ArgumentParser(IEnvironment environment, + IFileSystem fileSystem, + ICurrentBuildAgent buildAgent, + IConsole console, + IGlobbingResolver globbingResolver) : IArgumentParser { private readonly IEnvironment environment = environment.NotNull(); + private readonly IFileSystem fileSystem = fileSystem.NotNull(); private readonly ICurrentBuildAgent buildAgent = buildAgent.NotNull(); private readonly IConsole console = console.NotNull(); private readonly IGlobbingResolver globbingResolver = globbingResolver.NotNull(); @@ -97,19 +102,19 @@ public Arguments ParseArguments(string[] commandLineArguments) return arguments; } - private static void ValidateConfigurationFile(Arguments arguments) + private void ValidateConfigurationFile(Arguments arguments) { if (arguments.ConfigurationFile.IsNullOrWhiteSpace()) return; if (Path.IsPathRooted(arguments.ConfigurationFile)) { - if (!File.Exists(arguments.ConfigurationFile)) throw new WarningException($"Could not find config file at '{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); } else { var configFilePath = Path.GetFullPath(PathHelper.Combine(arguments.TargetPath, arguments.ConfigurationFile)); - if (!File.Exists(configFilePath)) throw new WarningException($"Could not find config file at '{configFilePath}'"); + if (!this.fileSystem.Exists(configFilePath)) throw new WarningException($"Could not find config file at '{configFilePath}'"); arguments.ConfigurationFile = configFilePath; } } @@ -161,7 +166,7 @@ private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList this.log.Info(logMessage)); } - if (!Directory.Exists(workingDirectory)) + if (!this.fileSystem.DirectoryExists(workingDirectory)) { this.log.Warning($"The working directory '{workingDirectory}' does not exist."); } diff --git a/src/GitVersion.Configuration/ConfigurationProvider.cs b/src/GitVersion.Configuration/ConfigurationProvider.cs index daf2fc1a28..cf1a89a74f 100644 --- a/src/GitVersion.Configuration/ConfigurationProvider.cs +++ b/src/GitVersion.Configuration/ConfigurationProvider.cs @@ -21,7 +21,7 @@ public IGitVersionConfiguration Provide(IReadOnlyDictionary? ov { var gitVersionOptions = this.options.Value; var workingDirectory = gitVersionOptions.WorkingDirectory; - var projectRootDirectory = workingDirectory.FindGitDir()?.WorkingTreeDirectory; + var projectRootDirectory = this.fileSystem.FindGitDir(workingDirectory)?.WorkingTreeDirectory; var configurationFile = this.configFileLocator.GetConfigurationFile(workingDirectory) ?? this.configFileLocator.GetConfigurationFile(projectRootDirectory); diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index 3a97ddbe3b..9fe51feda9 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -11,16 +11,7 @@ public class DynamicRepositoryTests : TestBase private string? workDirectory; [SetUp] - public void SetUp() - { - // // Note: we can't use guid because paths will be too long - this.workDirectory = PathHelper.Combine(Path.GetTempPath(), "GV"); - - if (!Directory.Exists(this.workDirectory)) - { - Directory.CreateDirectory(this.workDirectory); - } - } + public void SetUp() => this.workDirectory = PathHelper.Combine(Path.GetTempPath(), "GV"); [TearDown] public void TearDown() @@ -50,9 +41,6 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran }; var options = Options.Create(gitVersionOptions); - Directory.CreateDirectory(dynamicDirectory); - Directory.CreateDirectory(workingDirectory); - var sp = ConfigureServices(services => services.AddSingleton(options)); sp.DiscoverRepository(); @@ -60,6 +48,10 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran var gitPreparer = sp.GetRequiredService(); gitPreparer.Prepare(); + var fileSystem = sp.GetRequiredService(); + fileSystem.CreateDirectory(dynamicDirectory); + fileSystem.CreateDirectory(workingDirectory); + var gitVersionCalculator = sp.GetRequiredService(); var versionVariables = gitVersionCalculator.CalculateVersionVariables(); diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index ebd81f0957..2fea817d8f 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -67,7 +67,7 @@ public void CacheKeyForWorktree() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); - var worktreePath = PathHelper.Combine(Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); + var worktreePath = GetWorktreePath(fixture); try { // create a branch and a new worktree for it @@ -395,7 +395,7 @@ public void GetProjectRootDirectoryWorkingDirectoryWithWorktree() using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); - var worktreePath = PathHelper.Combine(Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); + var worktreePath = GetWorktreePath(fixture); try { // create a branch and a new worktree for it @@ -451,7 +451,7 @@ public void GetDotGitDirectoryWorktree() using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); - var worktreePath = PathHelper.Combine(Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); + var worktreePath = GetWorktreePath(fixture); try { // create a branch and a new worktree for it @@ -588,6 +588,12 @@ 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) + { + var worktreePath = PathHelper.Combine(Directory.GetParent(fixture.RepositoryPath)?.FullName, Guid.NewGuid().ToString()); + return worktreePath; + } + private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVersionOptions, ILog? logger = null, IGitRepository? repository = null, IFileSystem? fs = null) { this.sp = GetServiceProvider(gitVersionOptions, logger, repository, fs); diff --git a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs index 32e4646809..eadb410d9a 100644 --- a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs +++ b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs @@ -9,10 +9,12 @@ public interface IFileSystem string ReadAllText(string path); void WriteAllText(string? file, string fileContents); void WriteAllText(string? file, string fileContents, Encoding encoding); - IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption); 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); } diff --git a/src/GitVersion.Core/Core/FileSystem.cs b/src/GitVersion.Core/Core/FileSystem.cs index 50bd61f3a2..7da239b288 100644 --- a/src/GitVersion.Core/Core/FileSystem.cs +++ b/src/GitVersion.Core/Core/FileSystem.cs @@ -29,13 +29,6 @@ public void WriteAllText(string? file, string fileContents, Encoding encoding) File.WriteAllText(file, fileContents, encoding); } - public IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption) - { - ArgumentException.ThrowIfNullOrWhiteSpace(directory); - - return Directory.EnumerateFiles(directory, searchPattern, searchOption); - } - public Stream OpenWrite(string path) => File.OpenWrite(path); public Stream OpenRead(string path) => File.OpenRead(path); @@ -44,6 +37,17 @@ public IEnumerable DirectoryEnumerateFiles(string? directory, string sea 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 GetLastDirectoryWrite(string path) => new DirectoryInfo(path) .GetDirectories("*.*", SearchOption.AllDirectories) .Select(d => d.LastWriteTimeUtc) diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index e33d236d4d..e48aa1f8cc 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -10,6 +10,7 @@ namespace GitVersion; internal class GitPreparer( ILog log, + IFileSystem fileSystem, IEnvironment environment, ICurrentBuildAgent buildAgent, IOptions options, @@ -19,6 +20,7 @@ internal class GitPreparer( : IGitPreparer { private readonly ILog log = log.NotNull(); + private readonly IFileSystem fileSystem = fileSystem.NotNull(); private readonly IEnvironment environment = environment.NotNull(); private readonly IMutatingGitRepository repository = repository.NotNull(); private readonly IOptions options = options.NotNull(); @@ -112,7 +114,7 @@ private void CreateDynamicRepository(string? targetBranch) { var gitVersionOptions = this.options.Value; var authentication = gitVersionOptions.AuthenticationInfo; - if (!Directory.Exists(gitDirectory)) + if (!this.fileSystem.DirectoryExists(gitDirectory)) { CloneRepository(gitVersionOptions.RepositoryInfo.TargetUrl, gitDirectory, authentication); } diff --git a/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs b/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs index caa4032bdd..b10b2b9ae8 100644 --- a/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs +++ b/src/GitVersion.Core/Extensions/ConfigurationExtensions.cs @@ -123,24 +123,24 @@ public static bool IsReleaseBranch(this IGitVersionConfiguration configuration, return label; } - public static (string GitDirectory, string WorkingTreeDirectory)? FindGitDir(this 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 (Directory.Exists(dirOrFilePath)) + if (fileSystem.DirectoryExists(dirOrFilePath)) { return (dirOrFilePath, Path.GetDirectoryName(dirOrFilePath)!); } - if (File.Exists(dirOrFilePath)) + if (fileSystem.Exists(dirOrFilePath)) { string? relativeGitDirPath = ReadGitDirFromFile(dirOrFilePath); if (!string.IsNullOrWhiteSpace(relativeGitDirPath)) { var fullGitDirPath = Path.GetFullPath(PathHelper.Combine(startingDir, relativeGitDirPath)); - if (Directory.Exists(fullGitDirPath)) + if (fileSystem.DirectoryExists(fullGitDirPath)) { return (fullGitDirPath, Path.GetDirectoryName(dirOrFilePath)!); } diff --git a/src/GitVersion.Core/PublicAPI.Unshipped.txt b/src/GitVersion.Core/PublicAPI.Unshipped.txt index 7dc5c58110..d86fbfefd4 100644 --- a/src/GitVersion.Core/PublicAPI.Unshipped.txt +++ b/src/GitVersion.Core/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +GitVersion.IFileSystem.GetDirectories(string! path) -> string![]! +GitVersion.IFileSystem.GetFiles(string! path) -> string![]! diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs index c24047a798..70609d9250 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs @@ -57,7 +57,7 @@ private List CalculateDirectoryContents(string root) // examined for files. var dirs = new Stack(); - if (!Directory.Exists(root)) + if (!this.fileSystem.DirectoryExists(root)) { throw new DirectoryNotFoundException($"Root directory does not exist: {root}"); } @@ -74,7 +74,7 @@ private List CalculateDirectoryContents(string root) string[] subDirs; try { - subDirs = Directory.GetDirectories(currentDir); + subDirs = this.fileSystem.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 +99,7 @@ private List CalculateDirectoryContents(string root) string[] files; try { - files = Directory.GetFiles(currentDir); + files = this.fileSystem.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { diff --git a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs index 9252d5a6b5..ccff9b9549 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs @@ -34,7 +34,7 @@ public void GetVersion(GetVersion task) public void UpdateAssemblyInfo(UpdateAssemblyInfo task) { var versionVariables = GitVersionVariables(task); - FileHelper.DeleteTempFiles(); + DeleteTempFiles(); FileHelper.CheckForInvalidFiles(task.CompileFiles, task.ProjectFile); if (!string.IsNullOrEmpty(task.IntermediateOutputPath)) @@ -100,5 +100,27 @@ public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) gitVersionOutputTool.OutputVariables(versionVariables, configuration.UpdateBuildNumber); } + private void DeleteTempFiles() + { + if (!this.fileSystem.DirectoryExists(FileHelper.TempPath)) + { + return; + } + + foreach (var file in this.fileSystem.GetFiles(FileHelper.TempPath)) + { + if (File.GetLastWriteTime(file) >= DateTime.Now.AddDays(-1)) + continue; + try + { + File.Delete(file); + } + catch (UnauthorizedAccessException) + { + //ignore contention + } + } + } + private GitVersionVariables GitVersionVariables(GitVersionTaskBase task) => serializer.FromFile(task.VersionFile); } diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/FileHelper.cs index e8b478ee42..e8a4479af6 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/FileHelper.cs @@ -1,8 +1,9 @@ using System.Text.RegularExpressions; -using GitVersion.Core; using GitVersion.Helpers; using Microsoft.Build.Framework; +using static GitVersion.Core.RegexPatterns.AssemblyVersion; + namespace GitVersion.MsBuild; internal static class FileHelper @@ -16,28 +17,6 @@ private static string MakeAndGetTempPath() return tempPath; } - public static void DeleteTempFiles() - { - if (!Directory.Exists(TempPath)) - { - return; - } - - foreach (var file in Directory.GetFiles(TempPath)) - { - if (File.GetLastWriteTime(file) >= DateTime.Now.AddDays(-1)) - continue; - try - { - File.Delete(file); - } - catch (UnauthorizedAccessException) - { - //ignore contention - } - } - } - public static string GetFileExtension(string language) => language switch { "C#" => "cs", @@ -69,9 +48,9 @@ private static bool FileContainsVersionAttribute(string compileFile, string proj var (attributeRegex, triviaRegex) = compileFileExtension switch { - ".cs" => (RegexPatterns.AssemblyVersion.CSharp.AttributeRegex, RegexPatterns.AssemblyVersion.CSharp.TriviaRegex), - ".fs" => (RegexPatterns.AssemblyVersion.FSharp.AttributeRegex, RegexPatterns.AssemblyVersion.FSharp.TriviaRegex), - ".vb" => (RegexPatterns.AssemblyVersion.VisualBasic.AttributeRegex, RegexPatterns.AssemblyVersion.VisualBasic.TriviaRegex), + ".cs" => (CSharp.AttributeRegex, CSharp.TriviaRegex), + ".fs" => (FSharp.AttributeRegex, FSharp.TriviaRegex), + ".vb" => (VisualBasic.AttributeRegex, VisualBasic.TriviaRegex), _ => 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) }; diff --git a/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs b/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs index 56ac52df1b..284f3d6b65 100644 --- a/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs +++ b/src/GitVersion.Output.Tests/Output/GitVersionInfoGeneratorTests.cs @@ -19,12 +19,6 @@ public class GitVersionInfoGeneratorTests : TestBase [TestCase("vb")] public void ShouldCreateFile(string fileExtension) { - var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); - if (!Directory.Exists(directory)) - Directory.CreateDirectory(directory); - var fileName = "GitVersionInformation.g." + fileExtension; - var fullPath = PathHelper.Combine(directory, fileName); - var semanticVersion = new SemanticVersion { Major = 1, @@ -32,14 +26,20 @@ public void ShouldCreateFile(string fileExtension) Patch = 3, PreReleaseTag = "unstable4", BuildMetaData = new("versionSourceSha", 5, - "feature1", "commitSha", "commitShortSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z"), 0) + "feature1", "commitSha", "commitShortSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z"), 0) }; var sp = ConfigureServices(); var fileSystem = sp.GetRequiredService(); - var variableProvider = sp.GetRequiredService(); + var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); + if (!fileSystem.DirectoryExists(directory)) + fileSystem.CreateDirectory(directory); + var fileName = "GitVersionInformation.g." + fileExtension; + var fullPath = PathHelper.Combine(directory, fileName); + + var variableProvider = sp.GetRequiredService(); var variables = variableProvider.GetVariablesFor(semanticVersion, EmptyConfigurationBuilder.New.Build(), 0); using var generator = sp.GetRequiredService(); @@ -60,12 +60,6 @@ public void ShouldProperlyOutputNamespaceDeclaration(string fileExtension) { const string targetNamespace = "My.Custom.Namespace"; - var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); - if (!Directory.Exists(directory)) - Directory.CreateDirectory(directory); - var fileName = "GitVersionInformation.g." + fileExtension; - var fullPath = PathHelper.Combine(directory, fileName); - var semanticVersion = new SemanticVersion { Major = 1, @@ -79,8 +73,14 @@ public void ShouldProperlyOutputNamespaceDeclaration(string fileExtension) var sp = ConfigureServices(); var fileSystem = sp.GetRequiredService(); - var variableProvider = sp.GetRequiredService(); + var directory = PathHelper.Combine(PathHelper.GetTempPath(), "GitVersionInfoGeneratorTests", Guid.NewGuid().ToString()); + if (!fileSystem.DirectoryExists(directory)) + fileSystem.CreateDirectory(directory); + var fileName = "GitVersionInformation.g." + fileExtension; + var fullPath = PathHelper.Combine(directory, fileName); + + var variableProvider = sp.GetRequiredService(); var variables = variableProvider.GetVariablesFor(semanticVersion, EmptyConfigurationBuilder.New.Build(), 0); using var generator = sp.GetRequiredService(); From 012c377970db3d9fc144b36e04c8ce3828564dc9 Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Wed, 27 Nov 2024 17:15:31 +0100 Subject: [PATCH 4/5] Refactor MakeAndGetTempPath to use expression-bodied member Simplified the MakeAndGetTempPath method by converting it to an expression-bodied member. --- .../Core/Abstractions/IFileSystem.cs | 1 + src/GitVersion.Core/Core/FileSystem.cs | 2 ++ src/GitVersion.Core/PublicAPI.Unshipped.txt | 1 + .../Caching/GitVersionCacheKeyFactory.cs | 4 ++-- .../GitVersionTaskExecutor.cs | 17 +++++++++++++---- src/GitVersion.MsBuild/Helpers/FileHelper.cs | 7 +------ 6 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs index eadb410d9a..7678d8c373 100644 --- a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs +++ b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs @@ -17,4 +17,5 @@ public interface IFileSystem 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 index 7da239b288..1187b06528 100644 --- a/src/GitVersion.Core/Core/FileSystem.cs +++ b/src/GitVersion.Core/Core/FileSystem.cs @@ -48,6 +48,8 @@ public IEnumerable DirectoryEnumerateFiles(string? directory, string sea 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) diff --git a/src/GitVersion.Core/PublicAPI.Unshipped.txt b/src/GitVersion.Core/PublicAPI.Unshipped.txt index d86fbfefd4..b5c8a9949f 100644 --- a/src/GitVersion.Core/PublicAPI.Unshipped.txt +++ b/src/GitVersion.Core/PublicAPI.Unshipped.txt @@ -1,3 +1,4 @@ #nullable enable GitVersion.IFileSystem.GetDirectories(string! path) -> string![]! GitVersion.IFileSystem.GetFiles(string! path) -> string![]! +GitVersion.IFileSystem.GetLastWriteTime(string! path) -> long diff --git a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs index 70609d9250..c91350e733 100644 --- a/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Caching/GitVersionCacheKeyFactory.cs @@ -116,8 +116,8 @@ private List CalculateDirectoryContents(string root) { try { - var fi = new FileInfo(file); - result.Add(fi.Name); + if (!this.fileSystem.Exists(file)) continue; + result.Add(Path.GetFileName(file)); result.Add(this.fileSystem.ReadAllText(file)); } catch (IOException e) diff --git a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs index ccff9b9549..d51d364d95 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs @@ -46,6 +46,10 @@ public void UpdateAssemblyInfo(UpdateAssemblyInfo task) var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "AssemblyInfo"); task.AssemblyInfoTempFilePath = PathHelper.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); + if (!this.fileSystem.DirectoryExists(fileWriteInfo.WorkingDirectory)) + { + this.fileSystem.CreateDirectory(fileWriteInfo.WorkingDirectory); + } var gitVersionOptions = this.options.Value; gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory; gitVersionOptions.AssemblySettingsInfo.UpdateAssemblyInfo = true; @@ -68,6 +72,10 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "GitVersionInformation"); task.GitVersionInformationFilePath = PathHelper.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); + if (!this.fileSystem.DirectoryExists(fileWriteInfo.WorkingDirectory)) + { + this.fileSystem.CreateDirectory(fileWriteInfo.WorkingDirectory); + } var gitVersionOptions = this.options.Value; gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory; var targetNamespace = GetTargetNamespace(task); @@ -102,18 +110,19 @@ public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) private void DeleteTempFiles() { - if (!this.fileSystem.DirectoryExists(FileHelper.TempPath)) + var tempPath = FileHelper.TempPath; + if (!this.fileSystem.DirectoryExists(tempPath)) { return; } - foreach (var file in this.fileSystem.GetFiles(FileHelper.TempPath)) + foreach (var file in this.fileSystem.GetFiles(tempPath)) { - if (File.GetLastWriteTime(file) >= DateTime.Now.AddDays(-1)) + if (this.fileSystem.GetLastWriteTime(file) >= DateTime.Now.AddDays(-1).Ticks) continue; try { - File.Delete(file); + this.fileSystem.Delete(file); } catch (UnauthorizedAccessException) { diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/FileHelper.cs index e8a4479af6..ce3d1e9da7 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/FileHelper.cs @@ -10,12 +10,7 @@ internal static class FileHelper { public static readonly string TempPath = MakeAndGetTempPath(); - private static string MakeAndGetTempPath() - { - var tempPath = PathHelper.Combine(Path.GetTempPath(), "GitVersionTask"); - Directory.CreateDirectory(tempPath); - return tempPath; - } + private static string MakeAndGetTempPath() => PathHelper.Combine(Path.GetTempPath(), "GitVersionTask"); public static string GetFileExtension(string language) => language switch { From e2734f820549da51eba84def3d2c420a12bca9e0 Mon Sep 17 00:00:00 2001 From: Artur Stolear Date: Mon, 9 Dec 2024 13:39:10 +0100 Subject: [PATCH 5/5] fixing some warnings --- src/GitVersion.App/ArgumentParser.cs | 2 +- src/GitVersion.Core/Core/GitPreparer.cs | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index 11f4a4ac37..7e273f99da 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -166,7 +166,7 @@ private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList