|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.IO; |
| 7 | +using System.Linq; |
| 8 | +using Newtonsoft.Json; |
| 9 | +using Newtonsoft.Json.Linq; |
| 10 | +using Microsoft.Build.Framework; |
| 11 | +using Microsoft.Build.Utilities; |
| 12 | + |
| 13 | +namespace Microsoft.DotNet.Build.Tasks |
| 14 | +{ |
| 15 | + // Takes a path to a path to a json file and a |
| 16 | + // string that represents a dotted path to an attribute |
| 17 | + // and updates that attribute with the new value provided. |
| 18 | + public class UpdateJson : Task |
| 19 | + { |
| 20 | + [Required] |
| 21 | + public string JsonFilePath { get; set; } |
| 22 | + |
| 23 | + [Required] |
| 24 | + public string PathToAttribute { get; set; } |
| 25 | + |
| 26 | + [Required] |
| 27 | + public string NewAttributeValue { get; set; } |
| 28 | + |
| 29 | + public bool SkipUpdateIfMissingKey { get; set; } |
| 30 | + |
| 31 | + public override bool Execute() |
| 32 | + { |
| 33 | + JObject jsonObj = JObject.Parse(File.ReadAllText(JsonFilePath)); |
| 34 | + |
| 35 | + string[] escapedPathToAttributeParts = PathToAttribute.Replace("\\.", "\x1F").Split('.'); |
| 36 | + for (int i = 0; i < escapedPathToAttributeParts.Length; ++i) |
| 37 | + { |
| 38 | + escapedPathToAttributeParts[i] = escapedPathToAttributeParts[i].Replace("\x1F", "."); |
| 39 | + } |
| 40 | + UpdateAttribute(jsonObj, escapedPathToAttributeParts, NewAttributeValue); |
| 41 | + |
| 42 | + File.WriteAllText(JsonFilePath, jsonObj.ToString()); |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + private void UpdateAttribute(JToken jsonObj, string[] path, string newValue) |
| 47 | + { |
| 48 | + string pathItem = path[0]; |
| 49 | + if (jsonObj[pathItem] == null) |
| 50 | + { |
| 51 | + string message = $"Path item [{nameof(PathToAttribute)}] not found in json file."; |
| 52 | + if (SkipUpdateIfMissingKey) |
| 53 | + { |
| 54 | + Log.LogMessage(MessageImportance.Low, $"Skipping update: {message} {pathItem}"); |
| 55 | + return; |
| 56 | + } |
| 57 | + throw new ArgumentException(message, pathItem); |
| 58 | + } |
| 59 | + |
| 60 | + if (path.Length == 1) |
| 61 | + { |
| 62 | + jsonObj[pathItem] = newValue; |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + UpdateAttribute(jsonObj[pathItem], path.Skip(1).ToArray(), newValue); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments