|
| 1 | +using Octokit; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Diagnostics; |
| 5 | +using System.IO; |
| 6 | +using System.Linq; |
| 7 | +using System.Text; |
| 8 | +using System.Text.RegularExpressions; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace PullRequestSubmitter.Helpers |
| 12 | +{ |
| 13 | + static class GitHubUtil |
| 14 | + { |
| 15 | + public static async Task<IDictionary<string, NewBlob>> GetEditsToCommit( |
| 16 | + GitHubClient client, Repository upstreamRepo, string baseSha, |
| 17 | + IEnumerable<PropertyUpdate> propertyUpdates) |
| 18 | + { |
| 19 | + // Find the file to update |
| 20 | + var existingTree = await client.Git.Tree.GetRecursive(upstreamRepo.Id, baseSha); |
| 21 | + |
| 22 | + // Update the files' contents |
| 23 | + var result = new Dictionary<string, NewBlob>(); |
| 24 | + var filesToUpdate = propertyUpdates.GroupBy(p => p.Filename); |
| 25 | + foreach (var fileToUpdate in filesToUpdate) |
| 26 | + { |
| 27 | + var fileContents = await GetFileContentsAsString( |
| 28 | + client, upstreamRepo, existingTree.Tree, fileToUpdate.Key); |
| 29 | + |
| 30 | + foreach (var propToUpdate in fileToUpdate) |
| 31 | + { |
| 32 | + var propName = propToUpdate.PropertyName; |
| 33 | + var patternToReplace = new Regex($"<{propName}>[^<]+</{propName}>"); |
| 34 | + if (!patternToReplace.IsMatch(fileContents)) |
| 35 | + { |
| 36 | + throw new Exception($"The file {fileToUpdate.Key} does not contain a match for regex " + patternToReplace.ToString()); |
| 37 | + } |
| 38 | + |
| 39 | + fileContents = patternToReplace.Replace( |
| 40 | + fileContents, |
| 41 | + $"<{propName}>{propToUpdate.NewValue}</{propName}>"); |
| 42 | + } |
| 43 | + |
| 44 | + var newBlob = new NewBlob { Content = fileContents, Encoding = EncodingType.Utf8 }; |
| 45 | + result.Add(fileToUpdate.Key, newBlob); |
| 46 | + } |
| 47 | + |
| 48 | + return result; |
| 49 | + } |
| 50 | + |
| 51 | + public static async Task<string> GetLatestCommitSha( |
| 52 | + GitHubClient client, Repository repo, string branchName) |
| 53 | + { |
| 54 | + var commitRef = await client.Git.Reference.Get( |
| 55 | + repo.Id, |
| 56 | + $"heads/{branchName}"); |
| 57 | + return commitRef.Object.Sha; |
| 58 | + } |
| 59 | + |
| 60 | + public static async Task<string> CommitModifiedFiles( |
| 61 | + GitHubClient client, Repository toRepo, string toBranchName, string parentCommitSha, |
| 62 | + IDictionary<string, NewBlob> modifiedFiles, string commitMessage) |
| 63 | + { |
| 64 | + // Build and commit a new tree representing the updated state |
| 65 | + var newTree = new NewTree { BaseTree = parentCommitSha }; |
| 66 | + foreach (var kvp in modifiedFiles) |
| 67 | + { |
| 68 | + newTree.Tree.Remove(new NewTreeItem { Path = kvp.Key }); |
| 69 | + newTree.Tree.Add(new NewTreeItem() |
| 70 | + { |
| 71 | + Type = TreeType.Blob, |
| 72 | + Mode = "100644", |
| 73 | + Sha = (await client.Git.Blob.Create(toRepo.Id, kvp.Value)).Sha, |
| 74 | + Path = kvp.Key |
| 75 | + }); |
| 76 | + } |
| 77 | + var createdTree = await client.Git.Tree.Create(toRepo.Id, newTree); |
| 78 | + var commit = await client.Git.Commit.Create( |
| 79 | + toRepo.Id, |
| 80 | + new NewCommit(commitMessage, createdTree.Sha, parentCommitSha)); |
| 81 | + |
| 82 | + // Update the target branch to point to the new commit |
| 83 | + await client.Git.Reference.Update( |
| 84 | + toRepo.Id, |
| 85 | + $"heads/{toBranchName}", |
| 86 | + new ReferenceUpdate(commit.Sha, force: true)); |
| 87 | + |
| 88 | + return commit.Sha; |
| 89 | + } |
| 90 | + |
| 91 | + public static async Task<Issue> FindExistingPullRequestToUpdate( |
| 92 | + GitHubClient client, User currentUser, Repository upstreamRepo, |
| 93 | + Repository forkRepo, string forkBranch) |
| 94 | + { |
| 95 | + // Search for candidate PRs (same author, still open, etc.) |
| 96 | + var fromBaseRef = $"{forkRepo.Owner.Login}:{forkBranch}"; |
| 97 | + var searchInRepos = new RepositoryCollection(); |
| 98 | + searchInRepos.Add(upstreamRepo.Owner.Login, upstreamRepo.Name); |
| 99 | + var searchRequest = new SearchIssuesRequest |
| 100 | + { |
| 101 | + Repos = searchInRepos, |
| 102 | + Type = IssueTypeQualifier.PullRequest, |
| 103 | + Author = currentUser.Login, |
| 104 | + State = ItemState.Open |
| 105 | + }; |
| 106 | + var searchResults = await client.Search.SearchIssues(searchRequest); |
| 107 | + |
| 108 | + // Of the candidates, find the highest-numbered one that is requesting a |
| 109 | + // pull from the same fork and branch. GitHub only allows there to be one |
| 110 | + // of these at any given time, but we're more likely to find it faster |
| 111 | + // by searching from newest to oldest. |
| 112 | + var candidates = searchResults.Items.OrderByDescending(item => item.Number); |
| 113 | + foreach (var prInfo in candidates) |
| 114 | + { |
| 115 | + var pr = await client.PullRequest.Get(upstreamRepo.Id, prInfo.Number); |
| 116 | + if (pr.Head?.Repository?.Id == forkRepo.Id && pr.Head?.Ref == forkBranch) |
| 117 | + { |
| 118 | + return prInfo; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + return null; |
| 123 | + } |
| 124 | + |
| 125 | + public static async Task<PullRequest> CreateNewPullRequest( |
| 126 | + GitHubClient client, Repository upstreamRepo, string upstreamBranch, |
| 127 | + Repository forkRepo, string forkBranch, string prBodyText) |
| 128 | + { |
| 129 | + var fromBaseRef = $"{forkRepo.Owner.Login}:{forkBranch}"; |
| 130 | + var newPr = new NewPullRequest( |
| 131 | + prBodyText, |
| 132 | + fromBaseRef, |
| 133 | + upstreamBranch); |
| 134 | + return await client.PullRequest.Create(upstreamRepo.Id, newPr); |
| 135 | + } |
| 136 | + |
| 137 | + public static async Task UpdateExistingPullRequestTitle( |
| 138 | + GitHubClient client, Repository upstreamRepo, int prNumber, string newTitle) |
| 139 | + { |
| 140 | + var updateInfo = new PullRequestUpdate { Title = newTitle }; |
| 141 | + await client.PullRequest.Update(upstreamRepo.Id, prNumber, updateInfo); |
| 142 | + } |
| 143 | + |
| 144 | + private static async Task<string> GetFileContentsAsString( |
| 145 | + GitHubClient client, Repository repo, IReadOnlyList<TreeItem> tree, string path) |
| 146 | + { |
| 147 | + var existingFile = tree.FirstOrDefault(item => item.Path == path); |
| 148 | + var blob = await client.Git.Blob.Get(repo.Id, existingFile.Sha); |
| 149 | + |
| 150 | + switch (blob.Encoding.Value) |
| 151 | + { |
| 152 | + case EncodingType.Utf8: |
| 153 | + return blob.Content; |
| 154 | + case EncodingType.Base64: |
| 155 | + return Encoding.UTF8.GetString(Convert.FromBase64String(blob.Content)); |
| 156 | + default: |
| 157 | + throw new InvalidDataException($"Unsupported encoding: {blob.Encoding.StringValue}"); |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | +} |
0 commit comments