| 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. |
| 2 | |
| 3 | namespace WixToolset.BuildTasks |
| 4 | { |
| 5 | using System; |
| 6 | using System.Collections.Generic; |
| 7 | using System.Linq; |
| 8 | using Microsoft.Build.Framework; |
| 9 | |
| 10 | internal class MetadataValueList |
| 11 | { |
| 12 | private static readonly char[] MetadataListSplitter = new char[] { ',', ';' }; |
| 13 | |
| 14 | public MetadataValueList(ITaskItem item, string name) |
| 15 | { |
| 16 | this.Item = item; |
| 17 | this.Name = name; |
| 18 | |
| 19 | var value = item.GetMetadata(name); |
| 20 | |
| 21 | this.HadValue = !String.IsNullOrWhiteSpace(value); |
| 22 | this.OriginalValue = value; |
| 23 | |
| 24 | this.Values = value.Split(MetadataListSplitter).Where(s => !String.IsNullOrWhiteSpace(s)).ToList(); |
| 25 | } |
| 26 | |
| 27 | public ITaskItem Item { get; } |
| 28 | |
| 29 | public string Name { get; } |
| 30 | |
| 31 | public bool HadValue { get; } |
| 32 | |
| 33 | public string OriginalValue { get; } |
| 34 | |
| 35 | public bool Modified { get; private set; } |
| 36 | |
| 37 | public List<string> Values { get; } |
| 38 | |
| 39 | public void Clear() |
| 40 | { |
| 41 | if (this.Values.Count > 0) |
| 42 | { |
| 43 | this.Modified = true; |
| 44 | this.Values.Clear(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | public void SetValue(string prefix, string value) |
| 49 | { |
| 50 | if (!String.IsNullOrEmpty(prefix)) |
| 51 | { |
| 52 | value = String.IsNullOrWhiteSpace(value) ? null : prefix + value; |
| 53 | |
| 54 | for (var i = 0; i < this.Values.Count; ++i) |
| 55 | { |
| 56 | if (this.Values[i].StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) |
| 57 | { |
| 58 | if (value == null) |
| 59 | { |
| 60 | this.Values.RemoveAt(i); |
| 61 | } |
| 62 | else |
| 63 | { |
| 64 | this.Values[i] = value; |
| 65 | } |
| 66 | |
| 67 | this.Modified = true; |
| 68 | return; |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | if (!String.IsNullOrWhiteSpace(value) && !this.Values.Contains(value)) |
| 74 | { |
| 75 | this.Modified = true; |
| 76 | this.Values.Add(value); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | public void AddRange(IEnumerable<string> values) |
| 81 | { |
| 82 | foreach (var value in values) |
| 83 | { |
| 84 | this.SetValue(null, value); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | public void Apply() |
| 89 | { |
| 90 | if (this.Values.Count == 0) |
| 91 | { |
| 92 | this.Item.RemoveMetadata(this.Name); |
| 93 | } |
| 94 | else |
| 95 | { |
| 96 | this.Item.SetMetadata(this.Name, String.Join(";", this.Values)); |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | } |