Exemplo n.º 1
0
 public void If_invalid_subscription_context_specified_exception_is_thrown()
 {
    EnumerationServer server = new EnumerationServer();
    PullRequest request = new PullRequest
                             {
                                EnumerationContext = new EnumerationContextKey("aaa")
                             };
    server.Pull(request);
 }      
Exemplo n.º 2
0
 public GithubPullRequest(PullRequest pullrequest)
 {
     _pullrequest = pullrequest;
 }
Exemplo n.º 3
0
 public GitHubPullRequest(PullRequest pullRequest)
 {
     _pullRequest = pullRequest;
 }
 public GitHubPullRequestReference(PullRequest pullRequest)
 {
     PullRequest = pullRequest;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary <string, object> parsedArgs)
        {
            string subscriptionName = (string)parsedArgs["subscription_name"];

            Console.WriteLine(@"Retrieving messages from subscription: ""{0}""", subscriptionName);

            PullRequest pullRequest = new PullRequest();

            pullRequest.MaxMessages = (int?)parsedArgs["max_messages"];

            PullResponse response = null;

            try
            {
                response = pubSubService.Projects.Subscriptions.Pull(
                    pullRequest, subscriptionName).Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                          $"Google Cloud Pub/Sub API returned error response:\n{exception.Message}");
            }

            var ackIds = new List <string>();
            IList <ReceivedMessage> receivedMessages = response.ReceivedMessages;

            if (receivedMessages.Count == 0)
            {
                Console.Out.WriteLine("No messages received from the subscription.");
            }
            else
            {
                var options = new JsonSerializerOptions();
                options.WriteIndented = true;

                foreach (ReceivedMessage receivedMessage in receivedMessages)
                {
                    ackIds.Add(receivedMessage.AckId);
                    PubsubMessage message = receivedMessage.Message;
                    IDictionary <string, string> messageAttributes = message.Attributes;
                    var accountId  = messageAttributes["accountId"];
                    var creativeId = messageAttributes["creativeId"];

                    Console.Out.WriteLine(@"* Creative found for buyer account ID ""{0}"" with " +
                                          @"creative ID ""{1}"" has been updated with the following " +
                                          "creative status:\n", accountId, creativeId);

                    byte[]      data          = Convert.FromBase64String(message.Data);
                    var         decodedString = Encoding.UTF8.GetString(data);
                    JsonElement jsonData      = JsonSerializer.Deserialize <JsonElement>(decodedString);

                    Console.Out.WriteLine(JsonSerializer.Serialize(jsonData, options));
                }

                if ((bool)parsedArgs["acknowledge"])
                {
                    AcknowledgeRequest acknowledgeRequest = new AcknowledgeRequest();
                    acknowledgeRequest.AckIds = ackIds;

                    Console.Out.WriteLine(
                        "Acknowledging all {0} messages pulled from the subscription.",
                        ackIds.Count);

                    try
                    {
                        pubSubService.Projects.Subscriptions.Acknowledge(acknowledgeRequest,
                                                                         subscriptionName);
                    }
                    catch (System.Exception exception)
                    {
                        throw new ApplicationException(
                                  "Google Cloud Pub/Sub API returned error response:\n" +
                                  $"{exception.Message}");
                    }
                }
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Vetos the <see cref="PullRequestSignOff"/> for a given <paramref name="pullRequest"/>
 /// </summary>
 /// <param name="pullRequest">The <see cref="PullRequest"/> to veto</param>
 /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
 /// <returns>A <see cref="Task"/> representing the running operation</returns>
 public Task VetoSignOff(PullRequest pullRequest, CancellationToken cancellationToken) => EraseAndDismissReviews(pullRequest, stringLocalizer["SignOffVetod"], cancellationToken);
Exemplo n.º 7
0
        /// <summary>
        /// Generate map diffs for a given <paramref name="pullRequest"/>
        /// </summary>
        /// <param name="pullRequest">The <see cref="PullRequest"/></param>
        /// <param name="changedDmms">Paths to changed .dmm files</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
        /// <returns>A <see cref="Task"/> representing the running operation</returns>
        async Task GenerateDiffs(PullRequest pullRequest, IReadOnlyList <string> changedDmms, CancellationToken cancellationToken)
        {
            using (logger.BeginScope("Generating {0} diffs for pull request #{1} in {2}/{3}", changedDmms.Count, pullRequest.Number, pullRequest.Base.Repository.Owner.Login, pullRequest.Base.Repository.Name))
            {
                const string OldMapExtension = ".old_map_diff_bot";

                var gitHubManager = serviceProvider.GetRequiredService <IGitHubManager>();

                Task generatingCommentTask;
                List <Task <RenderResult> > afterRenderings, beforeRenderings;

                var workingDir = ioManager.ConcatPath(pullRequest.Base.Repository.Owner.Login, pullRequest.Base.Repository.Name, pullRequest.Number.ToString(CultureInfo.InvariantCulture));
                logger.LogTrace("Setting workdir to {0}", workingDir);
                IIOManager currentIOManager = new ResolvingIOManager(ioManager, workingDir);
                string     repoPath;

                int  lastProgress       = -1;
                Task lastProgressUpdate = Task.CompletedTask;
                async Task OnCloneProgress(int progress)
                {
                    lock (gitHubManager)
                    {
                        if (lastProgress >= progress)
                        {
                            return;
                        }
                        if (lastProgress == -1)
                        {
                            logger.LogInformation("Waiting on repository to finish cloning...");
                        }
                        lastProgress = progress;
                    }
                    await lastProgressUpdate.ConfigureAwait(false);

                    await gitHubManager.CreateSingletonComment(pullRequest, stringLocalizer["Cloning repository... ({0}%)", progress], cancellationToken).ConfigureAwait(false);
                };
                Task CreateBlockedComment()
                {
                    logger.LogInformation("Waiting for another diff generation on {0}/{1} to complete...", pullRequest.Base.Repository.Owner.Login, pullRequest.Base.Repository.Name);
                    return(gitHubManager.CreateSingletonComment(pullRequest, stringLocalizer["Waiting for another operation on this repository to complete..."], cancellationToken));
                };

                logger.LogTrace("Locking repository...");
                using (var repo = await repositoryManager.GetRepository(pullRequest.Base.Repository, OnCloneProgress, CreateBlockedComment, cancellationToken).ConfigureAwait(false))
                {
                    logger.LogTrace("Repository ready");
                    generatingCommentTask = gitHubManager.CreateSingletonComment(pullRequest, stringLocalizer["Generating diffs..."], cancellationToken);
                    //prep the outputDirectory
                    async Task DirectoryPrep()
                    {
                        logger.LogTrace("Cleaning workdir...");
                        await currentIOManager.DeleteDirectory(".", cancellationToken).ConfigureAwait(false);

                        await currentIOManager.CreateDirectory(".", cancellationToken).ConfigureAwait(false);

                        logger.LogTrace("Workdir cleaned");
                    };

                    var dirPrepTask = DirectoryPrep();
                    //get the dme to use
                    var dmeToUseTask = serviceProvider.GetRequiredService <IDatabaseContext>().InstallationRepositories.Where(x => x.Id == pullRequest.Base.Repository.Id).Select(x => x.TargetDme).ToAsyncEnumerable().FirstOrDefault(cancellationToken);

                    var oldMapPaths = new List <string>()
                    {
                        Capacity = changedDmms.Count
                    };
                    try
                    {
                        //fetch base commit if necessary and check it out, fetch pull request
                        if (!await repo.ContainsCommit(pullRequest.Base.Sha, cancellationToken).ConfigureAwait(false))
                        {
                            logger.LogTrace("Base commit not found, running fetch...");
                            await repo.Fetch(cancellationToken).ConfigureAwait(false);
                        }
                        logger.LogTrace("Moving HEAD to pull request base...");
                        await repo.Checkout(pullRequest.Base.Sha, cancellationToken).ConfigureAwait(false);

                        //but since we don't need this right await don't await it yet
                        var pullRequestFetchTask = repo.FetchPullRequest(pullRequest.Number, cancellationToken);
                        try
                        {
                            //first copy all modified maps to the same location with the .old_map_diff_bot extension
                            async Task <string> CacheMap(string mapPath)
                            {
                                var originalPath = currentIOManager.ConcatPath(repoPath, mapPath);

                                if (await currentIOManager.FileExists(originalPath, cancellationToken).ConfigureAwait(false))
                                {
                                    logger.LogTrace("Creating old map cache of {0}", mapPath);
                                    var oldMapPath = String.Format(CultureInfo.InvariantCulture, "{0}{1}", originalPath, OldMapExtension);
                                    await currentIOManager.CopyFile(originalPath, oldMapPath, cancellationToken).ConfigureAwait(false);

                                    return(oldMapPath);
                                }
                                return(null);
                            };

                            repoPath = repo.Path;

                            var tasks = changedDmms.Select(x => CacheMap(x)).ToList();
                            await Task.WhenAll(tasks).ConfigureAwait(false);

                            oldMapPaths.AddRange(tasks.Select(x => x.Result));
                        }
                        finally
                        {
                            logger.LogTrace("Waiting for pull request commits to be available...");
                            await pullRequestFetchTask.ConfigureAwait(false);
                        }

                        logger.LogTrace("Creating and moving HEAD to pull request merge commit...");
                        //generate the merge commit ourselves since we can't get it from GitHub because itll return an outdated one
                        await repo.Merge(pullRequest.Head.Sha, cancellationToken).ConfigureAwait(false);
                    }
                    finally
                    {
                        logger.LogTrace("Waiting for configured project dme...");
                        await dmeToUseTask.ConfigureAwait(false);
                    }

                    //create empty array of map regions
                    var mapRegions = Enumerable.Repeat <MapRegion>(null, changedDmms.Count).ToList();
                    var dmeToUse   = dmeToUseTask.Result;

                    var generator       = generatorFactory.CreateGenerator(dmeToUse, new ResolvingIOManager(ioManager, repoPath));
                    var outputDirectory = currentIOManager.ResolvePath(".");
                    logger.LogTrace("Full workdir path: {0}", outputDirectory);
                    //Generate MapRegions for modified maps and render all new maps
                    async Task <RenderResult> DiffAndRenderNewMap(int I)
                    {
                        await dirPrepTask.ConfigureAwait(false);

                        var originalPath = currentIOManager.ConcatPath(repoPath, changedDmms[I]);

                        if (!await currentIOManager.FileExists(originalPath, cancellationToken).ConfigureAwait(false))
                        {
                            logger.LogTrace("No new map for path {0} exists, skipping region detection and after render", changedDmms[I]);
                            return(new RenderResult {
                                InputPath = changedDmms[I], ToolOutput = stringLocalizer["Map missing!"]
                            });
                        }
                        ToolResult result = null;

                        if (oldMapPaths[I] != null)
                        {
                            logger.LogTrace("Getting diff region for {0}...", changedDmms[I]);
                            result = await generator.GetDifferences(oldMapPaths[I], originalPath, cancellationToken).ConfigureAwait(false);

                            var region = result.MapRegion;
                            logger.LogTrace("Diff region for {0}: {1}", changedDmms[I], region);
                            if (region != null)
                            {
                                var       xdiam             = region.MaxX - region.MinX;
                                var       ydiam             = region.MaxY - region.MinY;
                                const int minDiffDimensions = 5 - 1;
                                if (xdiam < minDiffDimensions || ydiam < minDiffDimensions)
                                {
                                    //need to expand
                                    var fullResult = await generator.GetMapSize(originalPath, cancellationToken).ConfigureAwait(false);

                                    var fullRegion = fullResult.MapRegion;
                                    if (fullRegion == null)
                                    {
                                        //give up
                                        region = null;
                                    }
                                    else
                                    {
                                        bool increaseMax = true;
                                        if (xdiam < minDiffDimensions && ((fullRegion.MaxX - fullRegion.MinX) >= minDiffDimensions))
                                        {
                                            while ((region.MaxX - region.MinX) < minDiffDimensions)
                                            {
                                                if (increaseMax)
                                                {
                                                    region.MaxX = (short)Math.Min(region.MaxX + 1, fullRegion.MaxX);
                                                }
                                                else
                                                {
                                                    region.MinX = (short)Math.Max(region.MinX - 1, 1);
                                                }
                                                increaseMax = !increaseMax;
                                            }
                                        }
                                        if (ydiam < minDiffDimensions && ((fullRegion.MaxY - fullRegion.MinY) >= minDiffDimensions))
                                        {
                                            while ((region.MaxY - region.MinY) < minDiffDimensions)
                                            {
                                                if (increaseMax)
                                                {
                                                    region.MaxY = (short)Math.Min(region.MaxY + 1, fullRegion.MaxY);
                                                }
                                                else
                                                {
                                                    region.MinY = (short)Math.Max(region.MinY - 1, 1);
                                                }
                                                increaseMax = !increaseMax;
                                            }
                                        }
                                    }
                                    logger.LogTrace("Region for {0} expanded to {1}", changedDmms[I], region);
                                }
                                mapRegions[I] = region;
                            }
                        }
                        else
                        {
                            logger.LogTrace("Skipping region detection for {0} due to old map not existing", changedDmms[I]);
                        }
                        logger.LogTrace("Performing after rendering for {0}...", changedDmms[I]);
                        var renderResult = await generator.RenderMap(originalPath, mapRegions[I], outputDirectory, "after", cancellationToken).ConfigureAwait(false);

                        logger.LogTrace("After rendering for {0} complete! Result path: {1}, Output: {2}", changedDmms[I], renderResult.OutputPath, renderResult.ToolOutput);
                        if (result != null)
                        {
                            renderResult.ToolOutput = String.Format(CultureInfo.InvariantCulture, "Differences task:{0}{1}{0}Render task:{0}{2}", Environment.NewLine, result.ToolOutput, renderResult.ToolOutput);
                        }
                        return(renderResult);
                    };

                    logger.LogTrace("Running iterations of DiffAndRenderNewMap...");
                    //finish up before we go back to the base branch
                    afterRenderings = Enumerable.Range(0, changedDmms.Count).Select(I => DiffAndRenderNewMap(I)).ToList();
                    try
                    {
                        await Task.WhenAll(afterRenderings).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        logger.LogDebug(e, "After renderings produced exception!");
                        //at this point everything is done but some have failed
                        //we'll handle it later
                    }

                    logger.LogTrace("Moving HEAD back to pull request base...");
                    await repo.Checkout(pullRequest.Base.Sha, cancellationToken).ConfigureAwait(false);

                    Task <RenderResult> RenderOldMap(int i)
                    {
                        var oldPath = oldMapPaths[i];

                        if (oldMapPaths != null)
                        {
                            logger.LogTrace("Performing before rendering for {0}...", changedDmms[i]);
                            return(generator.RenderMap(oldPath, mapRegions[i], outputDirectory, "before", cancellationToken));
                        }
                        return(Task.FromResult(new RenderResult {
                            InputPath = changedDmms[i], ToolOutput = stringLocalizer["Map missing!"]
                        }));
                    }

                    logger.LogTrace("Running iterations of RenderOldMap...");
                    //finish up rendering
                    beforeRenderings = Enumerable.Range(0, changedDmms.Count).Select(I => RenderOldMap(I)).ToList();
                    try
                    {
                        await Task.WhenAll(beforeRenderings).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        logger.LogDebug(e, "Before renderings produced exception!");
                        //see above
                    }

                    //done with the repo at this point
                    logger.LogTrace("Renderings complete. Releasing reposiotory");
                }

                //collect results and errors
                async Task <KeyValuePair <MapDiff, MapRegion> > GetResult(int i)
                {
                    var beforeTask = beforeRenderings[i];
                    var afterTask  = afterRenderings[i];

                    var result = new MapDiff
                    {
                        InstallationRepositoryId = pullRequest.Base.Repository.Id,
                        PullRequestNumber        = pullRequest.Number,
                        FileId = i,
                    };

                    RenderResult GetRenderingResult(Task <RenderResult> task)
                    {
                        if (task.Exception != null)
                        {
                            result.LogMessage = result.LogMessage == null?task.Exception.ToString() : String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", result.LogMessage, Environment.NewLine, task.Exception);

                            return(null);
                        }
                        return(task.Result);
                    };

                    var r1 = GetRenderingResult(beforeTask);
                    var r2 = GetRenderingResult(afterTask);

                    logger.LogTrace("Results for {0}: Before {1}, After {2}", changedDmms[i], r1?.OutputPath ?? "NONE", r2?.OutputPath ?? "NONE");

                    result.MapPath = changedDmms[i];

                    result.LogMessage = String.Format(CultureInfo.InvariantCulture, "Job {5}:{0}Path: {6}{0}Before:{0}Command Line: {1}{0}Output:{0}{2}{0}Logs:{0}{7}{0}After:{0}Command Line: {3}{0}Output:{0}{4}{0}Logs:{0}{8}{0}Exceptions:{0}{9}{0}", Environment.NewLine, r1?.CommandLine, r1?.OutputPath, r2?.CommandLine, r2?.OutputPath, i + 1, result.MapPath, r1?.ToolOutput, r2?.ToolOutput, result.LogMessage);

                    async Task <byte[]> ReadMapImage(string path)
                    {
                        if (path != null && await currentIOManager.FileExists(path, cancellationToken).ConfigureAwait(false))
                        {
                            var bytes = await currentIOManager.ReadAllBytes(path, cancellationToken).ConfigureAwait(false);

                            await currentIOManager.DeleteFile(path, cancellationToken).ConfigureAwait(false);

                            return(bytes);
                        }
                        return(null);
                    }

                    var readBeforeTask = ReadMapImage(r1?.OutputPath);

                    result.AfterImage = await ReadMapImage(r2?.OutputPath).ConfigureAwait(false);

                    result.BeforeImage = await readBeforeTask.ConfigureAwait(false);

                    return(new KeyValuePair <MapDiff, MapRegion>(result, r2?.MapRegion));
                }

                logger.LogTrace("Waiting for notification comment to POST...");
                await generatingCommentTask.ConfigureAwait(false);

                logger.LogTrace("Collecting results...");
                var results = Enumerable.Range(0, changedDmms.Count).Select(x => GetResult(x)).ToList();
                await Task.WhenAll(results).ConfigureAwait(false);

                var dic = new Dictionary <MapDiff, MapRegion>();
                foreach (var I in results.Select(x => x.Result))
                {
                    dic.Add(I.Key, I.Value);
                }
                await HandleResults(pullRequest, dic, cancellationToken).ConfigureAwait(false);
            }
        }
        private bool IsPullRequestValid(PullRequest pullRequest)
        {
            var consumerGroup = _consumerManager.GetConsumerGroup(pullRequest.PullMessageRequest.ConsumerGroup);

            return(consumerGroup != null && consumerGroup.IsConsumerActive(pullRequest.RequestHandlerContext.Connection.RemotingEndPoint.ToString()));
        }
Exemplo n.º 9
0
        private TimeSpan GetPullRequestActiveTime(PullRequest pr)
        {
            var completedDate = pr.State != PullRequestState.Active ? pr.Completed : DateTime.UtcNow;

            return(completedDate - pr.Created);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Create a route to the <see cref="Browse(long, int, CancellationToken)"/> page for a given <paramref name="pullRequest"/>
 /// </summary>
 /// <param name="pullRequest">The <see cref="PullRequest"/></param>
 /// <returns>A relative url to the appropriate <see cref="FilesController"/> action</returns>
 public static string RouteToBrowse(PullRequest pullRequest) => String.Format(CultureInfo.InvariantCulture, "/{2}/{0}/{1}", pullRequest.Base.Repository.Id, pullRequest.Number, Route);
Exemplo n.º 11
0
 /// <summary>
 /// Create a route for a <paramref name="pullRequest"/> diff image
 /// </summary>
 /// <param name="pullRequest">The <see cref="PullRequest"/></param>
 /// <param name="fileId">The <see cref="MapDiff.FileId"/></param>
 /// <param name="postfix">Either "before", "after" or "logs"</param>
 /// <returns>A relative url to the appropriate <see cref="FilesController"/> action</returns>
 public static string RouteTo(PullRequest pullRequest, int fileId, string postfix) => String.Format(CultureInfo.InvariantCulture, "/{5}/{0}/{1}/{2}/{3}.{4}", pullRequest.Base.Repository.Id, pullRequest.Number, fileId, postfix, postfix == "logs" ? "txt" : "png", Route);
Exemplo n.º 12
0
 public PullRequestViewModel(PullRequest pr)
 {
     Title    = pr.Title;
     MergedAt = pr.MergedAt;
     Url      = pr.HtmlUrl;
 }
Exemplo n.º 13
0
 public PullRequestCacheItem(PullRequest pr)
     : this(pr, new PullRequestFile[0], new IssueComment[0], new PullRequestReviewComment[0])
 {
 }
Exemplo n.º 14
0
 public static PullRequestCacheItem Create(PullRequest pr)
 {
     return(new PullRequestCacheItem(pr, new PullRequestFile[0], new IssueComment[0], new PullRequestReviewComment[0]));
 }
Exemplo n.º 15
0
 public override int Count(PullRequest prDetails)
 => GetWordCounts(prDetails).Sum();
Exemplo n.º 16
0
        /// <inheritdoc />
        public async Task <IReadOnlyList <PullRequestFile> > GetPullRequestChangedFiles(PullRequest pullRequest, CancellationToken cancellationToken)
        {
            if (pullRequest == null)
            {
                throw new ArgumentNullException(nameof(pullRequest));
            }
            logger.LogTrace("Get changed files for {0}/{1} #{2}", pullRequest.Base.Repository.Owner.Login, pullRequest.Base.Repository.Name, pullRequest.Number);
            var gitHubClient = await CreateInstallationClient(pullRequest.Base.Repository.Id, cancellationToken).ConfigureAwait(false);

            return(await gitHubClient.PullRequest.Files(pullRequest.Base.Repository.Id, pullRequest.Number).ConfigureAwait(false));
        }
Exemplo n.º 17
0
        /// <inheritdoc />
        public async Task <AutoMergeStatus> EvaluateFor(PullRequest pullRequest, CancellationToken cancellationToken)
        {
            if (gitHubManager == null)
            {
                throw new InvalidOperationException("Configure() wasn't called!");
            }

            var reviews = await gitHubManager.GetPullRequestReviews(pullRequest).ConfigureAwait(false);

            var approvers = new List <User>();
            var critics   = new List <User>();

            var userCheckups = new Dictionary <string, Task <bool> >();

            foreach (var I in reviews)
            {
                void CheckupUser()
                {
                    if (!userCheckups.ContainsKey(I.User.Login))
                    {
                        userCheckups.Add(I.User.Login, gitHubManager.UserHasWriteAccess(I.User));
                    }
                }

                if (I.State.Value == PullRequestReviewState.Approved)
                {
                    critics.RemoveAll(x => x.Id == I.User.Id);
                    approvers.Add(I.User);
                    CheckupUser();
                }
                else if (I.State.Value == PullRequestReviewState.ChangesRequested)
                {
                    approvers.RemoveAll(x => x.Id == I.User.Id);
                    critics.Add(I.User);
                    CheckupUser();
                }
            }

            var result = new AutoMergeStatus();

            await Task.WhenAll(userCheckups.Select(x => x.Value)).ConfigureAwait(false);

            foreach (var I in approvers)
            {
                if (!userCheckups[I.Login].Result)
                {
                    continue;
                }

                ++result.Progress;
                result.Notes.Add(stringLocalizer["ApprovedBy", I.Login]);
            }

            if (result.Progress == 0)
            {
                result.Notes.Add(stringLocalizer["NoApproval"]);
            }

            result.RequiredProgress = result.Progress;

            foreach (var I in critics)
            {
                if (!userCheckups[I.Login].Result)
                {
                    continue;
                }

                ++result.RequiredProgress;
                result.Notes.Add(stringLocalizer["RequestedChanges", I.Login]);
            }

            result.RequiredProgress = Math.Max(result.RequiredProgress, 1);

            return(result);
        }
Exemplo n.º 18
0
 private void SendRemotingResponse(PullRequest pullRequest, RemotingResponse remotingResponse)
 {
     pullRequest.RequestHandlerContext.SendRemotingResponse(remotingResponse);
 }
Exemplo n.º 19
0
        internal PullRequest PutPullRequest(string accountName, string repository, PullRequest pullRequest)
        {
            var overrideUrl = GetRepositoryUrl(accountName, repository, "pullrequests/");

            return(_sharpBucketV2.Put(pullRequest, overrideUrl));
        }
Exemplo n.º 20
0
 /// <inheritdoc />
 public void ProcessPullRequest(PullRequest pullRequest) => backgroundJobClient.Enqueue(() => ScanPullRequest(pullRequest.Base.Repository.Id, pullRequest.Number, JobCancellationToken.Null));
Exemplo n.º 21
0
        public PullRequestDataModel()
        {
            PullRequest = new PullRequest
            {
                User = new User
                {
                    Login     = "******",
                    AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                },
                Body      = "Look at my nice PR!",
                Additions = 468,
                Deletions = 352,
                Commits   = 8,
                State     = "Open"
            };

            CommentsRequest = new StubPaginatedRequest <Comment>
            {
                Result = new List <Comment>
                {
                    new Comment
                    {
                        Body = "My comment is nice ! My comment is nice ! My comment is nice ! My comment is nice ! My comment is nice ! My comment is nice ! My comment is nice ! My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    },
                    new Comment
                    {
                        Body = "My comment is nice !",
                        User = new User
                        {
                            Login     = "******",
                            AvatarUrl = "https://secure.gravatar.com/avatar/5c4663b12b9e6d8dc6dcdfbfb3dc1317",
                        },
                        UpdatedAt = DateTime.Now,
                    }
                }
            };

            CanComment      = false;
            MinimizeAppBar  = true;
            RepoName        = "michelsalib/gi7";
            PullRequestName = "Pull Request #01";
        }
Exemplo n.º 22
0
        public async Task <WopResult> GoOptimize(bool cleanupAfterwards, Repository repository, string branchName = null)
        {
            var repositoryOwner = repository.Owner.Login;
            var repositoryName  = repository.Name;

            var myUser = await _gitOctoKitHandler.GitHubClient.User.Current();

            await _git.ConfigureGitCredentials();

            Console.WriteLine($"{repositoryOwner}/{repositoryName} is being optimized...");
            Console.WriteLine();

            string dirOfClonedRepos = _wopConfig.ClonedRepositoriesDirectoryName;

            if (!Path.IsPathRooted(dirOfClonedRepos))
            {
                dirOfClonedRepos = Path.Combine(FolderHelperMethods.Internal_AssemblyDirectory.Value, _wopConfig.ClonedRepositoriesDirectoryName);
            }

            Directory.CreateDirectory(dirOfClonedRepos);
            Directory.SetCurrentDirectory(dirOfClonedRepos);

            var clonedRepo = await _git.GitClone(dirOfClonedRepos, repositoryOwner, repositoryName);

            Directory.SetCurrentDirectory(clonedRepo);

            try
            {
                var repositoryInfo = await _gitOctoKitHandler.GitHubClient.Repository.Get(repositoryOwner, repositoryName);

                if (branchName == null)
                {
                    branchName = repositoryInfo.DefaultBranch;
                    if (branchName == null)
                    {
                        throw new Exception("ERROR, couldn't determine branchname");
                    }
                }

                await _git.RunHubCommand("fork");

                await _git.RunHubCommand($"remote set-url {_wopConfig.GitHubUserName} https://github.com/{_wopConfig.GitHubUserName}/{repositoryName}.git");

                //Fetch everything in my repository
                await _git.RunHubCommand("fetch --all");

                //Go to master
                await _git.RunHubCommand($"checkout {_wopConfig.GitHubUserName}/{branchName}");

                await _git.RunHubCommand($"merge --strategy-option=theirs origin/{branchName}");

                await _git.RunHubCommand($"push {_wopConfig.GitHubUserName} HEAD:{branchName}");

                var wasAbleToAddTrackedBranch = await _git.RunHubCommand($"checkout --track -b {Constants.FeatureName} {_wopConfig.GitHubUserName}/{Constants.FeatureName}");

                if (wasAbleToAddTrackedBranch.ExitCode == 0)
                {
                    await _git.RunHubCommand($"merge --strategy-option=theirs {_wopConfig.GitHubUserName}/{branchName}");

                    await _git.RunHubCommand($"push {_wopConfig.GitHubUserName} {Constants.FeatureName} -u");
                }
                else
                {
                    var createdNewBranch = await _git.RunHubCommand($"checkout -b {Constants.FeatureName}");

                    if (createdNewBranch.ExitCode == 0)
                    {
                    }
                    else
                    {
                        await _git.RunHubCommand($"checkout {Constants.FeatureName}");

                        await _git.RunHubCommand($"merge --strategy-option=theirs {_wopConfig.GitHubUserName}/{branchName}");
                    }
                    await _git.RunHubCommand($"push {_wopConfig.GitHubUserName} {Constants.FeatureName} -u");
                }

                var optimizedFileResults = await GoOptimize(clonedRepo, _wopConfig);

                //var optimizedFileResults = await GoOptimizeStub(clonedRepo, config);

                await _git.RunHubCommand("add .");

                var descriptionForCommit = TemplatesHandler.GetDescriptionForCommit();
                await _git.Commit("Wop optimized this repository", descriptionForCommit);

                await _git.RunHubCommand($"push");

                var descriptionForPullRequest = TemplatesHandler.GetDescriptionForPullRequest();

                var successfulOptimizations = optimizedFileResults.Any(t => t.OptimizationResult == OptimizationResult.Success && t.OriginalSize > t.OptimizedSize);

                var retval = new WopResult()
                {
                    OptimizedFiles = optimizedFileResults
                };

                //Only create pull request if there were actually any successful optimizations
                if (successfulOptimizations)
                {
                    PullRequest obtainedPullRequest = await _gitOctoKitHandler.GetPullRequest(repositoryOwner, repositoryName);

                    if (obtainedPullRequest == null)
                    {
                        var pr = new NewPullRequest("The Web Optimization Project has optimized your repository!", $"{_wopConfig.GitHubUserName}:{Constants.FeatureName}", branchName)
                        {
                            Body = descriptionForPullRequest
                        };
                        obtainedPullRequest = await _gitOctoKitHandler.GitHubClient.PullRequest.Create(repositoryOwner, repositoryName, pr);
                    }
                    Console.WriteLine($"Using PR: {obtainedPullRequest.Url}");

                    var descriptionForCommitInPr = TemplatesHandler.GetCommitDescriptionForPullRequest(clonedRepo, branchName, optimizedFileResults, DateTime.UtcNow.ToString());
                    Console.WriteLine($"Creating comment on pr with length {descriptionForCommitInPr.Length}...");
                    var createdComment = await _gitOctoKitHandler.GitHubClient.Issue.Comment.Create(repositoryOwner, repositoryName, obtainedPullRequest.Number, descriptionForCommitInPr);

                    Console.WriteLine($"Comment created: {createdComment.Url}");

                    retval.CreatedPullRequest = obtainedPullRequest;
                }

                Console.WriteLine();
                Console.WriteLine($"{repositoryOwner}/{repositoryName} is optimized :)");
                Console.WriteLine();

                return(retval);
            }
            finally
            {
                if (cleanupAfterwards)
                {
                    Console.WriteLine($"Cleaning up local files '{clonedRepo}'...");
                    Directory.SetCurrentDirectory(dirOfClonedRepos);
                    CleanupRecursively(clonedRepo);
                    //Directory.Delete(clonedRepo, true);
                    Console.WriteLine($"Directory {clonedRepo} removed.");
                }
            }
        }
Exemplo n.º 23
0
 // [Kooboo.Attributes.RequireParameters("SiteId", "LastId")]
 public SyncObject SendToClient(long LastId, Guid SiteId, ApiCall call)
 {
     return(PullRequest.PullNext(call.WebSite.SiteDb(), LastId));
 }
        public async Task ArcadeSdkUpdate()
        {
            string testChannelName   = "Test Channel " + _random.Next(int.MaxValue);
            var    sourceRepo        = "arcade";
            var    sourceRepoUri     = "https://github.com/dotnet/arcade";
            var    sourceBranch      = "dependencyflow-tests";
            var    sourceCommit      = "0b36b99e29b1751403e23cfad0a7dff585818051";
            var    sourceBuildNumber = _random.Next(int.MaxValue).ToString();
            ImmutableList <AssetData> sourceAssets = ImmutableList.Create <AssetData>()
                                                     .Add(new AssetData(true)
            {
                Name    = "Microsoft.DotNet.Arcade.Sdk",
                Version = "2.1.0",
            });
            var targetRepo   = "maestro-test2";
            var targetBranch = _random.Next(int.MaxValue).ToString();

            await using AsyncDisposableValue <string> channel = await CreateTestChannelAsync(testChannelName).ConfigureAwait(false);

            await using AsyncDisposableValue <string> sub = await CreateSubscriptionAsync(testChannelName, sourceRepo, targetRepo, targetBranch, "none");

            Build build = await CreateBuildAsync(GetRepoUrl("dotnet", sourceRepo), sourceBranch, sourceCommit, sourceBuildNumber, sourceAssets);

            await using IAsyncDisposable _ = await AddBuildToChannelAsync(build.Id, testChannelName);

            using TemporaryDirectory repo = await CloneRepositoryAsync(targetRepo);

            using (ChangeDirectory(repo.Directory))
            {
                await RunGitAsync("checkout", "-b", targetBranch).ConfigureAwait(false);
                await RunDarcAsync("add-dependency",
                                   "--name", "Microsoft.DotNet.Arcade.Sdk",
                                   "--type", "toolset",
                                   "--repo", sourceRepoUri);
                await RunGitAsync("commit", "-am", "Add dependencies.");

                await using IAsyncDisposable ___ = await PushGitBranchAsync("origin", targetBranch);
                await TriggerSubscriptionAsync(sub.Value);

                PullRequest pr = await WaitForPullRequestAsync(targetRepo, targetBranch);

                StringAssert.AreEqualIgnoringCase($"[{targetBranch}] Update dependencies from dotnet/arcade", pr.Title);

                await CheckoutRemoteRefAsync(pr.MergeCommitSha);

                string dependencies = await RunDarcAsync("get-dependencies");

                string[] dependencyLines = dependencies.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                Assert.AreEqual(new[]
                {
                    "Name:             Microsoft.DotNet.Arcade.Sdk",
                    "Version:          2.1.0",
                    $"Repo:             {sourceRepoUri}",
                    $"Commit:           {sourceCommit}",
                    "Type:             Toolset",
                    "Pinned:           False",
                }, dependencyLines);

                using TemporaryDirectory arcadeRepo = await CloneRepositoryAsync("dotnet", sourceRepo);

                using (ChangeDirectory(arcadeRepo.Directory))
                {
                    await CheckoutRemoteRefAsync(sourceCommit);
                }

                var arcadeFiles = Directory.EnumerateFileSystemEntries(Path.Join(arcadeRepo.Directory, "eng", "common"),
                                                                       "*", SearchOption.AllDirectories)
                                  .Select(s => s.Substring(arcadeRepo.Directory.Length))
                                  .ToHashSet();
                var repoFiles = Directory.EnumerateFileSystemEntries(Path.Join(repo.Directory, "eng", "common"), "*",
                                                                     SearchOption.AllDirectories)
                                .Select(s => s.Substring(repo.Directory.Length))
                                .ToHashSet();

                Assert.IsEmpty(arcadeFiles.Except(repoFiles));
                Assert.IsEmpty(repoFiles.Except(arcadeFiles));
            }
        }
Exemplo n.º 25
0
 public static PullRequestCacheItem Create(PullRequest pr, IReadOnlyList <PullRequestFile> files)
 {
     return(new PullRequestCacheItem(pr, files));
 }
Exemplo n.º 26
0
 public static PullRequestCacheItem Create(PullRequest pr)
 {
     return(new PullRequestCacheItem(pr));
 }
Exemplo n.º 27
0
 public PullRequestCacheItem(PullRequest pr)
     : this(pr, new PullRequestFile[0])
 {
 }
 /// <inheritdoc />
 public Task AddViewVars(PullRequest pullRequest, dynamic viewBag, CancellationToken cancellationToken) => Task.CompletedTask;
Exemplo n.º 29
0
        private static void TestRestRepositoriesEndPoint(SharpBucketV2 sharpBucket)
        {
            var repositoriesEndPoint = sharpBucket.RepositoriesEndPoint();
            var repositories         = repositoriesEndPoint.ListRepositories(accountName);
            var publicRepositories   = repositoriesEndPoint.ListPublicRepositories();
            var repositoryResource   = repositoriesEndPoint.RepositoryResource(accountName, repository);
            //var repoInfo = new RepositoryInfo();
            //var newRepository = repositoriesEndPoint.PutRepository(repo, accountName, repository);
            //var deletedRepository = repositoriesEndPoint.DeleteRepository(newRepository, accountName, repository);
            var    watchers          = repositoryResource.ListWatchers();
            var    forks             = repositoryResource.ListForks();
            var    branchRestictions = repositoryResource.ListBranchRestrictions();
            var    newRestrictions   = repositoryResource.PostBranchRestriction(new BranchRestriction());
            int    restrictionId     = 1;
            var    restriction       = repositoryResource.GetBranchRestriction(restrictionId);
            var    newRestiction     = repositoryResource.PutBranchRestriction(new BranchRestriction());
            var    deletedRestiction = repositoryResource.DeleteBranchRestriction(restrictionId);
            var    diff           = repositoryResource.GetDiff(null);
            var    patch          = repositoryResource.GetPatch(null);
            var    commits        = repositoryResource.ListCommits();
            string commitId       = "sdfsdf";
            var    commit         = repositoryResource.GetCommit(commitId);
            var    commitComments = repositoryResource.ListCommitComments(commitId);
            int    commentId      = 10;
            var    commitComment  = repositoryResource.GetCommitComment(commitId, commentId);
            var    commitApproval = repositoryResource.ApproveCommit(commitId);
            var    deleteApproval = repositoryResource.DeleteCommitApproval(commitId);

            var targetUsername  = "";
            var defaultReviewer = repositoryResource.PutDefaultReviewer(targetUsername);

            var r               = repositoriesEndPoint.RepositoryResource(accountName, repository);
            var dr              = r.DeleteRepository();
            var w               = r.ListWatchers();
            var f               = r.ListForks();
            var br              = r.ListBranchRestrictions();
            var gr              = r.GetBranchRestriction(restrictionId);
            var nr              = r.PostBranchRestriction(new BranchRestriction());
            var dbr             = r.DeleteBranchRestriction(restrictionId);
            var diff2           = r.GetDiff(new object());
            var patch2          = r.GetPatch(new object());
            var commits2        = r.ListCommits();
            var commit2         = r.GetCommit(commitId);
            var commitComments2 = r.ListCommitComments(commitId);
            var commitComment2  = r.GetCommitComment(commitId, commentId);
            var commitApproval2 = r.ApproveCommit(commitId);
            var deleteApproval2 = r.DeleteCommitApproval(commitId);

            var pullRequestsResource = r.PullRequestsResource();
            var pullRequests         = pullRequestsResource.ListPullRequests();
            var source = new Source
            {
                branch = new Branch {
                    name = "develop"
                },
                repository = new Repository
                {
                    full_name = repository
                }
            };
            var destination = new Source
            {
                branch = new Branch {
                    name = "master"
                },
                commit = new Commit {
                    hash = "56c3aca"
                }
            };
            var newRequest = new PullRequest
            {
                title       = "testing new one",
                description = "My new description",
                source      = source,
                destination = destination
            };
            //var newPullRequest = repositoriesEndPoint.PostPullRequest(accountName, repository, newRequest);
            //var updatedPullRequest = repositoriesEndPoint.PutPullRequest(accountName, repository, new PullRequest());
            //var pullRequestId = 1;
            //var pullRequest = repositoriesEndPoint.GetPullRequest(accountName, repository, pullRequestId);
            //pullRequest.title = "HEHEHEH";
            //var updatedPullRequest = repositoriesEndPoint.PutPullRequest(accountName, repository, pullRequest);

            //var commitsInPullRequest = repositoriesEndPoint.ListPullRequestCommits(accountName, repository, pullRequestId);
            //var postPullRequestApproval = repositoriesEndPoint.ApprovePullRequest(accountName, repository, pullRequestId);
            //var deletePullRequest = repositoriesEndPoint.RemovePullRequestApproval(accountName, repository, pullRequestId);
            //var getDiffForPullRequest = repositoriesEndPoint.GetDiffForPullRequest(accountName, repository, pullRequestId);
            //var pullRequestLog = repositoriesEndPoint.GetPullRequestLog(accountName, repository);
            //var pullRequestActivity = repositoriesEndPoint.GetPullRequestActivity(accountName, repository, pullRequestId);
            //var acceptPullRequest = repositoriesEndPoint.AcceptAndMergePullRequest(accountName, repository, pullRequestId);
            //var declinePullRequest = repositoriesEndPoint.DeclinePullRequest(accountName, repository, pullRequestId);
            //var pullRequestComments = repositoriesEndPoint.ListPullRequestComments(accountName, repository, pullRequestId);
            //var commentId = 10;
            //var pullRequestComment = repositoriesEndPoint.GetPullRequestComment(accountName, repository, pullRequestId, commentId);

            //var pullRequestsEP = repositoriesEndPoint.PullReqestsResource(accountName, repository);
            //var PRs = pullRequestsEP.ListPullRequests();
            //var newPR = pullRequestsEP.PostPullRequest(new PullRequest());
            //var updatedPR = pullRequestsEP.PutPullRequest(new PullRequest());
            //var PRId = 10;
            //var PR = pullRequestsEP.GetPullRequest(PRId);
            //var commitsInPR = pullRequestsEP.ListPullRequestCommits(PRId);
            //var postPRApproval = pullRequestsEP.ApprovePullRequest(PRId);
            //var deletePR = pullRequestsEP.RemovePullRequestApproval(PRId);
            //var getDiffForPR = pullRequestsEP.GetDiffForPullRequest(PRId);
            //var PRLog = pullRequestsEP.GetPullRequestLog();
            //var PRActivity = pullRequestsEP.GetPullRequestActivity(PRId);
            //var acceptPR = pullRequestsEP.AcceptAndMergePullRequest(PRId);
            //var declinePR = pullRequestsEP.DeclinePullRequest(PRId);
            //var PRComments = pullRequestsEP.ListPullRequestComments(PRId);
            //var cId = 10;
            //var PRComment = pullRequestsEP.GetPullRequestComment(PRId, cId);

            //var PRId2 = 10;
            //var pullRequestEP = pullRequestsEP.PullRequestEndPoint(PRId);
            //var PR2 = pullRequestEP.GetPullRequest();
            //var commitsInPR2 = pullRequestEP.ListPullRequestCommits();
            //var postPR2Approval = pullRequestEP.ApprovePullRequest();
            //var deletePR2 = pullRequestEP.RemovePullRequestApproval();
            //var getDiffForPR2 = pullRequestEP.GetDiffForPullRequest();
            //var PR2Activity = pullRequestEP.GetPullRequestActivity();
            //var acceptPR2 = pullRequestEP.AcceptAndMergePullRequest();
            //var declinePR2 = pullRequestEP.DeclinePullRequest();
            //var PR2Comments = pullRequestEP.ListPullRequestComments();
            //var cId2 = 10;
            //var PR2Comment = pullRequestEP.GetPullRequestComment(cId2);

            var branchResource = repositoriesEndPoint.BranchResource(accountName, repository);
            var branches       = branchResource.ListBranches();

            var tagResource = repositoriesEndPoint.TagResource(accountName, repository);
            var tags        = tagResource.ListTags();
        }
Exemplo n.º 30
0
 public GithubPullRequest(PullRequest pullrequest)
 {
     this.pullrequest = pullrequest;
 }
Exemplo n.º 31
0
 public GitHubPullRequestDiscussion(PullRequest pullRequest)
 {
     _pullRequest = pullRequest;
     Entries      = new List <IDiscussionEntry>();
     ForceReload();
 }