Skip to content

Commit

Permalink
chore: finished configurable pr functionality and added documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
GrigoreMihai committed Oct 18, 2021
1 parent 138a671 commit 1bba836
Show file tree
Hide file tree
Showing 10 changed files with 164 additions and 85 deletions.
4 changes: 1 addition & 3 deletions Common/RepoConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ public class RepoConfiguration

public string PrBody { get; set; }

public string Labels { get; set; }

public bool? PrDetails { get; set; }
// public string Labels { get; set; } TODO: add when having the labels feature
}
}
2 changes: 0 additions & 2 deletions Common/TableModels/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,5 @@ public Settings(string installationId, string repoName)
public string PrTitle { get; set; }

public string Labels { get; set; }

public bool? PrDetails { get; set; }
}
}
74 changes: 36 additions & 38 deletions CompressImagesFunction/CompressImages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,38 +29,6 @@ public static class CompressImages
new GifsicleCompress(),
};

private static bool PaidPlan (CloudStorageAccount storageAccount, string ownerLogin)
{
var marketplaceTable = storageAccount.CreateCloudTableClient().GetTableReference("marketplace");
var paidPlans = KnownGitHubs.Plans.Keys.Where(k => KnownGitHubs.Plans[k] != 0);
string plansQuery = string.Empty;
string needsOr = string.Empty;
if (paidPlans.Count() > 0)
{
needsOr = " or ";
}

int i = 0;
foreach (int planId in paidPlans)
{
plansQuery += "PlanId eq " + planId.ToString();
if (i != paidPlans.Count() - 1)
{
plansQuery += needsOr;
}

i++;
}

var query = new TableQuery<Marketplace>().Where(
$"AccountLogin eq '{ownerLogin}' and ({plansQuery})");

var rows = marketplaceTable.ExecuteQuerySegmentedAsync(query, null).Result;
var plan = rows.FirstOrDefault();

return plan != null;
}

public static bool Run(CompressimagesParameters parameters, ICollector<CompressImagesMessage> compressImagesMessages, ILogger logger)
{
var storageAccount = CloudStorageAccount.Parse(Common.KnownEnvironmentVariables.AzureWebJobsStorage);
Expand Down Expand Up @@ -135,21 +103,19 @@ public static bool Run(CompressimagesParameters parameters, ICollector<CompressI
{
repoConfiguration = JsonConvert.DeserializeObject<RepoConfiguration>(repoConfigJson);

if (paidPlan && (repoConfiguration.PrBody != null || repoConfiguration.PrTitle != null || repoConfiguration.Labels.Any() || repoConfiguration.PrDetails != null))
// for now we are not adding the labels functionality || repoConfiguration.Labels.Any() TODO: add it when adding the labels feature
if (paidPlan && (repoConfiguration.PrBody != null || repoConfiguration.PrTitle != null))
{
var settingsTable = storageAccount.CreateCloudTableClient().GetTableReference("settings");

// Labels = repoConfiguration.Labels TODO: add it when adding the labels feature
var settings = new Common.TableModels.Settings(
parameters.CompressImagesMessage.InstallationId.ToString(),
parameters.CompressImagesMessage.RepoName)
{
PrBody = repoConfiguration.PrBody,
PrTitle = repoConfiguration.PrTitle,
Labels = repoConfiguration.Labels,
};
if (repoConfiguration.PrDetails != null)
{
settings.PrDetails = repoConfiguration.PrDetails;
}

settingsTable.ExecuteAsync(TableOperation.InsertOrReplace(settings)).Wait();
}
Expand Down Expand Up @@ -422,5 +388,37 @@ private static CompressionResult[] OptimizeImages(Repository repo, string localP
logger.LogInformation("Compressed {NumImages}", optimizedImages.Count);
return optimizedImages.ToArray();
}

private static bool PaidPlan(CloudStorageAccount storageAccount, string ownerLogin)
{
var marketplaceTable = storageAccount.CreateCloudTableClient().GetTableReference("marketplace");
var paidPlans = KnownGitHubs.Plans.Keys.Where(k => KnownGitHubs.Plans[k] != 0);
string plansQuery = string.Empty;
string needsOr = string.Empty;
if (paidPlans.Count() > 0)
{
needsOr = " or ";
}

int i = 0;
foreach (int planId in paidPlans)
{
plansQuery += "PlanId eq " + planId.ToString();
if (i != paidPlans.Count() - 1)
{
plansQuery += needsOr;
}

i++;
}

var query = new TableQuery<Marketplace>().Where(
$"AccountLogin eq '{ownerLogin}' and ({plansQuery})");

var rows = marketplaceTable.ExecuteQuerySegmentedAsync(query, null).Result;
var plan = rows.FirstOrDefault();

return plan != null;
}
}
}
5 changes: 4 additions & 1 deletion Docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ Here is an example .imgbotconfig setup that shows some of the options.
],
"aggressiveCompression": "true", // true|false
"compressWiki": "true", // true|false
"minKBReduced": 500 // delay new prs until size reduction meets this threshold (default to 10)
"minKBReduced": 500, // delay new prs until size reduction meets this threshold (default to 10)
"prTitle" : "Your own pr title",
"prBody" : " Text before optimization ratio {optimization_ratio} Text after optimization ratio
Text before optimization details {optimization_details} Text after optimization details",
}
```

Expand Down
15 changes: 15 additions & 0 deletions Docs/pr-body.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
You can set a pull request body for your Imgbot PRs through the `.imgbotconfig` file.

- This configuration is optional and is only required if you want a custom body for your pr's
- Available only for paid plans
- Accepts any string written using github [markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
- The default pr body to display is the one from [here](https://imgbot.net/images/screen.png?cache=2)

`.imgbotconfig`

```
{
"prBody" : " Text before optimization ratio {optimization_ratio} Text after optimization ratio
Text before optimization details {optimization_details} Text after optimization details",
}
```
14 changes: 14 additions & 0 deletions Docs/pr-title.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
You can set a pull request title for your Imgbot PRs through the `.imgbotconfig` file.

- This configuration is optional and is only required if you want a custom title for your pr's
- Available only for paid plans
- Accepts any string written using github [markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
- The default title to display is: "[ImgBot] Optimize images"

`.imgbotconfig`

```
{
"prTitle": "My title"
}
```
93 changes: 55 additions & 38 deletions OpenPrFunction/PullRequestBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ public static class PullRequestBody
* Convert the ImageStat[] into a markdown PR body
*/
public static string Generate(ImageStat[] imageStats, Settings settings = null)
{
var prBody = BasicPr(imageStats, settings);

if (settings?.PrBody != null)
{
prBody = settings?.PrBody;
}

prBody = ReplacePrMagicTags(imageStats, prBody);
return prBody;
}

private static string BasicPr(ImageStat[] imageStats, Settings settings = null)
{
if (imageStats == null || imageStats.Length == 0)
{
Expand All @@ -18,28 +31,49 @@ public static string Generate(ImageStat[] imageStats, Settings settings = null)
}

var sb = new StringBuilder();
if (settings?.PrBody == null)
{
sb.AppendLine("## Beep boop. Your images are optimized!");
sb.AppendLine();
sb.AppendLine("## Beep boop. Your images are optimized!");
sb.AppendLine();
sb.AppendLine("{optimization_ratio}");
sb.AppendLine();
sb.AppendLine("{optimization_details}");

if (Math.Round(imageStats[0].Percent) < 5)
{
sb.AppendLine("Your image file size has been reduced!");
}
else
{
sb.AppendLine($"Your image file size has been reduced by **{imageStats[0].Percent:N0}%** 🎉");
}
sb.Append("[📝 docs](https://imgbot.net/docs) | ");
sb.Append("[:octocat: repo](https://github.com/imgbot/ImgBot) | ");
sb.Append("[🙋🏾 issues](https://github.com/imgbot/ImgBot/issues) | ");
sb.Append("[🏪 marketplace](https://github.com/marketplace/imgbot)");
sb.AppendLine();
sb.AppendLine();
sb.Append("<i>");
sb.Append("~Imgbot - Part of [Optimole](https://optimole.com/) family");
sb.Append("</i>");
sb.AppendLine();
return sb.ToString();
}

private static string ReplacePrMagicTags(ImageStat[] imageStats, string prBody)
{
if (imageStats == null || imageStats.Length == 0)
{
prBody = prBody.Replace("{optimization_ratio}", "Your image file size has been reduced!");
prBody = prBody.Replace("{optimization_details}", string.Empty);
return prBody;
}
else

if (prBody.Contains("{optimization_ratio}"))
{
sb.AppendLine(settings.PrBody);
var replace = "Your image file size has been reduced ";
if (Math.Round(imageStats[0].Percent) >= 5)
{
replace += $"by **{imageStats[0].Percent:N0}%** ";
}

replace += "🎉";
prBody = prBody.Replace("{optimization_ratio}", replace);
}

sb.AppendLine();
if (settings?.PrDetails != false)
if (prBody.Contains("{optimization_details}"))
{
var sb = new StringBuilder();
sb.AppendLine("<details>");

sb.AppendLine("<summary>");
Expand All @@ -52,45 +86,28 @@ public static string Generate(ImageStat[] imageStats, Settings settings = null)

if (imageStats.Length == 1)
{
sb.AppendLine(
$"| {imageStats[0].Name} | {imageStats[0].Before} | {imageStats[0].After} | {imageStats[0].Percent:N2}% |");
sb.AppendLine($"| {imageStats[0].Name} | {imageStats[0].Before} | {imageStats[0].After} | {imageStats[0].Percent:N2}% |");
}
else
{
// the zeroth item is the total; we print it at the bottom of the table
for (var i = 1; i < imageStats.Length; i++)
{
sb.AppendLine(
$"| {imageStats[i].Name} | {imageStats[i].Before} | {imageStats[i].After} | {imageStats[i].Percent:N2}% |");
sb.AppendLine($"| {imageStats[i].Name} | {imageStats[i].Before} | {imageStats[i].After} | {imageStats[i].Percent:N2}% |");
}

sb.AppendLine("| | | | |");
sb.AppendLine(
$"| **Total :** | **{imageStats[0].Before}** | **{imageStats[0].After}** | **{imageStats[0].Percent:N2}%** |");
sb.AppendLine($"| **Total :** | **{imageStats[0].Before}** | **{imageStats[0].After}** | **{imageStats[0].Percent:N2}%** |");
}

sb.AppendLine("</details>");
sb.AppendLine();
}

if (settings?.PrBody == null)
{
sb.AppendLine("---");
sb.AppendLine();
sb.Append("[📝 docs](https://imgbot.net/docs) | ");
sb.Append("[:octocat: repo](https://github.com/imgbot/ImgBot) | ");
sb.Append("[🙋🏾 issues](https://github.com/imgbot/ImgBot/issues) | ");
sb.Append("[🏪 marketplace](https://github.com/marketplace/imgbot)");

sb.AppendLine();
sb.AppendLine();
sb.Append("<i>");
sb.Append("~Imgbot - Part of [Optimole](https://optimole.com/) family");
sb.Append("</i>");
sb.AppendLine();
prBody = prBody.Replace("{optimization_details}", sb.ToString());
}

return sb.ToString();
return prBody;
}
}
}
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ This file should be placed in the root of the repository and set to your liking.
],
"aggressiveCompression": "true", // true|false
"compressWiki": "true", // true|false
"minKBReduced": 500 // set reduction threshold (default to 10)
"minKBReduced": 500 // set reduction threshold (default to 10),
"prTitle" : "Compressed images", // set pull request title
// set the pull request body, supports any valid github markdown
// {optimization_ratio} display a message containing the optimization ratio
// {optimization_details} display the table containing the optimization details
"prBody" : " Text before optimization ratio {optimization_ratio} Text after optimization ratio
Text before optimization details {optimization_details} Text after optimization details",
}
```

Expand Down Expand Up @@ -67,6 +74,26 @@ to help@imgbot.net
- Can be used to limit the frequency of PRs Imgbot will open over time
- The default setting is 10

**prTitle**

- Optional
- Available only for paid plans
- Accepts only strings as input (e.g. `"prTitle": "My title"`)
- Can be used to display any custom pull request title
- The default setting is "[ImgBot] Optimize images"

**prBody**

- Optional
- Available only for paid plans
- Accepts only strings as input
- (e.g. `"prBody": "Text before {optimization_ratio} Text after"` <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; `Text before {optimization_details} Text after"`)
- Can be used to display any custom pull request body, written using github [markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
- Supports two magic tags: `{optimization_ratio} //displays the mean optimization ratio for all images` <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; `{optimization_details} //display the optimization details for every images`
- The default setting generates the body displayed [here](https://imgbot.net/images/screen.png?cache=2)

Find out more: https://imgbot.net/docs

## Contributing
Expand Down
4 changes: 2 additions & 2 deletions Test/PullRequestBodyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void GivenZeroPercentReductionCommitMessage_ShouldOmitPercentage()

var expectedMarkdown = "## Beep boop. Your images are optimized!" + Environment.NewLine +
Environment.NewLine +
"Your image file size has been reduced!" + Environment.NewLine +
"Your image file size has been reduced 🎉" + Environment.NewLine +
Environment.NewLine +
"<details>" + Environment.NewLine +
"<summary>" + Environment.NewLine +
Expand Down Expand Up @@ -93,7 +93,7 @@ public void GivenReductionBelow5PercentCommitMessage_ShouldOmitPercentage()

var expectedMarkdown = "## Beep boop. Your images are optimized!" + Environment.NewLine +
Environment.NewLine +
"Your image file size has been reduced!" + Environment.NewLine +
"Your image file size has been reduced 🎉" + Environment.NewLine +
Environment.NewLine +
"<details>" + Environment.NewLine +
"<summary>" + Environment.NewLine +
Expand Down
9 changes: 9 additions & 0 deletions Web/src/docs/metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@
"slug": "min-kb-threshold",
"title": "Min KB threshold"
},
{
"slug": "pr-title",
"title": "Pull request title"
},
{
"slug": "pr-body",
"title": "Pull request body"
},

{
"slug": "authorization",
"title": "Authorization"
Expand Down

0 comments on commit 1bba836

Please sign in to comment.