From 4a9b8aabd8b1a5ddfa4e94b85a380ceb4f1e6133 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Wed, 20 Nov 2024 15:40:18 +0100 Subject: [PATCH] Fallback to main for remote tracking (#81) --- src/Elastic.Markdown/IO/GitConfiguration.cs | 39 ++++++++++----------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/src/Elastic.Markdown/IO/GitConfiguration.cs b/src/Elastic.Markdown/IO/GitConfiguration.cs index 3e01d8f..6634ab7 100644 --- a/src/Elastic.Markdown/IO/GitConfiguration.cs +++ b/src/Elastic.Markdown/IO/GitConfiguration.cs @@ -5,17 +5,15 @@ using System.IO.Abstractions; using System.Text.Json.Serialization; using IniParser; +using IniParser.Model; namespace Elastic.Markdown.IO; public record GitConfiguration { - [JsonPropertyName("branch")] - public required string Branch { get; init; } - [JsonPropertyName("remote")] - public required string Remote { get; init; } - [JsonPropertyName("ref")] - public required string Ref { get; init; } + [JsonPropertyName("branch")] public required string Branch { get; init; } + [JsonPropertyName("remote")] public required string Remote { get; init; } + [JsonPropertyName("ref")] public required string Ref { get; init; } // manual read because libgit2sharp is not yet AOT ready public static GitConfiguration Create(IFileSystem fileSystem) @@ -24,12 +22,7 @@ public static GitConfiguration Create(IFileSystem fileSystem) if (fileSystem is not FileSystem) { var fakeRef = Guid.NewGuid().ToString().Substring(0, 16); - return new GitConfiguration - { - Branch = $"test-{fakeRef}", - Remote = "elastic/docs-builder", - Ref = fakeRef, - }; + return new GitConfiguration { Branch = $"test-{fakeRef}", Remote = "elastic/docs-builder", Ref = fakeRef, }; } var gitConfig = Git(".git/config"); @@ -44,19 +37,25 @@ public static GitConfiguration Create(IFileSystem fileSystem) using var stream = gitConfig.OpenRead(); using var streamReader = new StreamReader(stream); var config = ini.ReadData(streamReader); - var remoteName = config[$"branch \"{branch}\""]["remote"]; - var remote = config[$"remote \"{remoteName}\""]["url"]; + var remote = BranchTrackingRemote(branch, config); + if (string.IsNullOrEmpty(remote)) + remote = BranchTrackingRemote("main", config); + if (string.IsNullOrEmpty(remote)) + remote = BranchTrackingRemote("master", config); - return new GitConfiguration - { - Ref = gitRef, - Branch = branch, - Remote = remote - }; + + return new GitConfiguration { Ref = gitRef, Branch = branch, Remote = remote }; IFileInfo Git(string path) => fileSystem.FileInfo.New(Path.Combine(Paths.Root.FullName, path)); string Read(string path) => fileSystem.File.ReadAllText(Git(path).FullName).Trim(Environment.NewLine.ToCharArray()); + + string BranchTrackingRemote(string b, IniData c) + { + var remoteName = c[$"branch \"{b}\""]["remote"]; + remote = c[$"remote \"{remoteName}\""]["url"]; + return remote; + } } }