|
| 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 | + |
| 4 | +using System.IO; |
| 5 | +using System.Linq; |
| 6 | +using System.Xml.Linq; |
| 7 | +using Microsoft.Build.Framework; |
| 8 | +using Microsoft.Build.Utilities; |
| 9 | + |
| 10 | +namespace Microsoft.DotNet.Build.Tasks |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// This task adds a source to a well-formed NuGet.Config file with highest |
| 14 | + /// priority, or replaces a source with the same name if present. The task |
| 15 | + /// also by default adds a 'clear' element if none exists, to avoid |
| 16 | + /// unintended leaks from the build environment. |
| 17 | + /// </summary> |
| 18 | + public class AddSourceToNuGetConfig : Task |
| 19 | + { |
| 20 | + [Required] |
| 21 | + public string NuGetConfigFile { get; set; } |
| 22 | + |
| 23 | + [Required] |
| 24 | + public string SourceName { get; set; } |
| 25 | + |
| 26 | + [Required] |
| 27 | + public string SourcePath { get; set; } |
| 28 | + |
| 29 | + public bool SkipEnsureClear { get; set; } |
| 30 | + |
| 31 | + public override bool Execute() |
| 32 | + { |
| 33 | + XDocument document = XDocument.Load(NuGetConfigFile); |
| 34 | + |
| 35 | + XName CreateQualifiedName(string plainName) |
| 36 | + { |
| 37 | + return document.Root.GetDefaultNamespace().GetName(plainName); |
| 38 | + } |
| 39 | + |
| 40 | + XElement packageSourcesElement = document.Root |
| 41 | + .Element(CreateQualifiedName("packageSources")); |
| 42 | + |
| 43 | + var sourceElementToAdd = new XElement( |
| 44 | + "add", |
| 45 | + new XAttribute("key", SourceName), |
| 46 | + new XAttribute("value", SourcePath)); |
| 47 | + |
| 48 | + XElement existingSourceElement = packageSourcesElement |
| 49 | + .Elements(CreateQualifiedName("add")) |
| 50 | + .FirstOrDefault(e => e.Attribute("key").Value == SourceName); |
| 51 | + |
| 52 | + XElement lastClearElement = packageSourcesElement |
| 53 | + .Elements(CreateQualifiedName("clear")) |
| 54 | + .LastOrDefault(); |
| 55 | + |
| 56 | + if (existingSourceElement != null) |
| 57 | + { |
| 58 | + existingSourceElement.ReplaceWith(sourceElementToAdd); |
| 59 | + } |
| 60 | + else if (lastClearElement != null) |
| 61 | + { |
| 62 | + lastClearElement.AddAfterSelf(sourceElementToAdd); |
| 63 | + } |
| 64 | + else |
| 65 | + { |
| 66 | + packageSourcesElement.AddFirst(sourceElementToAdd); |
| 67 | + } |
| 68 | + |
| 69 | + if (lastClearElement == null && !SkipEnsureClear) |
| 70 | + { |
| 71 | + packageSourcesElement.AddFirst(new XElement("clear")); |
| 72 | + } |
| 73 | + |
| 74 | + using (var fs = new FileStream(NuGetConfigFile, FileMode.Create, FileAccess.ReadWrite)) |
| 75 | + { |
| 76 | + document.Save(fs); |
| 77 | + } |
| 78 | + |
| 79 | + return !Log.HasLoggedErrors; |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments