Skip to content

Commit

Permalink
Optimize retrieval and propagation of X-Sha
Browse files Browse the repository at this point in the history
Simplify retrieval by leveraging JQ support in GH CLI, and always ensure we propagate the latest value for the X-Sha header.
  • Loading branch information
kzu committed Oct 18, 2024
1 parent e2531c3 commit 9814380
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
3 changes: 3 additions & 0 deletions src/File/GitHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public static class GitHub
public static bool TryIsInstalled(out string output)
=> Process.TryExecute("gh", "--version", out output) && output.StartsWith("gh version");

public static bool TryApi(string endpoint, string jq, out string? output)
=> Process.TryExecute("gh", $"api {endpoint} --jq \"{jq}\"", out output);

public static bool TryApi(string endpoint, out JToken? json)
{
json = null;
Expand Down
16 changes: 9 additions & 7 deletions src/File/Http/GitHubRawHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,10 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
(originalEtag != newEtag || originalSha == null) &&
parts.Length > 2 &&
GitHub.IsInstalled &&
GitHub.TryApi($"repos/{parts[0]}/{parts[1]}/commits?per_page=1&path={string.Join('/', parts.Skip(4))}", out var json) &&
json is JArray commits &&
commits[0] is JObject obj &&
obj.Property("sha") is JProperty prop &&
prop != null &&
prop.Value.Type == JTokenType.String)
GitHub.TryApi($"repos/{parts[0]}/{parts[1]}/commits?per_page=1&path={string.Join('/', parts.Skip(4))}", ".[0]?.sha", out var json) &&
json is { Length: > 0 })
{
newSha = prop.Value.ToObject<string>();
newSha = json;
}

// Just propagate back what we had initially, as an optimization for HEAD and cases
Expand All @@ -75,7 +71,13 @@ commits[0] is JObject obj &&
newSha = originalSha;

if (newSha != null)
{
// Make sure the X-Sha matches what we have now.
if (response.Headers.TryGetValues("X-Sha", out _))
response.Headers.Remove("X-Sha");

response.Headers.TryAddWithoutValidation("X-Sha", newSha);
}

return response;
}
Expand Down

0 comments on commit 9814380

Please sign in to comment.