Skip to content

Improve IFileSystem usage in the app (part 1) #4340

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/GitVersion.App.Tests/ArgumentParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class ArgumentParserTests : TestBase
{
private IEnvironment environment;
private IArgumentParser argumentParser;
private IFileSystem fileSystem;

[SetUp]
public void SetUp()
Expand All @@ -23,6 +24,7 @@ public void SetUp()
});
this.environment = sp.GetRequiredService<IEnvironment>();
this.argumentParser = sp.GetRequiredService<IArgumentParser>();
this.fileSystem = sp.GetRequiredService<IFileSystem>();
}

[Test]
Expand Down Expand Up @@ -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);

Expand All @@ -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);
Expand Down
2 changes: 0 additions & 2 deletions src/GitVersion.App.Tests/GitVersion.App.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
<Compile Include="..\GitVersion.Core.Tests\Helpers\ExecutableHelper.cs" Link="Helpers\ExecutableHelper.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\TestConsoleAdapter.cs" Link="Helpers\TestConsoleAdapter.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\TestEnvironment.cs" Link="Helpers\TestEnvironment.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\TestFileSystem.cs" Link="Helpers\TestFileSystem.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\TestLogAppender.cs" Link="Helpers\TestLogAppender.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\TestStream.cs" Link="Helpers\TestStream.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\TestBase.cs" Link="Helpers\TestBase.cs" />
<Compile Include="..\GitVersion.Core.Tests\Helpers\GitVersionCoreTestModule.cs" Link="Helpers\GitVersionCoreTestModule.cs" />
<Compile Include="..\GitVersion.Core.Tests\Extensions\GitVersionVariablesExtensions.cs" Link="Extensions\GitVersionVariablesExtensions.cs" />
Expand Down
15 changes: 10 additions & 5 deletions src/GitVersion.App/ArgumentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -161,7 +166,7 @@ private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList<st
{
EnsureArgumentValueCount(values);
arguments.TargetPath = value;
if (!Directory.Exists(value))
if (string.IsNullOrWhiteSpace(value) || !this.fileSystem.DirectoryExists(value))
{
this.console.WriteLine($"The working directory '{value}' does not exist.");
}
Expand Down
4 changes: 3 additions & 1 deletion src/GitVersion.App/GitVersionExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace GitVersion;

internal class GitVersionExecutor(
ILog log,
IFileSystem fileSystem,
IConsole console,
IVersionWriter versionWriter,
IHelpWriter helpWriter,
Expand All @@ -21,6 +22,7 @@ internal class GitVersionExecutor(
: IGitVersionExecutor
{
private readonly ILog log = log.NotNull();
private readonly IFileSystem fileSystem = fileSystem.NotNull();
private readonly IConsole console = console.NotNull();
private readonly IVersionWriter versionWriter = versionWriter.NotNull();
private readonly IHelpWriter helpWriter = helpWriter.NotNull();
Expand Down Expand Up @@ -131,7 +133,7 @@ private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int e
GitExtensions.DumpGraphLog(logMessage => this.log.Info(logMessage));
}

if (!Directory.Exists(workingDirectory))
if (!this.fileSystem.DirectoryExists(workingDirectory))
{
this.log.Warning($"The working directory '{workingDirectory}' does not exist.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ public static IDisposable<string> 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));
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.Configuration/ConfigurationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public IGitVersionConfiguration Provide(IReadOnlyDictionary<object, object?>? 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);
Expand Down
47 changes: 10 additions & 37 deletions src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,46 +10,18 @@ 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 SetUp() => this.workDirectory = PathHelper.Combine(Path.GetTempPath(), "GV");

[OneTimeSetUp]
public void CreateTemporaryRepository()
{
// 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))
{
var di = new DirectoryInfo(this.workDirectory);
ClearReadOnly(di);

Directory.Delete(this.workDirectory, true);
}

Directory.CreateDirectory(this.workDirectory);
}

[OneTimeTearDown]
public void Cleanup()
[TearDown]
public void TearDown()
{
}

// 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);
Expand All @@ -64,21 +36,22 @@ 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);

Directory.CreateDirectory(dynamicDirectory);
Directory.CreateDirectory(workingDirectory);

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

sp.DiscoverRepository();

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

var fileSystem = sp.GetRequiredService<IFileSystem>();
fileSystem.CreateDirectory(dynamicDirectory);
fileSystem.CreateDirectory(workingDirectory);

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

var versionVariables = gitVersionCalculator.CalculateVersionVariables();
Expand Down
12 changes: 9 additions & 3 deletions src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void RegisterTypes(IServiceCollection services)
services.AddModule(new GitVersionConfigurationModule());
services.AddModule(new GitVersionCoreModule());

services.AddSingleton<IFileSystem, TestFileSystem>();
services.AddSingleton<IFileSystem, FileSystem>();
services.AddSingleton<IEnvironment, TestEnvironment>();
services.AddSingleton<ILog, NullLog>();
}
Expand Down
96 changes: 0 additions & 96 deletions src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs

This file was deleted.

Loading
Loading