/// <summary> /// Update a pull request for the specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/#update-a-pull-request</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The PullRequest number</param> /// <param name="pullRequestUpdate">An <see cref="PullRequestUpdate"/> instance describing the changes to make to the PullRequest /// </param> /// <returns>An updated <see cref="PullRequest"/> result</returns> public IObservable<PullRequest> Update(string owner, string name, int number, PullRequestUpdate pullRequestUpdate) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(pullRequestUpdate, "pullRequestUpdate"); return _client.Update(owner, name, number, pullRequestUpdate).ToObservable(); }
public void PostsToCorrectUrl() { var pullRequestUpdate = new PullRequestUpdate(); var connection = Substitute.For<IApiConnection>(); var client = new PullRequestsClient(connection); client.Update("fake", "repo", 42, pullRequestUpdate); connection.Received().Patch<PullRequest>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/pulls/42"), pullRequestUpdate); }
public void UpdatesClientRepositoryPullRequest() { var pullRequestUpdate = new PullRequestUpdate(); var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestsClient(gitHubClient); client.Update("fake", "repo", 42, pullRequestUpdate); gitHubClient.Repository.PullRequest.Received().Update("fake", "repo", 42, pullRequestUpdate); }
/// <summary> /// Update a pull request for the specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/#update-a-pull-request</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The PullRequest number</param> /// <param name="pullRequestUpdate">An <see cref="PullRequestUpdate"/> instance describing the changes to make to the PullRequest /// </param> public IObservable <PullRequest> Update(long repositoryId, int number, PullRequestUpdate pullRequestUpdate) { Ensure.ArgumentNotNull(pullRequestUpdate, "pullRequestUpdate"); return(_client.Update(repositoryId, number, pullRequestUpdate).ToObservable()); }
public async Task EvaluateAsync_WithDisabledPolicy_ShouldNotEvaluatePolicy() { var pullRequestUpdate = new PullRequestUpdate { Id = 5, CollectionId = Guid.NewGuid().ToString(), ProjectId = Guid.NewGuid().ToString(), RepositoryId = Guid.NewGuid().ToString() }; var accountConfiguration = new AccountConfiguration { CollectionId = pullRequestUpdate.CollectionId, BaseUrl = "https://fabrikam.visualstudio.com/DefaultCollection", PersonalAccessToken = "SECRET!!" }; var pullRequest = new GitPullRequest(); var gitClientMock = new Mock <GitHttpClient>(new object[] { new Uri("https://fabrikam.visualstudio.com/DefaultCollection"), (VssCredentials) new VssBasicCredential() }); gitClientMock.Setup(m => m.GetPullRequestAsync(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int?>(), It.IsAny <int?>(), It.IsAny <int?>(), It.IsAny <bool?>(), It.IsAny <bool?>(), It.IsAny <object>(), It.IsAny <CancellationToken>())) .ReturnsAsync(pullRequest); var connectionFactoryMock = new Mock <IVssConnectionFactory>(); connectionFactoryMock.Setup(m => m.CreateFactory(It.IsAny <Uri>(), It.IsAny <VssCredentials>())) .Returns(connectionFactoryMock.Object); connectionFactoryMock.Setup(m => m.GetClientAsync <GitHttpClient>()) .ReturnsAsync(gitClientMock.Object); var testPolicyMock = new Mock <StatusPolicy>(new object[] { connectionFactoryMock.Object }); testPolicyMock.Setup(m => m.EvaluateAsync(It.IsAny <GitPullRequest>())); const string policyName = "TestPolicy"; var statusPoliciesServiceMock = new Mock <IStatusPoliciesService>(); statusPoliciesServiceMock.Setup(m => m.GetPolicies()) .Returns(new string[] { policyName }); statusPoliciesServiceMock.Setup(m => m.GetPolicy(It.IsAny <IVssConnectionFactory>(), It.IsAny <string>())) .Returns(testPolicyMock.Object); var configurationRepositoryMock = new Mock <IConfigurationRepository>(); configurationRepositoryMock.Setup(m => m.GetAsync(It.IsAny <string>())) .ReturnsAsync(accountConfiguration); var pullRequestService = new PullRequestService( new Uri("https://aitpullrequests.azurewebsites.net/"), connectionFactoryMock.Object, statusPoliciesServiceMock.Object, configurationRepositoryMock.Object); await pullRequestService.EvaluateAsync(pullRequestUpdate); configurationRepositoryMock.Verify(m => m.GetAsync(pullRequestUpdate.CollectionId), Times.Once); connectionFactoryMock.Verify(m => m.CreateFactory(new Uri(accountConfiguration.BaseUrl), It.IsAny <VssCredentials>()), Times.Once); gitClientMock.Verify(m => m.GetPullRequestAsync(pullRequestUpdate.RepositoryId, pullRequestUpdate.Id, It.IsAny <int?>(), It.IsAny <int?>(), It.IsAny <int?>(), It.IsAny <bool?>(), It.IsAny <bool?>(), It.IsAny <object>(), It.IsAny <CancellationToken>()), Times.Once); statusPoliciesServiceMock.Verify(m => m.GetPolicies(), Times.Once); statusPoliciesServiceMock.Verify(m => m.GetPolicy(connectionFactoryMock.Object, policyName), Times.Never); testPolicyMock.Verify(m => m.EvaluateAsync(pullRequest), Times.Never); }
public void Start() { var consoleMenu = new ConsoleMenu(ConsoleMenuType.StringInput); consoleMenu.MenuOptions.Add(new ConsoleMenuOption("Remove all my forks and close their active PR's", new Action(() => { Console.WriteLine("Actions to execute:"); var allPrs = _gitOctoKitHandler.GetAllMyOpenPrs().Result; foreach (var pr in allPrs) { Console.WriteLine($"\tClose:\t{pr.Issue.HtmlUrl} ({pr.Issue.State})"); } var myReposAll = _gitOctoKitHandler.GitHubClient.Repository.GetAllForCurrent().Result; var myRepos = myReposAll.Where(t => t.Fork).ToList(); foreach (var repo in myRepos) { Console.WriteLine($"\tDelete:\t{repo.FullName}"); } var consMenuRemoveRepos = new ConsoleMenu(ConsoleMenuType.StringInput); consMenuRemoveRepos.MenuOptions.Add(new ConsoleMenuOption("Yes", new Action(() => { foreach (var pr in allPrs) { Console.Write($"Closing: {pr.Issue.HtmlUrl} "); var up = new PullRequestUpdate() { State = ItemState.Closed }; _gitOctoKitHandler.GitHubClient.PullRequest.Update(pr.RepoOwner, pr.RepoName, pr.Issue.Number, up).Wait(); Console.WriteLine("Done"); } foreach (var repo in myRepos) { Console.Write($"Removing: {repo.FullName} "); _gitOctoKitHandler.GitHubClient.Repository.Delete(repo.Id).Wait(); Console.WriteLine("Done"); } }))); consMenuRemoveRepos.MenuOptions.Add(new ConsoleMenuOption("No", new Action(() => { }))); Console.WriteLine(); Console.WriteLine("Are you sure you want to execute these actions?"); consMenuRemoveRepos.RenderMenu(); consMenuRemoveRepos.WaitForResult(); }))); consoleMenu.MenuOptions.Add(new ConsoleMenuOption("Remove all my forks", new Action(() => { Console.WriteLine("Actions to execute:"); var myReposAll = _gitOctoKitHandler.GitHubClient.Repository.GetAllForCurrent().Result; var myRepos = myReposAll.Where(t => t.Fork).ToList(); foreach (var repo in myRepos) { Console.WriteLine($"\tDelete:\t{repo.FullName}"); } var consMenuRemoveRepos = new ConsoleMenu(ConsoleMenuType.StringInput); consMenuRemoveRepos.MenuOptions.Add(new ConsoleMenuOption("Yes", new Action(() => { foreach (var repo in myRepos) { Console.Write($"Removing: {repo.FullName} "); _gitOctoKitHandler.GitHubClient.Repository.Delete(repo.Id).Wait(); Console.WriteLine("Done"); } }))); consMenuRemoveRepos.MenuOptions.Add(new ConsoleMenuOption("No", new Action(() => { }))); Console.WriteLine(); Console.WriteLine("Are you sure you want to execute these actions?"); consMenuRemoveRepos.RenderMenu(); consMenuRemoveRepos.WaitForResult(); }))); consoleMenu.MenuOptions.Add(new ConsoleMenuOption("Close all my pull requests", new Action(() => { Console.WriteLine("Actions to execute:"); var allPrs = _gitOctoKitHandler.GetAllMyOpenPrs().Result; foreach (var pr in allPrs) { Console.WriteLine($"\tClose:\t{pr.Issue.HtmlUrl} ({pr.Issue.State})"); } var consMenuRemoveRepos = new ConsoleMenu(ConsoleMenuType.StringInput); consMenuRemoveRepos.MenuOptions.Add(new ConsoleMenuOption("Yes", new Action(() => { foreach (var pr in allPrs) { Console.Write($"Closing: {pr.Issue.HtmlUrl} "); var up = new PullRequestUpdate() { State = ItemState.Closed }; _gitOctoKitHandler.GitHubClient.PullRequest.Update(pr.RepoOwner, pr.RepoName, pr.Issue.Number, up).Wait(); Console.WriteLine("Done"); } }))); consMenuRemoveRepos.MenuOptions.Add(new ConsoleMenuOption("No", new Action(() => { }))); Console.WriteLine(); Console.WriteLine("Are you sure you want to execute these actions?"); consMenuRemoveRepos.RenderMenu(); consMenuRemoveRepos.WaitForResult(); }))); consoleMenu.MenuOptions.Add(new ConsoleMenuOption("Exit", new Action(() => { }))); Console.WriteLine(); consoleMenu.RenderMenu(); consoleMenu.WaitForResult(); }
/// <summary> /// Update a pull request for the specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/#update-a-pull-request</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="number">The PullRequest number</param> /// <param name="pullRequestUpdate">An <see cref="PullRequestUpdate"/> instance describing the changes to make to the PullRequest /// </param> public IObservable <PullRequest> Update(string owner, string name, int number, PullRequestUpdate pullRequestUpdate) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(pullRequestUpdate, "pullRequestUpdate"); return(_client.Update(owner, name, number, pullRequestUpdate).ToObservable()); }
/// <summary> /// Update a pull request for the specified repository. /// </summary> /// <remarks>http://developer.github.com/v3/pulls/#update-a-pull-request</remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="number">The PullRequest number</param> /// <param name="pullRequestUpdate">An <see cref="PullRequestUpdate"/> instance describing the changes to make to the PullRequest /// </param> public IObservable<PullRequest> Update(long repositoryId, int number, PullRequestUpdate pullRequestUpdate) { Ensure.ArgumentNotNull(pullRequestUpdate, "pullRequestUpdate"); return _client.Update(repositoryId, number, pullRequestUpdate).ToObservable(); }
public async ValueTask <string> UpdatePullRequestAsync(int number, PullRequestUpdate input) { var result = await _client.PullRequest.Update(_config.Owner, _config.Repo, number, input); return(result.NodeId); }
public async Task PostsToCorrectUrlWithRepositoryId() { var pullRequestUpdate = new PullRequestUpdate(); var connection = Substitute.For<IApiConnection>(); var client = new PullRequestsClient(connection); await client.Update(1, 42, pullRequestUpdate); connection.Received().Patch<PullRequest>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/pulls/42"), pullRequestUpdate); }
public static async Task GoOptimize(string repositoryOwner, string repositoryName, string branchName = null) { Console.WriteLine($"{repositoryOwner}/{repositoryName} is being optimized..."); Console.WriteLine(); var config = ConfigHelper.GetConfig(); var gitOctoKitHandler = new GitOctoKitHandler(config); string dirOfClonedRepos = config.ClonedRepositoriesDirectoryName; if (!Path.IsPathRooted(dirOfClonedRepos)) { dirOfClonedRepos = Path.Combine(FolderHelperMethods.EntryAssemblyDirectory.Value, config.ClonedRepositoriesDirectoryName); } Directory.CreateDirectory(dirOfClonedRepos); Directory.SetCurrentDirectory(dirOfClonedRepos); var git = new GitCommandLineHandler(config); var clonedRepo = await git.GitClone(dirOfClonedRepos, repositoryOwner, repositoryName); Directory.SetCurrentDirectory(clonedRepo); if (branchName == null) { branchName = await git.GetHeadBranch(); if (branchName == null) { throw new Exception("ERROR, couldn't determine branchname"); } } await git.RunHubCommand("fork"); await git.RunHubCommand($"remote set-url {config.GithubUserName} https://github.com/{config.GithubUserName}/{repositoryName}.git"); //Fetch everything in my repository await git.RunHubCommand("fetch --all"); //Go to master await git.RunHubCommand($"checkout {config.GithubUserName}/{branchName}"); await git.RunHubCommand($"merge --strategy-option=theirs origin/{branchName}"); await git.RunHubCommand($"push {config.GithubUserName} HEAD:{branchName}"); var wasAbleToAddTrackedBranch = await git.RunHubCommand($"checkout --track -b {Constants.FeatureName} {config.GithubUserName}/{Constants.FeatureName}"); if (wasAbleToAddTrackedBranch == 0) { await git.RunHubCommand($"merge --strategy-option=theirs {config.GithubUserName}/{branchName}"); await git.RunHubCommand($"push {config.GithubUserName} {Constants.FeatureName} -u"); } else { var createdNewBranch = await git.RunHubCommand($"checkout -b {Constants.FeatureName}"); if (createdNewBranch == 0) { } else { await git.RunHubCommand($"checkout {Constants.FeatureName}"); await git.RunHubCommand($"merge --strategy-option=theirs {config.GithubUserName}/{branchName}"); } await git.RunHubCommand($"push {config.GithubUserName} {Constants.FeatureName} -u"); } var optimizedFileResults = await GoOptimize(clonedRepo, config); //var optimizedFileResults = await GoOptimizeStub(clonedRepo, config); await git.RunHubCommand("add ."); var descriptionForCommit = await TemplatesHandler.GetDescriptionForCommit(); await git.Commit("Wop optimized this repository", descriptionForCommit); await git.RunHubCommand($"push"); var descriptionForPullRequest = await TemplatesHandler.GetDescriptionForPullRequest(); //Only create pull request if there were actually any successful optimizations if (optimizedFileResults.Any(t => t.Successful) && optimizedFileResults.Sum(t => t.OriginalSize) > optimizedFileResults.Sum(t => t.OptimizedSize)) { var pullRequestState = await git.PullRequest("The Web Optimization Project has optimized your repository!", descriptionForPullRequest); Console.WriteLine("Pullrequeststate: " + pullRequestState); PullRequest obtainedPullRequest = null; for (int i = 0; i < 3; i++) { obtainedPullRequest = await gitOctoKitHandler.GetPullRequest(repositoryOwner, repositoryName); if (obtainedPullRequest != null) { break; } Console.WriteLine("Couldn't find Pull Request. Waiting and retrying..."); await Task.Delay(10000); } Console.WriteLine($"Found pull request: {obtainedPullRequest.HtmlUrl}"); var commitIdentifier = "### Commit "; var splittedBody = obtainedPullRequest.Body.Split('\n'); var commitCount = splittedBody.Count(t => t.StartsWith(commitIdentifier)); var descriptionForCommitInPr = await TemplatesHandler.GetCommitDescriptionForPullRequest(clonedRepo, branchName, optimizedFileResults, commitCount + 1); var bodySb = new StringBuilder(obtainedPullRequest.Body); bodySb.AppendLine(); bodySb.AppendLine(); bodySb.AppendLine(descriptionForCommitInPr); var pullRequestUpdate = new PullRequestUpdate() { Body = bodySb.ToString() }; await gitOctoKitHandler.GitHubClient.PullRequest.Update(repositoryOwner, repositoryName, obtainedPullRequest.Number, pullRequestUpdate); } Console.WriteLine(); Console.WriteLine($"{repositoryOwner}/{repositoryName} is optimized :)"); Console.WriteLine(); }
public async Task <Pr> OpenAsync(GitHubClientParameters parameters, bool update, Settings settings = null) { var inMemoryCredentialStore = new InMemoryCredentialStore(new Credentials(KnownGitHubs.Username, parameters.Password)); var githubClient = new GitHubClient(new ProductHeaderValue("ImgBot"), inMemoryCredentialStore); var repo = await githubClient.Repository.Get(parameters.RepoOwner, parameters.RepoName); var branch = await githubClient.Repository.Branch.Get(parameters.RepoOwner, parameters.RepoName, KnownGitHubs.BranchName); var commit = await githubClient.Repository.Commit.Get(parameters.RepoOwner, parameters.RepoName, branch.Commit.Sha); if (branch == null) { return(null); } var baseBranch = repo.DefaultBranch; if (settings != null && !string.IsNullOrEmpty(settings.DefaultBranchOverride)) { baseBranch = settings.DefaultBranchOverride; } var stats = Stats.ParseStats(commit.Commit.Message); Octokit.PullRequest result; if (update) { // get PR number var allPrs = await githubClient.PullRequest.GetAllForRepository(parameters.RepoOwner, parameters.RepoName); var pr = allPrs.FirstOrDefault(p => p.State == ItemState.Open && p.Head.Sha == commit.Sha); if (pr == null) { throw new Exception("Couldn't update PR. PR not found"); } var pru = new PullRequestUpdate() { Body = PullRequestBody.Generate(stats, settings), }; result = await githubClient.PullRequest.Update(parameters.RepoOwner, parameters.RepoName, pr.Number, pru); } else { var commitMessageTitle = KnownGitHubs.CommitMessageTitle; if (settings?.PrTitle != null) { commitMessageTitle = settings.PrTitle; } var pr = new NewPullRequest(commitMessageTitle, KnownGitHubs.BranchName, baseBranch) { Body = PullRequestBody.Generate(stats, settings), }; result = await githubClient.PullRequest.Create(parameters.RepoOwner, parameters.RepoName, pr); } var labels = new List <string>(); if (settings?.Labels != null) { var issueUpdate = new IssueUpdate(); foreach (var label in settings.Labels.Split(',')) { issueUpdate.AddLabel(label); } await githubClient.Issue.Update(parameters.RepoOwner, parameters.RepoName, result.Number, issueUpdate); } if (stats == null) { return(null); } return(new Pr(parameters.RepoOwner) { RepoName = parameters.RepoName, Id = result.Id, NumImages = stats.Length == 1 ? 1 : stats.Length - 1, Number = result.Number, SizeBefore = ImageStat.ToDouble(stats[0].Before), SizeAfter = ImageStat.ToDouble(stats[0].After), PercentReduced = stats[0].Percent, }); }