|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace Semmle.Autobuild.Shared |
| 7 | +{ |
| 8 | + public static class MarkdownUtil |
| 9 | + { |
| 10 | + /// <summary> |
| 11 | + /// Formats items as markdown inline code. |
| 12 | + /// </summary> |
| 13 | + /// <returns>A function which formats items as markdown inline code.</returns> |
| 14 | + public static readonly Func<string, string> CodeFormatter = item => $"`{item}`"; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Renders <see cref="projects" /> as a markdown list of the project paths. |
| 18 | + /// </summary> |
| 19 | + /// <param name="projects"> |
| 20 | + /// The list of projects whose paths should be rendered as a markdown list. |
| 21 | + /// </param> |
| 22 | + /// <param name="limit">The maximum number of items to include in the list.</param> |
| 23 | + /// <returns>Returns the markdown list as a string.</returns> |
| 24 | + public static string ToMarkdownList(this IEnumerable<IProjectOrSolution> projects, int? limit = null) |
| 25 | + { |
| 26 | + return projects.ToMarkdownList(p => $"`{p.FullPath}`", limit); |
| 27 | + } |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// Renders <see cref="items" /> as a markdown list. |
| 31 | + /// </summary> |
| 32 | + /// <typeparam name="T">The item type.</typeparam> |
| 33 | + /// <param name="items">The list that should be formatted as a markdown list.</param> |
| 34 | + /// <param name="formatter">A function which converts individual items into a string representation.</param> |
| 35 | + /// <param name="limit">The maximum number of items to include in the list.</param> |
| 36 | + /// <returns>Returns the markdown list as a string.</returns> |
| 37 | + public static string ToMarkdownList<T>(this IEnumerable<T> items, Func<T, string> formatter, int? limit = null) |
| 38 | + { |
| 39 | + var sb = new StringBuilder(); |
| 40 | + |
| 41 | + // if there is a limit, take at most that many items from the start of the list |
| 42 | + var list = limit is not null ? items.Take(limit.Value) : items; |
| 43 | + sb.Append(string.Join('\n', list.Select(item => $"- {formatter(item)}"))); |
| 44 | + |
| 45 | + // if there were more items than allowed in the list, add an extra item indicating |
| 46 | + // how many more items there were |
| 47 | + var length = items.Count(); |
| 48 | + |
| 49 | + if (limit is not null && length > limit) |
| 50 | + { |
| 51 | + sb.Append($"\n- and {length - limit} more. View the CodeQL logs for a full list."); |
| 52 | + } |
| 53 | + |
| 54 | + return sb.ToString(); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments