|
1 | 1 | using DevOps.Responses; |
2 | 2 | using DevOps.Services; |
| 3 | +using DevOps.Utils; |
| 4 | +using Newtonsoft.Json; |
3 | 5 | using Spectre.Console; |
4 | 6 |
|
5 | 7 | namespace DevOps.Actions; |
6 | 8 |
|
7 | 9 | internal static class ActionHelpers |
8 | 10 | { |
| 11 | + /// <summary> |
| 12 | + /// Writes work items as machine-readable JSON or CSV to stdout. Returns a non-zero |
| 13 | + /// exit code (with an error) for an unknown format. |
| 14 | + /// </summary> |
| 15 | + internal static int WriteWorkItemsOutput(List<WorkItemResponse> items, string format) |
| 16 | + { |
| 17 | + switch (format?.ToLowerInvariant()) |
| 18 | + { |
| 19 | + case "json": |
| 20 | + var projected = items.Select(i => new |
| 21 | + { |
| 22 | + id = i.Id, |
| 23 | + type = i.Fields.WorkItemType, |
| 24 | + title = i.Fields.Title, |
| 25 | + state = i.Fields.State, |
| 26 | + assignedTo = i.Fields.AssignedTo?.DisplayName, |
| 27 | + project = i.Fields.TeamProject, |
| 28 | + parentId = i.Fields.ParentId, |
| 29 | + priority = i.Fields.Priority, |
| 30 | + createdDate = i.Fields.CreatedDate, |
| 31 | + changedDate = i.Fields.ChangedDate |
| 32 | + }); |
| 33 | + Console.WriteLine(JsonConvert.SerializeObject(projected, Formatting.Indented)); |
| 34 | + return 0; |
| 35 | + |
| 36 | + case "csv": |
| 37 | + Console.WriteLine("id,type,title,state,assigned_to,project,parent_id,priority,created,changed"); |
| 38 | + foreach (var i in items) |
| 39 | + { |
| 40 | + var f = i.Fields; |
| 41 | + Console.WriteLine(string.Join(",", |
| 42 | + i.Id, |
| 43 | + Csv(f.WorkItemType), Csv(f.Title), Csv(f.State), |
| 44 | + Csv(f.AssignedTo?.DisplayName), Csv(f.TeamProject), |
| 45 | + f.ParentId?.ToString() ?? "", f.Priority?.ToString() ?? "", |
| 46 | + f.CreatedDate.ToString("yyyy-MM-dd"), f.ChangedDate.ToString("yyyy-MM-dd"))); |
| 47 | + } |
| 48 | + return 0; |
| 49 | + |
| 50 | + default: |
| 51 | + ConsoleHelper.WriteError($"Unknown output format '{format}'. Use 'json' or 'csv'."); |
| 52 | + return 1; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + private static string Csv(string value) |
| 57 | + { |
| 58 | + if (string.IsNullOrEmpty(value)) return ""; |
| 59 | + return value.Contains(',') || value.Contains('"') || value.Contains('\n') |
| 60 | + ? "\"" + value.Replace("\"", "\"\"") + "\"" |
| 61 | + : value; |
| 62 | + } |
| 63 | + |
9 | 64 | /// <summary>Creates a table with bold headers, sized to the terminal, using the configured border.</summary> |
10 | 65 | internal static Table NewTable(params string[] columns) |
11 | 66 | { |
|
0 commit comments