Skip to content

Commit

Permalink
Add git check to preflight checks
Browse files Browse the repository at this point in the history
Replace libgit2sharp with just running git commands using process
  • Loading branch information
juliangiebel committed Sep 15, 2023
1 parent e2e6369 commit be062b0
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 50 deletions.
5 changes: 3 additions & 2 deletions SS14.MapServer/BuildRunners/LocalBuildService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public async Task Build(string directory, CancellationToken cancellationToken =
_log.Information("Build finished");
}

public async Task Run(string directory, string command, List<string> arguments, bool joinExecutablePath = false, CancellationToken cancellationToken = default)
public async Task<string> Run(string directory, string command, List<string> arguments, bool joinExecutablePath = false, CancellationToken cancellationToken = default)
{
var executablePath = joinExecutablePath ? Path.Join(directory, command) : command;

Expand Down Expand Up @@ -114,6 +114,7 @@ public async Task Run(string directory, string command, List<string> arguments,
}

_log.Information("Run finished");
return log;
}

private void SetUpProcess(Process process, string? executable = "dotnet")
Expand Down Expand Up @@ -147,6 +148,6 @@ private void ProcessLocalBuildException(string log, string fileName, Exception e
});
}

[GeneratedRegex("error?|exception")]
[GeneratedRegex("error?|exception|fatal")]
private static partial Regex LogErrorRegex();
}
1 change: 0 additions & 1 deletion SS14.MapServer/SS14.MapServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
<PackageReference Include="Docker.DotNet" Version="3.125.15" />
<PackageReference Include="JetBrains.Annotations" Version="2023.2.0" />
<PackageReference Include="JsonModelBinder" Version="2.1.1" />
<PackageReference Include="LibGit2Sharp" Version="0.27.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
Expand Down
87 changes: 42 additions & 45 deletions SS14.MapServer/Services/GitService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using LibGit2Sharp;
using LibGit2Sharp.Handlers;
using System.Diagnostics;
using Serilog;
using SS14.MapServer.BuildRunners;
using SS14.MapServer.Configuration;
Expand All @@ -9,6 +8,8 @@ namespace SS14.MapServer.Services;

public sealed class GitService
{
private const string GitCommand = "git";

private readonly LocalBuildService _buildService;

private readonly GitConfiguration _configuration = new();
Expand All @@ -22,12 +23,28 @@ public GitService(IConfiguration configuration, LocalBuildService buildService)
}

/// <summary>
///
/// Gets the git version. Used for determining it git is installed
/// </summary>
public async Task<string> GetGitVersion(CancellationToken cancellationToken = default)
{
using var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = GitCommand;
process.StartInfo.Arguments = "--version";
process.Start();
await process.WaitForExitAsync(cancellationToken);
return await process.StandardOutput.ReadToEndAsync(cancellationToken);
}

/// <summary>
/// Clones the repo if it hasn't been cloned yet and pulls the provided git ref or the current branch
/// </summary>
/// <param name="workingDirectory"></param>
/// <param name="gitRef">[Optional] The Ref to pull</param>
/// <param name="repoUrl"></param>
/// <returns></returns>
/// <returns>The directory the repository is in</returns>
public string Sync(string workingDirectory, string? gitRef = null, string? repoUrl = null)
{
gitRef ??= _configuration.Branch;
Expand Down Expand Up @@ -55,8 +72,9 @@ public string Sync(string workingDirectory, string? gitRef = null, string? repoU
/// <exception cref="NotImplementedException"></exception>
public string GetRepoCommitHash(string directory)
{
using var repository = new Repository(directory);
return repository.Head.Tip.Sha;
var task = _buildService.Run(directory, GitCommand, new List<string> { "rev-parse HEAD" });
task.Wait();
return task.Result;
}

public static string StripRef(string gitRef)
Expand All @@ -68,26 +86,14 @@ private void Clone(string repoUrl, string directory, string gitRef)
{
_log.Information("Cloning branch/commit {Ref}...", gitRef);

var sshConfig = _configuration.SshCommand != null
? $"--config core.sshcommand=\"{_configuration.SshCommand}\""
: "";

RunCommand(Path.GetFullPath("./..", directory), "clone --recurse-submodules", sshConfig, repoUrl);
RunCommand(directory, "fetch -fu origin", gitRef);
RunCommand(directory, "checkout", StripRef(gitRef));

/*var repoDirectory = Repository.Clone(repoUrl, directory, new CloneOptions
{
RecurseSubmodules = true,
OnProgress = LogProgress
});
using var repository = new Repository(repoDirectory);
Commands.Fetch(
repository,
"origin",
new []{gitRef},
new FetchOptions
{
OnProgress = LogProgress
},
null);
Commands.Checkout(repository, StripRef(gitRef));*/
_log.Information("Done cloning");
}

Expand All @@ -96,45 +102,36 @@ private void Pull(string repoDirectory, string gitRef)
_log.Information( "Pulling branch/commit {Ref}...", gitRef);
_log.Debug("Opening repository in: {RepositoryPath}", repoDirectory);

using var repository = new Repository(repoDirectory);
//Set an identity
_log.Debug("Setting identity");
repository.Config.Set("user.name", _configuration.Identity.Name);
repository.Config.Set("user.email", _configuration.Identity.Email);
RunCommand(repoDirectory, "config user.name", $"\"{_configuration.Identity.Name}\"");
RunCommand(repoDirectory, "config user.email", $"\"{_configuration.Identity.Email}\"");

if (_configuration.SshCommand != null)
{
_log.Debug("Setting ssh command");
repository.Config.Set("core.sshcommand", _configuration.SshCommand);
RunCommand(repoDirectory, "config core.sshcommand", $"\"{_configuration.SshCommand}\"");
}

_log.Debug("Fetching ref");
_buildService.Run(repoDirectory, "git", new List<string> { "fetch -fu origin", gitRef }).Wait();
RunCommand(repoDirectory, "fetch -fu origin", gitRef);

_log.Debug("Checking out {Ref}", StripRef(gitRef));
Commands.Checkout(repository, StripRef(gitRef));
RunCommand(repoDirectory, "checkout", StripRef(gitRef));

_log.Debug("Pulling latest changes");
_buildService.Run(repoDirectory, "git", new List<string> { "pull origin HEAD --ff-only" }).Wait();
RunCommand(repoDirectory, "pull origin HEAD --ff-only --force");

_log.Debug("Updating submodules");
foreach (var submodule in repository.Submodules)
{
if (submodule.UpdateRule == SubmoduleUpdate.None)
continue;

repository.Submodules.Update(submodule.Name, new SubmoduleUpdateOptions
{
OnProgress = LogProgress
});
}
RunCommand(repoDirectory, "submodule update --init --recursive");

_log.Information("Done pulling");
}

private bool LogProgress(string? progress)
private string RunCommand(string directory, params string[] arguments)
{
_log.Verbose("Progress: {Progress}", progress);
return true;
var task = _buildService.Run(directory, GitCommand, new List<string>(arguments));
task.Wait();
return task.Result;
}
}
26 changes: 24 additions & 2 deletions SS14.MapServer/Services/StartupCheckService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ public sealed class StartupCheckService
private readonly BuildConfiguration _buildConfiguration = new();
private readonly GitConfiguration _gitConfiguration = new();
private readonly ProcessingConfiguration _processingConfiguration = new();
private readonly GitService _gitService;
private readonly ContainerService _containerService;
private readonly LocalBuildService _localBuildService;


public StartupCheckService(ContainerService containerService, IConfiguration configuration, LocalBuildService localBuildService)
public StartupCheckService(ContainerService containerService, IConfiguration configuration, LocalBuildService localBuildService, GitService gitService)
{
_containerService = containerService;
_localBuildService = localBuildService;
_gitService = gitService;
configuration.Bind(FilePathsConfiguration.Name, _filePathsConfiguration);
configuration.Bind(BuildConfiguration.Name, _buildConfiguration);
configuration.Bind(GitConfiguration.Name, _gitConfiguration);
Expand Down Expand Up @@ -66,14 +68,34 @@ private async Task<bool> CheckBuildServices()
if (!_buildConfiguration.Enabled)
return true;

return _buildConfiguration.Runner switch
var result = await CheckGitPrerequisites();

return result && _buildConfiguration.Runner switch
{
BuildRunnerName.Local => await CheckLocalRunnerPrerequisites(),
BuildRunnerName.Container => await CheckContainerPrerequisites(),
_ => false
};
}

private async Task<bool> CheckGitPrerequisites()
{
Log.Information("Checking Git:");

try
{
var version = await _gitService.GetGitVersion();
Log.Information(" - Git version: {GitVersion}", version.Replace("\n", ""));
}
catch (Exception e)
{
Log.Fatal(e, "Couldn't determine Git version");
return false;
}

return true;
}

private async Task<bool> CheckContainerPrerequisites()
{
Log.Information("Checking container manager:");
Expand Down

0 comments on commit be062b0

Please sign in to comment.