Skip to content

Commit 1bba836

Browse files
committed
chore: finished configurable pr functionality and added documentation
1 parent 138a671 commit 1bba836

File tree

10 files changed

+164
-85
lines changed

10 files changed

+164
-85
lines changed

Common/RepoConfiguration.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ public class RepoConfiguration
1616

1717
public string PrBody { get; set; }
1818

19-
public string Labels { get; set; }
20-
21-
public bool? PrDetails { get; set; }
19+
// public string Labels { get; set; } TODO: add when having the labels feature
2220
}
2321
}

Common/TableModels/Settings.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,5 @@ public Settings(string installationId, string repoName)
2727
public string PrTitle { get; set; }
2828

2929
public string Labels { get; set; }
30-
31-
public bool? PrDetails { get; set; }
3230
}
3331
}

CompressImagesFunction/CompressImages.cs

Lines changed: 36 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -29,38 +29,6 @@ public static class CompressImages
2929
new GifsicleCompress(),
3030
};
3131

32-
private static bool PaidPlan (CloudStorageAccount storageAccount, string ownerLogin)
33-
{
34-
var marketplaceTable = storageAccount.CreateCloudTableClient().GetTableReference("marketplace");
35-
var paidPlans = KnownGitHubs.Plans.Keys.Where(k => KnownGitHubs.Plans[k] != 0);
36-
string plansQuery = string.Empty;
37-
string needsOr = string.Empty;
38-
if (paidPlans.Count() > 0)
39-
{
40-
needsOr = " or ";
41-
}
42-
43-
int i = 0;
44-
foreach (int planId in paidPlans)
45-
{
46-
plansQuery += "PlanId eq " + planId.ToString();
47-
if (i != paidPlans.Count() - 1)
48-
{
49-
plansQuery += needsOr;
50-
}
51-
52-
i++;
53-
}
54-
55-
var query = new TableQuery<Marketplace>().Where(
56-
$"AccountLogin eq '{ownerLogin}' and ({plansQuery})");
57-
58-
var rows = marketplaceTable.ExecuteQuerySegmentedAsync(query, null).Result;
59-
var plan = rows.FirstOrDefault();
60-
61-
return plan != null;
62-
}
63-
6432
public static bool Run(CompressimagesParameters parameters, ICollector<CompressImagesMessage> compressImagesMessages, ILogger logger)
6533
{
6634
var storageAccount = CloudStorageAccount.Parse(Common.KnownEnvironmentVariables.AzureWebJobsStorage);
@@ -135,21 +103,19 @@ public static bool Run(CompressimagesParameters parameters, ICollector<CompressI
135103
{
136104
repoConfiguration = JsonConvert.DeserializeObject<RepoConfiguration>(repoConfigJson);
137105

138-
if (paidPlan && (repoConfiguration.PrBody != null || repoConfiguration.PrTitle != null || repoConfiguration.Labels.Any() || repoConfiguration.PrDetails != null))
106+
// for now we are not adding the labels functionality || repoConfiguration.Labels.Any() TODO: add it when adding the labels feature
107+
if (paidPlan && (repoConfiguration.PrBody != null || repoConfiguration.PrTitle != null))
139108
{
140109
var settingsTable = storageAccount.CreateCloudTableClient().GetTableReference("settings");
110+
111+
// Labels = repoConfiguration.Labels TODO: add it when adding the labels feature
141112
var settings = new Common.TableModels.Settings(
142113
parameters.CompressImagesMessage.InstallationId.ToString(),
143114
parameters.CompressImagesMessage.RepoName)
144115
{
145116
PrBody = repoConfiguration.PrBody,
146117
PrTitle = repoConfiguration.PrTitle,
147-
Labels = repoConfiguration.Labels,
148118
};
149-
if (repoConfiguration.PrDetails != null)
150-
{
151-
settings.PrDetails = repoConfiguration.PrDetails;
152-
}
153119

154120
settingsTable.ExecuteAsync(TableOperation.InsertOrReplace(settings)).Wait();
155121
}
@@ -422,5 +388,37 @@ private static CompressionResult[] OptimizeImages(Repository repo, string localP
422388
logger.LogInformation("Compressed {NumImages}", optimizedImages.Count);
423389
return optimizedImages.ToArray();
424390
}
391+
392+
private static bool PaidPlan(CloudStorageAccount storageAccount, string ownerLogin)
393+
{
394+
var marketplaceTable = storageAccount.CreateCloudTableClient().GetTableReference("marketplace");
395+
var paidPlans = KnownGitHubs.Plans.Keys.Where(k => KnownGitHubs.Plans[k] != 0);
396+
string plansQuery = string.Empty;
397+
string needsOr = string.Empty;
398+
if (paidPlans.Count() > 0)
399+
{
400+
needsOr = " or ";
401+
}
402+
403+
int i = 0;
404+
foreach (int planId in paidPlans)
405+
{
406+
plansQuery += "PlanId eq " + planId.ToString();
407+
if (i != paidPlans.Count() - 1)
408+
{
409+
plansQuery += needsOr;
410+
}
411+
412+
i++;
413+
}
414+
415+
var query = new TableQuery<Marketplace>().Where(
416+
$"AccountLogin eq '{ownerLogin}' and ({plansQuery})");
417+
418+
var rows = marketplaceTable.ExecuteQuerySegmentedAsync(query, null).Result;
419+
var plan = rows.FirstOrDefault();
420+
421+
return plan != null;
422+
}
425423
}
426424
}

Docs/configuration.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ Here is an example .imgbotconfig setup that shows some of the options.
1616
],
1717
"aggressiveCompression": "true", // true|false
1818
"compressWiki": "true", // true|false
19-
"minKBReduced": 500 // delay new prs until size reduction meets this threshold (default to 10)
19+
"minKBReduced": 500, // delay new prs until size reduction meets this threshold (default to 10)
20+
"prTitle" : "Your own pr title",
21+
"prBody" : " Text before optimization ratio {optimization_ratio} Text after optimization ratio
22+
Text before optimization details {optimization_details} Text after optimization details",
2023
}
2124
```
2225

Docs/pr-body.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
You can set a pull request body for your Imgbot PRs through the `.imgbotconfig` file.
2+
3+
- This configuration is optional and is only required if you want a custom body for your pr's
4+
- Available only for paid plans
5+
- 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)
6+
- The default pr body to display is the one from [here](https://imgbot.net/images/screen.png?cache=2)
7+
8+
`.imgbotconfig`
9+
10+
```
11+
{
12+
"prBody" : " Text before optimization ratio {optimization_ratio} Text after optimization ratio
13+
Text before optimization details {optimization_details} Text after optimization details",
14+
}
15+
```

Docs/pr-title.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
You can set a pull request title for your Imgbot PRs through the `.imgbotconfig` file.
2+
3+
- This configuration is optional and is only required if you want a custom title for your pr's
4+
- Available only for paid plans
5+
- 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)
6+
- The default title to display is: "[ImgBot] Optimize images"
7+
8+
`.imgbotconfig`
9+
10+
```
11+
{
12+
"prTitle": "My title"
13+
}
14+
```

OpenPrFunction/PullRequestBody.cs

Lines changed: 55 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,19 @@ public static class PullRequestBody
1010
* Convert the ImageStat[] into a markdown PR body
1111
*/
1212
public static string Generate(ImageStat[] imageStats, Settings settings = null)
13+
{
14+
var prBody = BasicPr(imageStats, settings);
15+
16+
if (settings?.PrBody != null)
17+
{
18+
prBody = settings?.PrBody;
19+
}
20+
21+
prBody = ReplacePrMagicTags(imageStats, prBody);
22+
return prBody;
23+
}
24+
25+
private static string BasicPr(ImageStat[] imageStats, Settings settings = null)
1326
{
1427
if (imageStats == null || imageStats.Length == 0)
1528
{
@@ -18,28 +31,49 @@ public static string Generate(ImageStat[] imageStats, Settings settings = null)
1831
}
1932

2033
var sb = new StringBuilder();
21-
if (settings?.PrBody == null)
22-
{
23-
sb.AppendLine("## Beep boop. Your images are optimized!");
24-
sb.AppendLine();
34+
sb.AppendLine("## Beep boop. Your images are optimized!");
35+
sb.AppendLine();
36+
sb.AppendLine("{optimization_ratio}");
37+
sb.AppendLine();
38+
sb.AppendLine("{optimization_details}");
2539

26-
if (Math.Round(imageStats[0].Percent) < 5)
27-
{
28-
sb.AppendLine("Your image file size has been reduced!");
29-
}
30-
else
31-
{
32-
sb.AppendLine($"Your image file size has been reduced by **{imageStats[0].Percent:N0}%** 🎉");
33-
}
40+
sb.Append("[📝 docs](https://imgbot.net/docs) | ");
41+
sb.Append("[:octocat: repo](https://github.com/imgbot/ImgBot) | ");
42+
sb.Append("[🙋🏾 issues](https://github.com/imgbot/ImgBot/issues) | ");
43+
sb.Append("[🏪 marketplace](https://github.com/marketplace/imgbot)");
44+
sb.AppendLine();
45+
sb.AppendLine();
46+
sb.Append("<i>");
47+
sb.Append("~Imgbot - Part of [Optimole](https://optimole.com/) family");
48+
sb.Append("</i>");
49+
sb.AppendLine();
50+
return sb.ToString();
51+
}
52+
53+
private static string ReplacePrMagicTags(ImageStat[] imageStats, string prBody)
54+
{
55+
if (imageStats == null || imageStats.Length == 0)
56+
{
57+
prBody = prBody.Replace("{optimization_ratio}", "Your image file size has been reduced!");
58+
prBody = prBody.Replace("{optimization_details}", string.Empty);
59+
return prBody;
3460
}
35-
else
61+
62+
if (prBody.Contains("{optimization_ratio}"))
3663
{
37-
sb.AppendLine(settings.PrBody);
64+
var replace = "Your image file size has been reduced ";
65+
if (Math.Round(imageStats[0].Percent) >= 5)
66+
{
67+
replace += $"by **{imageStats[0].Percent:N0}%** ";
68+
}
69+
70+
replace += "🎉";
71+
prBody = prBody.Replace("{optimization_ratio}", replace);
3872
}
3973

40-
sb.AppendLine();
41-
if (settings?.PrDetails != false)
74+
if (prBody.Contains("{optimization_details}"))
4275
{
76+
var sb = new StringBuilder();
4377
sb.AppendLine("<details>");
4478

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

5387
if (imageStats.Length == 1)
5488
{
55-
sb.AppendLine(
56-
$"| {imageStats[0].Name} | {imageStats[0].Before} | {imageStats[0].After} | {imageStats[0].Percent:N2}% |");
89+
sb.AppendLine($"| {imageStats[0].Name} | {imageStats[0].Before} | {imageStats[0].After} | {imageStats[0].Percent:N2}% |");
5790
}
5891
else
5992
{
6093
// the zeroth item is the total; we print it at the bottom of the table
6194
for (var i = 1; i < imageStats.Length; i++)
6295
{
63-
sb.AppendLine(
64-
$"| {imageStats[i].Name} | {imageStats[i].Before} | {imageStats[i].After} | {imageStats[i].Percent:N2}% |");
96+
sb.AppendLine($"| {imageStats[i].Name} | {imageStats[i].Before} | {imageStats[i].After} | {imageStats[i].Percent:N2}% |");
6597
}
6698

6799
sb.AppendLine("| | | | |");
68-
sb.AppendLine(
69-
$"| **Total :** | **{imageStats[0].Before}** | **{imageStats[0].After}** | **{imageStats[0].Percent:N2}%** |");
100+
sb.AppendLine($"| **Total :** | **{imageStats[0].Before}** | **{imageStats[0].After}** | **{imageStats[0].Percent:N2}%** |");
70101
}
71102

72103
sb.AppendLine("</details>");
73104
sb.AppendLine();
74-
}
75-
76-
if (settings?.PrBody == null)
77-
{
78105
sb.AppendLine("---");
79-
sb.AppendLine();
80-
sb.Append("[📝 docs](https://imgbot.net/docs) | ");
81-
sb.Append("[:octocat: repo](https://github.com/imgbot/ImgBot) | ");
82-
sb.Append("[🙋🏾 issues](https://github.com/imgbot/ImgBot/issues) | ");
83-
sb.Append("[🏪 marketplace](https://github.com/marketplace/imgbot)");
84106

85-
sb.AppendLine();
86-
sb.AppendLine();
87-
sb.Append("<i>");
88-
sb.Append("~Imgbot - Part of [Optimole](https://optimole.com/) family");
89-
sb.Append("</i>");
90-
sb.AppendLine();
107+
prBody = prBody.Replace("{optimization_details}", sb.ToString());
91108
}
92109

93-
return sb.ToString();
110+
return prBody;
94111
}
95112
}
96113
}

README.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,14 @@ This file should be placed in the root of the repository and set to your liking.
2121
],
2222
"aggressiveCompression": "true", // true|false
2323
"compressWiki": "true", // true|false
24-
"minKBReduced": 500 // set reduction threshold (default to 10)
24+
"minKBReduced": 500 // set reduction threshold (default to 10),
25+
"prTitle" : "Compressed images", // set pull request title
26+
// set the pull request body, supports any valid github markdown
27+
// {optimization_ratio} display a message containing the optimization ratio
28+
// {optimization_details} display the table containing the optimization details
29+
"prBody" : " Text before optimization ratio {optimization_ratio} Text after optimization ratio
30+
Text before optimization details {optimization_details} Text after optimization details",
31+
2532
}
2633
```
2734

@@ -67,6 +74,26 @@ to [email protected]
6774
- Can be used to limit the frequency of PRs Imgbot will open over time
6875
- The default setting is 10
6976

77+
**prTitle**
78+
79+
- Optional
80+
- Available only for paid plans
81+
- Accepts only strings as input (e.g. `"prTitle": "My title"`)
82+
- Can be used to display any custom pull request title
83+
- The default setting is "[ImgBot] Optimize images"
84+
85+
**prBody**
86+
87+
- Optional
88+
- Available only for paid plans
89+
- Accepts only strings as input
90+
- (e.g. `"prBody": "Text before {optimization_ratio} Text after"` <br />
91+
&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"`)
92+
- 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)
93+
- Supports two magic tags: `{optimization_ratio} //displays the mean optimization ratio for all images` <br />
94+
&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`
95+
- The default setting generates the body displayed [here](https://imgbot.net/images/screen.png?cache=2)
96+
7097
Find out more: https://imgbot.net/docs
7198

7299
## Contributing

Test/PullRequestBodyTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public void GivenZeroPercentReductionCommitMessage_ShouldOmitPercentage()
6565

6666
var expectedMarkdown = "## Beep boop. Your images are optimized!" + Environment.NewLine +
6767
Environment.NewLine +
68-
"Your image file size has been reduced!" + Environment.NewLine +
68+
"Your image file size has been reduced 🎉" + Environment.NewLine +
6969
Environment.NewLine +
7070
"<details>" + Environment.NewLine +
7171
"<summary>" + Environment.NewLine +
@@ -93,7 +93,7 @@ public void GivenReductionBelow5PercentCommitMessage_ShouldOmitPercentage()
9393

9494
var expectedMarkdown = "## Beep boop. Your images are optimized!" + Environment.NewLine +
9595
Environment.NewLine +
96-
"Your image file size has been reduced!" + Environment.NewLine +
96+
"Your image file size has been reduced 🎉" + Environment.NewLine +
9797
Environment.NewLine +
9898
"<details>" + Environment.NewLine +
9999
"<summary>" + Environment.NewLine +

Web/src/docs/metadata.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@
3535
"slug": "min-kb-threshold",
3636
"title": "Min KB threshold"
3737
},
38+
{
39+
"slug": "pr-title",
40+
"title": "Pull request title"
41+
},
42+
{
43+
"slug": "pr-body",
44+
"title": "Pull request body"
45+
},
46+
3847
{
3948
"slug": "authorization",
4049
"title": "Authorization"

0 commit comments

Comments
 (0)