Skip to content

Commit

Permalink
This should fix PR length issues
Browse files Browse the repository at this point in the history
  • Loading branch information
devedse committed Aug 1, 2020
1 parent f3b54a5 commit 20e052a
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 54 deletions.
34 changes: 34 additions & 0 deletions WebOptimizationProject.Tests/Helpers/TemplatesHandlerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using DeveImageOptimizer.State;
using System;
using System.Collections.Generic;
using WebOptimizationProject.Helpers;
using Xunit;

namespace WebOptimizationProject.Tests.Helpers
{
public class TemplatesHandlerTests
{
[Fact]
public void DoesNotCreateTemplateContentHigherThenMaxLength()
{
//Arrange
var fileList = new List<OptimizableFile>();

for (int i = 0; i < 10000; i++)
{
fileList.Add(new OptimizableFile("test2.png", "test2.png", 9000));
}

foreach (var file in fileList)
{
file.SetSuccess(50, TimeSpan.FromSeconds(5));
}

//Act
var result = TemplatesHandler.GetCommitDescriptionForPullRequest("coolPath", "coolBranch", fileList, "date");

//Assert
Assert.True(result.Length < Constants.MaxLengthPullRequestDescriptionAndComment);
}
}
}
1 change: 1 addition & 0 deletions WebOptimizationProject/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
public static class Constants
{
public const string FeatureName = "WebOptimizationProject";
public const int MaxLengthPullRequestDescriptionAndComment = 262144;
}
}
48 changes: 7 additions & 41 deletions WebOptimizationProject/GitHubRepositoryOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,56 +132,22 @@ public async Task GoOptimize(Repository repository, string branchName = null)
var descriptionForPullRequest = TemplatesHandler.GetDescriptionForPullRequest();

//Only create pull request if there were actually any successful optimizations
if (optimizedFileResults.Any(t => t.OptimizationResult == OptimizationResult.Success) && optimizedFileResults.Sum(t => t.OriginalSize) > optimizedFileResults.Sum(t => t.OptimizedSize))
if (optimizedFileResults.Any(t => t.OptimizationResult == OptimizationResult.Success && t.OriginalSize > t.OptimizedSize))
{
//var pullRequestState = await _git.PullRequest("The Web Optimization Project has optimized your repository!", descriptionForPullRequest);
//Console.WriteLine("Pullrequeststate: " + pullRequestState);


PullRequest obtainedPullRequest = await _gitOctoKitHandler.GetPullRequest(repositoryOwner, repositoryName);

int commitCount = 0;
var bodySb = new StringBuilder();



if (obtainedPullRequest == null)
{
bodySb.AppendLine(descriptionForPullRequest);
}
else
{
bodySb.AppendLine(obtainedPullRequest.Body);

Console.WriteLine($"Found pull request: {obtainedPullRequest.HtmlUrl}");
var commitIdentifier = "### Commit ";
var splittedBody = obtainedPullRequest.Body.Split('\n');
commitCount = splittedBody.Count(t => t.StartsWith(commitIdentifier));
}

var descriptionForCommitInPr = TemplatesHandler.GetCommitDescriptionForPullRequest(clonedRepo, branchName, optimizedFileResults, commitCount + 1);

bodySb.AppendLine();
bodySb.AppendLine();
bodySb.AppendLine(descriptionForCommitInPr);


if (obtainedPullRequest != null)
{
var pullRequestUpdate = new PullRequestUpdate()
{
Body = bodySb.ToString()
};
await _gitOctoKitHandler.GitHubClient.PullRequest.Update(repositoryOwner, repositoryName, obtainedPullRequest.Number, pullRequestUpdate);
}
else
{
var pr = new NewPullRequest("The Web Optimization Project has optimized your repository!", $"{_wopConfig.GitHubUserName}:{Constants.FeatureName}", branchName)
{
Body = bodySb.ToString()
Body = descriptionForPullRequest
};
await _gitOctoKitHandler.GitHubClient.PullRequest.Create(repositoryOwner, repositoryName, pr);
obtainedPullRequest = await _gitOctoKitHandler.GitHubClient.PullRequest.Create(repositoryOwner, repositoryName, pr);
}

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

Console.WriteLine();
Expand Down
47 changes: 37 additions & 10 deletions WebOptimizationProject/Helpers/TemplatesHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ public static string GetDescriptionForPullRequest()
return templateText;
}

public static string GetCommitDescriptionForPullRequest(string clonedRepoPath, string branchName, IEnumerable<OptimizableFile> optimizedFileResults, int commitNumber)
public static string GetCommitDescriptionForPullRequest(string clonedRepoPath, string branchName, IEnumerable<OptimizableFile> optimizedFileResults, string commitDate)
{
var templateText = Templates.CommitInPullRequestMarkdownTemplate;
var templateText = Templates.CommitInPullRequestMarkdownTemplate.Trim();

templateText = templateText.Replace("{CommitNumber}", commitNumber.ToString());
templateText = templateText.Replace("{CommitDate}", commitDate);
templateText = templateText.Replace("{SupportedFileExtensions}", string.Join(" ", ConstantsAndConfig.ValidExtensions));
templateText = templateText.Replace("{Version}", Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion.ToString());

Expand All @@ -54,12 +54,21 @@ public static string GetCommitDescriptionForPullRequest(string clonedRepoPath, s
templateText = templateText.Replace("{OptimizationDuration}", ValuesToStringHelper.SecondsToString((long)timeSpan.TotalSeconds));

var optimizedFilesTable = new StringBuilder();

optimizedFilesTable.AppendLine(templateText);
optimizedFilesTable.AppendLine();
optimizedFilesTable.AppendLine("FileName | Original Size | Optimized Size | Bytes Saved | Duration | Status");
optimizedFilesTable.AppendLine("-- | -- | -- | -- | -- | --");
var filesToPrint = optimizedFileResults.Where(t => t.OriginalSize > t.OptimizedSize || t.OptimizationResult == OptimizationResult.Failed).OrderByDescending(t => t.OriginalSize - t.OptimizedSize);
foreach (var fileResult in filesToPrint)
var filesToPrint = optimizedFileResults
//Don't list items that where skipped or did succeed but did not get optimized anything
.Where(t => (t.OptimizationResult == OptimizationResult.Success && t.OriginalSize > t.OptimizedSize) || t.OptimizationResult == OptimizationResult.Failed)
.OrderByDescending(t => t.OptimizationResult == OptimizationResult.Failed) //This ensures the Failed items come first
.ThenByDescending(t => t.OriginalSize - t.OptimizedSize)
.ToList();

for (int i = 0; i < filesToPrint.Count; i++)
{
var fileResult = filesToPrint[i];

//Reduce length of filename
string fileName = Path.GetFileName(fileResult.Path);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
Expand All @@ -79,12 +88,30 @@ public static string GetCommitDescriptionForPullRequest(string clonedRepoPath, s
var originalSize = ValuesToStringHelper.BytesToString(fileResult.OriginalSize);
var optimizedSize = ValuesToStringHelper.BytesToString(fileResult.OptimizedSize);
var bytesSaved = ValuesToStringHelper.BytesToString(fileResult.OriginalSize - fileResult.OptimizedSize);
optimizedFilesTable.AppendLine($"{fileName} | {originalSize} | {optimizedSize} | {bytesSaved} | {ValuesToStringHelper.SecondsToString((long)fileResult.Duration.TotalSeconds)} | {fileResult.OptimizationResult}");
}

templateText = templateText.Replace("{OptimizedFiles}", optimizedFilesTable.ToString());
var newLine = $"{fileName} | {originalSize} | {optimizedSize} | {bytesSaved} | {ValuesToStringHelper.SecondsToString((long)fileResult.Duration.TotalSeconds)} | {fileResult.OptimizationResult}{Environment.NewLine}";

return templateText;

var truncateMessage = "";
if (i < filesToPrint.Count - 1)
{
//Not the last item
truncateMessage = $"{Environment.NewLine}Remaining {filesToPrint.Count - i} items got truncated.";
}


if (optimizedFilesTable.Length + newLine.Length + truncateMessage.Length > Constants.MaxLengthPullRequestDescriptionAndComment)
{
optimizedFilesTable.Append(truncateMessage);
return optimizedFilesTable.ToString();
}
else
{
optimizedFilesTable.Append(newLine);
}
}

return optimizedFilesTable.ToString();
}

public static string GetDescriptionForCommit()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### Commit {CommitNumber}
### Commit {CommitDate}

Information | Value
-- | --
Expand All @@ -21,4 +21,4 @@ Time taken for optimization | {OptimizationDuration}

#### Files optimized in this repository

{OptimizedFiles}
(Files that couldn't be optimized any further are not listed here)
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ If you have any questions, feel free to create an issue or join the gitter chat:

The Web Optimization Project optimized this repository. All optimizations (compressions) are done losslessly and no quality / data is lost. This is also verified afterwards by the Wop so you can be sure that your images are exactly the same.

## Commits
Check the comments below to find out exactly what files where optimized :smile:

0 comments on commit 20e052a

Please sign in to comment.