ChangeCommand.cs 8.7 KB
Newer Older
J
Jared Parsons 已提交
1 2 3 4 5 6
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
J
Jared Parsons 已提交
7
using System.Text.RegularExpressions;
J
Jared Parsons 已提交
8
using System.Threading.Tasks;
J
Jared Parsons 已提交
9 10
using System.Xml;
using System.Xml.Linq;
J
Jared Parsons 已提交
11 12 13 14 15

namespace RepoUtil
{
    /// <summary>
    /// Responsible for changing the repo to use a new set of NuGet packages.
J
Jared Parsons 已提交
16 17 18
    ///
    /// TODO: change needs to be concious of version.  Can only upgrade the items that have the old 
    /// version.  Needed to support static packages.
J
Jared Parsons 已提交
19
    /// </summary>
J
Jared Parsons 已提交
20
    internal sealed class ChangeCommand : ICommand
J
Jared Parsons 已提交
21 22 23
    {
        private readonly RepoData _repoData;

J
Jared Parsons 已提交
24
        internal ChangeCommand(RepoData repoData)
J
Jared Parsons 已提交
25 26 27 28
        {
            _repoData = repoData;
        }

J
Jared Parsons 已提交
29 30 31 32 33 34 35 36 37 38 39 40
        public bool Run(TextWriter writer, string[] args)
        {
            List<NuGetPackage> changes;
            if (!TryParseChangeSource(writer, args, out changes))
            {
                return false;
            }

            ChangeAll(changes);
            return true;
        }

J
Jared Parsons 已提交
41 42 43
        /// <summary>
        /// Parse out the arguments that can be provided to the 'change' command.
        /// </summary>
J
Jared Parsons 已提交
44
        private static bool TryParseChangeSource(TextWriter writer, string[] args, out List<NuGetPackage> changes)
J
Jared Parsons 已提交
45 46
        {
            changes = new List<NuGetPackage>();
J
Jared Parsons 已提交
47
            var allGood = true;
J
Jared Parsons 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
            var index = 0;
            while (index < args.Length && allGood)
            {
                var arg = args[index];
                index++;

                switch (arg.ToLower())
                {
                    case "-version":
                        if (index < args.Length)
                        {
                            allGood = TryParseVersionSource(writer, args[index], changes);
                            index++;
                        }
                        else
                        {
                            Console.WriteLine($"The -version switch needs a value");
                            allGood = false;
                        }
                        break;
                    default:
                        if (!TryParsePackage(writer, arg, changes))
                        {
                            allGood = false;
                        }
                        break;
                }
            }

            return allGood;
        }

        /// <summary>
        /// Parse out a file that has the format used on the dotnet/versions repo.  Essentially every entry in the file
        /// will be a package name, space, version.
        /// </summary>
        private static bool TryParseVersionSource(TextWriter writer, string path, List<NuGetPackage> changes)
        {
            try
            {
                foreach (var line in File.ReadAllLines(path))
                {
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }

                    if (!TryParsePackage(writer, line, changes))
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                writer.WriteLine($"Error parsing {path}: {ex.ToString()}");
                writer.WriteLine(ex.StackTrace);
                changes = null;
                return false;
            }
        }

        private static bool TryParsePackage(TextWriter writer, string packageLine, List<NuGetPackage> changes)
        {
            var match = Regex.Match(packageLine, @"([^\s]*)\s*(.*)");
            if (match.Success)
            {
                var package = new NuGetPackage(
                    match.Groups[1].Value,
                    match.Groups[2].Value);
                changes.Add(package);
                return true;
            }

            match = Regex.Match(packageLine, @"([^\s]*)\s*-\s*(.*)");
            if (match.Success)
            {
                var package = new NuGetPackage(
                    match.Groups[1].Value,
                    match.Groups[2].Value);
                changes.Add(package);
                return true;
            }

            writer.WriteLine($"Unable to parse package {packageLine}");
            return false;
        }

J
Jared Parsons 已提交
137 138 139
        /// <summary>
        /// Change the state of the repo to use the specified packages.
        /// </summary>
J
Jared Parsons 已提交
140
        internal void ChangeAll(IEnumerable<NuGetPackage> packages)
J
Jared Parsons 已提交
141 142 143 144 145 146 147
        {
            var changeList = CalculateChanges(packages);
            var map = ImmutableDictionary<string, NuGetPackage>.Empty.WithComparers(Constants.NugetPackageNameComparer);
            foreach (var package in changeList)
            {
                map = map.Add(package.Name, package.NewPackage);
            }
J
Jared Parsons 已提交
148
            ChangeAllCore(map);
J
Jared Parsons 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        }

        private List<NuGetPackageChange> CalculateChanges(IEnumerable<NuGetPackage> packages)
        {
            var map = _repoData
                .FloatingPackages
                .ToDictionary(x => x.Name, Constants.NugetPackageNameComparer);
            var list = new List<NuGetPackageChange>();

            Console.WriteLine("Calculating the changes");
            foreach (var package in packages)
            {
                NuGetPackage existingPackage;
                if (!map.TryGetValue(package.Name, out existingPackage))
                {
                    Console.WriteLine($"\tSkipping {package.Name} as it's not a floating package in this repo.");
                }

                list.Add(new NuGetPackageChange(package.Name, oldVersion: existingPackage.Version, newVersion: package.Version));
            }

            return list;
        }

        /// <summary>
        /// Change the repo to respect the new version for the specified set of NuGet packages
        /// </summary>
J
Jared Parsons 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        private void ChangeAllCore(ImmutableDictionary<string, NuGetPackage> changeMap)
        {
            ChangeProjectJsonFiles(changeMap);

            // Calculate the new set of packages based on the changed information.
            var list = new List<NuGetPackage>();
            foreach (var cur in _repoData.AllPackages)
            {
                NuGetPackage newPackage;
                if (changeMap.TryGetValue(cur.Name, out newPackage))
                {
                    list.Add(newPackage);
                }
                else
                {
                    list.Add(cur);
                }
            }

            ChangeGeneratedFiles(list);
        }

        private void ChangeProjectJsonFiles(ImmutableDictionary<string, NuGetPackage> changeMap)
J
Jared Parsons 已提交
199 200 201 202 203 204 205 206 207
        {
            Console.WriteLine("Changing project.json files");
            foreach (var filePath in ProjectJsonUtil.GetProjectJsonFiles(_repoData.SourcesPath))
            {
                if (ProjectJsonUtil.ChangeDependencies(filePath, changeMap))
                {
                    Console.WriteLine($"\t{filePath} updated");
                }
            }
J
Jared Parsons 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        }

        private void ChangeGeneratedFiles(IEnumerable<NuGetPackage> allPackages)
        {
            var msbuildData = _repoData.RepoConfig.MSBuildGenerateData;
            if (msbuildData.HasValue)
            {
                GenerateMSBuild(msbuildData.Value, allPackages);
            }
        }

        private void GenerateMSBuild(GenerateData data, IEnumerable<NuGetPackage> allPackages)
        {
            Console.WriteLine($"Generating MSBuild props file {data.RelativeFileName}");
            var doc = GenerateMSBuildXml(data, allPackages);
            var fileName = new FileName(_repoData.SourcesPath, data.RelativeFileName);
            using (var writer = XmlWriter.Create(fileName.FullPath, new XmlWriterSettings() { Indent = true }))
            {
                doc.WriteTo(writer);
            }
        }

        /// <summary>
        /// Generate the MSBuild props file which contains named values for the NuGet versions.
        /// </summary>
        private XDocument GenerateMSBuildXml(GenerateData data, IEnumerable<NuGetPackage> allPackages)
        {
            var ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
            var doc = new XDocument(new XElement(ns + "Project"));
            doc.Root.Add(new XAttribute("ToolsVersion", "4.0"));

            var group = new XElement(ns + "PropertyGroup");
            foreach (var package in allPackages)
            {
                if (data.Packages.Any(x => x.IsMatch(package.Name)))
                {
                    var name = package.Name.Replace(".", "") + "Version";
                    var elem = new XElement(ns + name);
                    elem.Value = package.Version;
                    group.Add(elem);
                }
            }
J
Jared Parsons 已提交
250

J
Jared Parsons 已提交
251 252
            doc.Root.Add(group);
            return doc;
J
Jared Parsons 已提交
253 254 255
        }
    }
}