├── .gitattributes ├── .gitignore ├── .travis.yml ├── LICENSE ├── ProjectSimplifier.Tests ├── GlobalSuppressions.cs ├── ItemsDiffTests.cs ├── Mocks │ └── IProjectFactory.cs ├── ProjectExtensionsTests.cs ├── ProjectSimplifier.Tests.csproj └── PropertiesDiffTests.cs ├── ProjectSimplifier.sln ├── ProjectSimplifier ├── BaselineProject.cs ├── Converter.cs ├── Differ.cs ├── Facts.cs ├── GlobalSuppressions.cs ├── InternalsVisibleTo.cs ├── ItemsDiff.cs ├── MSBuildProject.cs ├── MSBuildProjectRootElement.cs ├── MSBuildUtilities.cs ├── Options.cs ├── Program.cs ├── ProjectExtensions.cs ├── ProjectItemComparer.cs ├── ProjectLoader.cs ├── ProjectSimplifier.csproj ├── ProjectStyle.cs ├── Properties │ ├── PublishProfiles │ │ └── FolderProfile.pubxml │ └── launchSettings.json ├── PropertiesDiff.cs └── UnconfiguredProject.cs └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc 262 | 263 | report.diff 264 | currentProject.log 265 | sdkBaseLineProject.log 266 | out.csproj 267 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | 3 | matrix: 4 | include: 5 | - os: linux 6 | dist: trusty 7 | sudo: required 8 | - os: osx 9 | 10 | solution: solution-name.sln 11 | mono: beta 12 | 13 | before_install: 14 | - wget https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -O /tmp/nuget.exe 15 | - mono /tmp/nuget.exe install xunit.runner.console -Version 2.2.0 -Output /tmp/packages/ 16 | install: 17 | - msbuild /t:restore 18 | 19 | script: 20 | - msbuild 21 | - mono /tmp/packages/xunit.runner.console.2.2.0/tools/xunit.console.exe ./ProjectSimplifier.Tests/bin/Debug/net461/ProjectSimplifier.Tests.dll 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Srivatsn Narayanan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ProjectSimplifier.Tests/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 |  2 | // This file is used by Code Analysis to maintain SuppressMessage 3 | // attributes that are applied to this project. 4 | // Project-level suppressions either have no target or are given 5 | // a specific target and scoped to a namespace, type, member, etc. 6 | 7 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0033:Use explicitly provided tuple name", Justification = "Appveyor doesnt support 15.3 yet.")] 8 | 9 | -------------------------------------------------------------------------------- /ProjectSimplifier.Tests/ItemsDiffTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using System.Linq; 4 | using ProjectSimplifier.Tests.Mocks; 5 | using Xunit; 6 | 7 | namespace ProjectSimplifier.Tests 8 | { 9 | public class ItemsDiffTests 10 | { 11 | [Theory] 12 | [InlineData("Compile:a.cs,b.cs", "Compile:a.cs", "Compile:a.cs", "Compile:b.cs", null, null)] 13 | [InlineData("Compile:a.cs,b.cs", "Compile:e.cs,d.cs", null, "Compile:a.cs,b.cs", "Compile:e.cs,d.cs", null)] 14 | [InlineData("Compile:a.cs,b.cs", "Compile:a.cs,b.cs,e.cs", "Compile:a.cs,b.cs", null, "Compile:e.cs", null)] 15 | [InlineData("Compile:a.cs,b.cs", "Compile:a.cs,d.cs", "Compile:a.cs", "Compile:b.cs", "Compile:d.cs", null)] 16 | [InlineData("Compile:a.cs,b.cs;None:a.xml", "Compile:a.cs", "Compile:a.cs", "Compile:b.cs;None:a.xml", null, null)] 17 | [InlineData("Compile:a.cs,b.cs;None:a.cs", "Compile:a.cs", "Compile:a.cs", "Compile:b.cs;None:a.cs", null, null)] 18 | [InlineData("Compile:a.cs|x=y,b.cs|x=y", "Compile:a.cs", null, "Compile:b.cs", null, "Compile:a.cs")] 19 | [InlineData("Compile:a.cs|x=y|z=z,b.cs|x=y", "Compile:a.cs|x=y", null, "Compile:b.cs", null, "Compile:a.cs")] 20 | [InlineData("Compile:a.cs|x=y,b.cs|x=y", "Compile:a.cs|x=z", null, "Compile:b.cs", null, "Compile:a.cs")] 21 | public void ItemsDiff(string projectItems, string sdkBaselineItems, string expectedDefaultedItems, string expectedNotDefaultedItems, string expectedIntroducedItems, string expectedChangedItems) 22 | { 23 | var project = IProjectFactory.Create(GetItems(projectItems)); 24 | var sdkBaselineProject = IProjectFactory.Create(GetItems(sdkBaselineItems)); 25 | 26 | var differ = new Differ(project, sdkBaselineProject); 27 | 28 | var diffs = differ.GetItemsDiff(); 29 | 30 | if (expectedDefaultedItems == null) 31 | { 32 | Assert.All(diffs, diff => Assert.Empty(diff.DefaultedItems)); 33 | } 34 | else 35 | { 36 | var expectedDiffItems = GetItems(expectedDefaultedItems); 37 | var matchingItems = diffs.Select(diff => (diff.DefaultedItems.Select(i => i.EvaluatedInclude), expectedDiffItems.SingleOrDefault(d => d.ItemType == diff.ItemType).Items)); 38 | Assert.All(matchingItems, diff => Assert.Equal(diff.Item1, diff.Item2)); 39 | } 40 | 41 | if (expectedNotDefaultedItems == null) 42 | { 43 | Assert.All(diffs, diff => Assert.Empty(diff.NotDefaultedItems)); 44 | } 45 | else 46 | { 47 | var expectedDiffItems = GetItems(expectedNotDefaultedItems); 48 | var matchingItems = diffs.Select(diff => (diff.NotDefaultedItems.Select(i => i.EvaluatedInclude), expectedDiffItems.SingleOrDefault(d => d.ItemType == diff.ItemType).Items)); 49 | Assert.All(matchingItems, diff => Assert.Equal(diff.Item1, diff.Item2)); 50 | } 51 | 52 | if (expectedIntroducedItems == null) 53 | { 54 | Assert.All(diffs, diff => Assert.Empty(diff.IntroducedItems)); 55 | } 56 | else 57 | { 58 | var expectedDiffItems = GetItems(expectedIntroducedItems); 59 | var matchingItems = diffs.Select(diff => (diff.IntroducedItems.Select(i => i.EvaluatedInclude), expectedDiffItems.SingleOrDefault(d => d.ItemType == diff.ItemType).Items)); 60 | Assert.All(matchingItems, diff => Assert.Equal(diff.Item1, diff.Item2)); 61 | } 62 | 63 | if (expectedChangedItems == null) 64 | { 65 | Assert.All(diffs, diff => Assert.Empty(diff.ChangedItems)); 66 | } 67 | else 68 | { 69 | var expectedDiffItems = GetItems(expectedChangedItems); 70 | var matchingItems = diffs.Select(diff => (diff.ChangedItems.Select(i => i.EvaluatedInclude), expectedDiffItems.SingleOrDefault(d => d.ItemType == diff.ItemType).Items)); 71 | Assert.All(matchingItems, diff => Assert.Equal(diff.Item1, diff.Item2)); 72 | } 73 | } 74 | 75 | [Fact] 76 | public void ItemsDiff_GetLines() 77 | { 78 | var defaultedItems = IProjectFactory.Create(GetItems("A:B,C")).Items.ToImmutableArray(); 79 | var removedItems = IProjectFactory.Create(GetItems("A:D,E")).Items.ToImmutableArray(); 80 | var introducedItems = IProjectFactory.Create(GetItems("A:F,G")).Items.ToImmutableArray(); 81 | var changedItems = ImmutableArray.Empty; 82 | var diff = new ItemsDiff("A", defaultedItems, removedItems, introducedItems, changedItems); 83 | 84 | var lines = diff.GetDiffLines(); 85 | var expectedLines = new[] 86 | { 87 | "A items:", 88 | "- B", 89 | "- C", 90 | "= D", 91 | "= E", 92 | "+ F", 93 | "+ G", 94 | "", 95 | }; 96 | 97 | Assert.Equal(expectedLines, lines); 98 | } 99 | 100 | [Fact] 101 | public void ItemsDiff_GetLines_Partial() 102 | { 103 | var defaultedItems = IProjectFactory.Create(GetItems("X:Y,Z")).Items.ToImmutableArray(); 104 | var removedItems = ImmutableArray.Empty; 105 | var introducedItems = ImmutableArray.Empty; 106 | var changedItems = ImmutableArray.Empty; 107 | var diff = new ItemsDiff("X", defaultedItems, removedItems, introducedItems, changedItems); 108 | 109 | var lines = diff.GetDiffLines(); 110 | var expectedLines = new[] 111 | { 112 | "X items:", 113 | "- Y", 114 | "- Z", 115 | "", 116 | }; 117 | 118 | Assert.Equal(expectedLines, lines); 119 | 120 | } 121 | /// 122 | /// Expected format here is "A:B,C;C:D,E" 123 | /// 124 | private static IEnumerable<(string ItemType, string[] Items)> GetItems(string projectItems) 125 | { 126 | var lines = projectItems.Split(';'); 127 | 128 | var items = from line in lines 129 | let splitItems = line.Split(':') 130 | select (ItemType: splitItems[0], Items: splitItems[1].Split(',')); 131 | 132 | return items; 133 | } 134 | 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /ProjectSimplifier.Tests/Mocks/IProjectFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Microsoft.Build.Evaluation; 4 | using Moq; 5 | 6 | namespace ProjectSimplifier.Tests.Mocks 7 | { 8 | internal class IProjectFactory 9 | { 10 | /// 11 | /// Expected format here is "A=B;C=D" 12 | /// 13 | public static IProject Create(string projectProperties, string propertiesInFile="") 14 | { 15 | var lines = projectProperties.Split(';'); 16 | return Create(lines.Select(p => p.Split('=')).ToDictionary(a => a[0], a => a[1]), propertiesInFile.Split(';')); 17 | } 18 | 19 | public static IProject Create(IEnumerable<(string ItemType, string[] Items)> items) 20 | { 21 | var mock = new Mock(); 22 | 23 | var projectItems = new List(); 24 | 25 | foreach (var itemGroup in items) 26 | { 27 | foreach (var item in itemGroup.Items) 28 | { 29 | var itemSplit = item.Split('|'); 30 | var itemInclude = itemSplit.First(); 31 | var metadata = itemSplit.Length > 1 ? itemSplit.Skip(1).Select(p => p.Split('=')).ToDictionary(a => a[0], a => a[1]) : new Dictionary(); 32 | var metadataMocks = metadata?.Select(kvp => 33 | { 34 | var metadataMock = new Mock(); 35 | metadataMock.SetupGet(md => md.Name).Returns(kvp.Key); 36 | metadataMock.SetupGet(md => md.EvaluatedValue).Returns(kvp.Value); 37 | metadataMock.SetupGet(md => md.UnevaluatedValue).Returns(kvp.Value); 38 | return metadataMock.Object; 39 | }); 40 | 41 | var projectItemMock = new Mock(); 42 | projectItemMock.SetupGet(pi => pi.ItemType).Returns(itemGroup.ItemType); 43 | projectItemMock.SetupGet(pi => pi.EvaluatedInclude).Returns(itemInclude); 44 | projectItemMock.SetupGet(pi => pi.DirectMetadata).Returns(metadataMocks); 45 | projectItems.Add(projectItemMock.Object); 46 | } 47 | } 48 | 49 | mock.SetupGet(m => m.Items).Returns(projectItems); 50 | 51 | return mock.Object; 52 | } 53 | 54 | public static IProject Create(IDictionary projectProperties, IEnumerable propertiesInFile=null) 55 | { 56 | var mock = new Mock(); 57 | 58 | mock.Setup(m => m.GetPropertyValue(It.IsAny())).Returns((string prop) => projectProperties.ContainsKey(prop) ? projectProperties[prop] : ""); 59 | 60 | mock.Setup(m => m.GetProperty(It.IsAny())).Returns((string prop) => 61 | { 62 | if (projectProperties.ContainsKey(prop)) 63 | { 64 | return MockProperty(prop, projectProperties[prop], propertiesInFile?.Contains(prop)); 65 | } 66 | return null; 67 | }); 68 | 69 | mock.SetupGet(m => m.Properties).Returns(projectProperties.Select(kvp => MockProperty(kvp.Key, kvp.Value, propertiesInFile?.Contains(kvp.Key))).ToArray()); 70 | 71 | return mock.Object; 72 | } 73 | 74 | private static IProjectProperty MockProperty(string propName, string propValue, bool? isDefinedInProject) 75 | { 76 | var projectProperty = new Mock(); 77 | projectProperty.SetupGet(pp => pp.Name).Returns(propName); 78 | projectProperty.SetupGet(pp => pp.EvaluatedValue).Returns(propValue); 79 | projectProperty.SetupGet(pp => pp.IsDefinedInProject).Returns(isDefinedInProject??false); 80 | return projectProperty.Object; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /ProjectSimplifier.Tests/ProjectExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using ProjectSimplifier; 5 | using ProjectSimplifier.Tests.Mocks; 6 | using Xunit; 7 | 8 | namespace ProjectSimplifier.Tests 9 | { 10 | public class ProjectExtensionsTests 11 | { 12 | [Theory] 13 | [InlineData("net46", null, null, null, "net46")] 14 | [InlineData(null, ".NETFramework", "v4.6", null, "net4.6")] 15 | [InlineData(null, ".NETCoreApp", "v1.0", null, "netcoreapp1.0")] 16 | [InlineData(null, ".NETStandard", "v1.0", null, "netstandard1.0")] 17 | [InlineData(null, ".NETPortable", "v5.0", "Profile7", "netstandard1.1")] 18 | public void GetTargetFramework(string targetFramework, string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string expectedTargetFramework) 19 | { 20 | var properties = new Dictionary(); 21 | if (targetFramework != null) 22 | properties.Add("TargetFramework", targetFramework); 23 | if (targetFrameworkIdentifier != null) 24 | properties.Add("TargetFrameworkIdentifier", targetFrameworkIdentifier); 25 | if (targetFrameworkVersion != null) 26 | properties.Add("TargetFrameworkVersion", targetFrameworkVersion); 27 | if (targetFrameworkProfile != null) 28 | properties.Add("TargetFrameworkProfile", targetFrameworkProfile); 29 | 30 | var project = IProjectFactory.Create(properties); 31 | var actualTargetFramework = ProjectExtensions.GetTargetFramework(project); 32 | 33 | Assert.Equal(expectedTargetFramework, actualTargetFramework); 34 | } 35 | 36 | [Theory] 37 | [InlineData(null, null, "v4.6")] 38 | [InlineData(null, ".NETCoreApp", null)] 39 | [InlineData(null, "Unknown", null)] 40 | public void GetTargetFramework_Throws(string targetFramework, string targetFrameworkIdentifier, string targetFrameworkVersion) 41 | { 42 | var properties = new Dictionary(); 43 | if (targetFramework != null) 44 | properties.Add("TargetFramework", targetFramework); 45 | if (targetFrameworkIdentifier != null) 46 | properties.Add("TargetFrameworkIdentifier", targetFrameworkIdentifier); 47 | if (targetFrameworkVersion != null) 48 | properties.Add("TargetFrameworkVersion", targetFrameworkVersion); 49 | 50 | var project = IProjectFactory.Create(properties); 51 | 52 | Assert.Throws(() => ProjectExtensions.GetTargetFramework(project)); 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /ProjectSimplifier.Tests/ProjectSimplifier.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /ProjectSimplifier.Tests/PropertiesDiffTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using ProjectSimplifier.Tests.Mocks; 4 | using Xunit; 5 | 6 | namespace ProjectSimplifier.Tests 7 | { 8 | public class PropertiesDiffTests 9 | { 10 | [Theory] 11 | [InlineData("A=B", "A", "A=B", "A", null, null)] 12 | [InlineData("A=B", "A", "D=E", null, "A", null)] 13 | [InlineData("A=B;C=D", "A", "C=D", null, "A", null)] 14 | [InlineData("A=B;C=D", "A", "A=C", null, null, "A")] 15 | [InlineData("A=B;C=D", "A;C", "C=E", null, "A", "C")] 16 | [InlineData("A=B;C=D;E=F", "A;C;E", "C=E;E=F", "E", "A", "C")] 17 | public void PropertiesDiff(string projectProps, string propsInFile, string sdkBaselineProps, string expectedDefaultedProps, string expectedNotDefaultedProps, string expectedChangedProps) 18 | { 19 | var project = IProjectFactory.Create(projectProps, propsInFile); 20 | var sdkBaselineProject = IProjectFactory.Create(sdkBaselineProps, propsInFile); 21 | 22 | var differ = new Differ(project, sdkBaselineProject); 23 | 24 | var diff = differ.GetPropertiesDiff(); 25 | 26 | if (expectedDefaultedProps == null) 27 | { 28 | Assert.Empty(diff.DefaultedProperties); 29 | } 30 | else 31 | { 32 | Assert.Equal(diff.DefaultedProperties.Select(p=> p.Name), expectedDefaultedProps.Split(';')); 33 | } 34 | 35 | if (expectedNotDefaultedProps == null) 36 | { 37 | Assert.Empty(diff.NotDefaultedProperties); 38 | } 39 | else 40 | { 41 | Assert.Equal(diff.NotDefaultedProperties.Select(p => p.Name), expectedNotDefaultedProps.Split(';')); 42 | } 43 | 44 | if (expectedChangedProps == null) 45 | { 46 | Assert.Empty(diff.ChangedProperties); 47 | } 48 | else 49 | { 50 | Assert.Equal(diff.ChangedProperties.Select(p => p.oldProp.Name), expectedChangedProps.Split(';')); 51 | } 52 | } 53 | 54 | [Fact] 55 | public void PropertiesDiff_GetLines() 56 | { 57 | var defaultedProps = IProjectFactory.Create("A=B;C=D").Properties.ToImmutableArray(); 58 | var removedProps = IProjectFactory.Create("E=F;G=H").Properties.ToImmutableArray(); 59 | var changedProps = IProjectFactory.Create("I=J").Properties.Zip(IProjectFactory.Create("I=K").Properties, (a, b) => (a, b)).ToImmutableArray(); 60 | var diff = new PropertiesDiff(defaultedProps, removedProps, changedProps); 61 | 62 | var lines = diff.GetDiffLines(); 63 | var expectedLines = new[] 64 | { 65 | "Properties that are defaulted by the SDK:", 66 | "- A = B", 67 | "- C = D", 68 | "", 69 | "Properties that are not defaulted by the SDK:", 70 | "+ E = F", 71 | "+ G = H", 72 | "", 73 | "Properties whose value is different from the SDK's default:", 74 | "- I = J", 75 | "+ I = K", 76 | "" 77 | }; 78 | 79 | Assert.Equal(expectedLines, lines); 80 | } 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /ProjectSimplifier.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26606.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectSimplifier", "ProjectSimplifier\ProjectSimplifier.csproj", "{AAC442C6-A00F-4EA5-A992-2F1E9CEEB6F7}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectSimplifier.Tests", "ProjectSimplifier.Tests\ProjectSimplifier.Tests.csproj", "{1E4BD1E1-C0F6-4216-AB17-F7EA8C461FC1}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {AAC442C6-A00F-4EA5-A992-2F1E9CEEB6F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {AAC442C6-A00F-4EA5-A992-2F1E9CEEB6F7}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {AAC442C6-A00F-4EA5-A992-2F1E9CEEB6F7}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {AAC442C6-A00F-4EA5-A992-2F1E9CEEB6F7}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {1E4BD1E1-C0F6-4216-AB17-F7EA8C461FC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {1E4BD1E1-C0F6-4216-AB17-F7EA8C461FC1}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {1E4BD1E1-C0F6-4216-AB17-F7EA8C461FC1}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {1E4BD1E1-C0F6-4216-AB17-F7EA8C461FC1}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /ProjectSimplifier/BaselineProject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Immutable; 3 | 4 | namespace ProjectSimplifier 5 | { 6 | internal struct BaselineProject 7 | { 8 | public readonly ImmutableArray GlobalProperties; 9 | public readonly ImmutableDictionary TargetProjectProperties; 10 | public readonly UnconfiguredProject Project; 11 | public readonly ProjectStyle ProjectStyle; 12 | 13 | public BaselineProject(UnconfiguredProject project, ImmutableArray globalProperties, ImmutableDictionary targetProjectProperties, ProjectStyle projectStyle) : this() 14 | { 15 | GlobalProperties = globalProperties; 16 | TargetProjectProperties = targetProjectProperties; 17 | Project = project ?? throw new ArgumentNullException(nameof(project)); 18 | ProjectStyle = projectStyle; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ProjectSimplifier/Converter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Immutable; 3 | using System.Linq; 4 | using Microsoft.Build.Construction; 5 | 6 | namespace ProjectSimplifier 7 | { 8 | internal class Converter 9 | { 10 | private readonly UnconfiguredProject _project; 11 | private readonly BaselineProject _sdkBaselineProject; 12 | private readonly IProjectRootElement _projectRootElement; 13 | private readonly ImmutableDictionary _differs; 14 | 15 | public Converter(UnconfiguredProject project, BaselineProject sdkBaselineProject, IProjectRootElement projectRootElement) 16 | { 17 | _project = project ?? throw new ArgumentNullException(nameof(project)); 18 | _sdkBaselineProject = sdkBaselineProject; 19 | _projectRootElement = projectRootElement ?? throw new ArgumentNullException(nameof(projectRootElement)); 20 | _differs = _project.ConfiguredProjects.Select(p => (p.Key, new Differ(p.Value, _sdkBaselineProject.Project.ConfiguredProjects[p.Key]))).ToImmutableDictionary(kvp => kvp.Item1, kvp => kvp.Item2); 21 | } 22 | 23 | internal void GenerateProjectFile(string outputProjectPath) 24 | { 25 | ChangeImports(); 26 | 27 | RemoveDefaultedProperties(); 28 | AddTargetFrameworkProperty(); 29 | AddTargetProjectProperties(); 30 | 31 | RemoveOrUpdateItems(); 32 | AddItemRemovesForIntroducedItems(); 33 | 34 | _projectRootElement.ToolsVersion = null; 35 | _projectRootElement.Save(outputProjectPath); 36 | Console.WriteLine($"Successfully converted project to {outputProjectPath}"); 37 | } 38 | 39 | private void ChangeImports() 40 | { 41 | var projectStyle = _sdkBaselineProject.ProjectStyle; 42 | 43 | if (projectStyle == ProjectStyle.Default) 44 | { 45 | foreach (var import in _projectRootElement.Imports) 46 | { 47 | _projectRootElement.RemoveChild(import); 48 | } 49 | _projectRootElement.Sdk = "Microsoft.NET.Sdk"; 50 | } 51 | } 52 | 53 | private void RemoveDefaultedProperties() 54 | { 55 | foreach (var propGroup in _projectRootElement.PropertyGroups) 56 | { 57 | var configurationName = MSBuildUtilities.GetConfigurationName(propGroup.Condition); 58 | var propDiff = _differs[configurationName].GetPropertiesDiff(); 59 | 60 | foreach (var prop in propGroup.Properties) 61 | { 62 | // These properties were added to the baseline - so don't treat them as defaulted properties. 63 | if (_sdkBaselineProject.GlobalProperties.Contains(prop.Name, StringComparer.OrdinalIgnoreCase)) 64 | { 65 | continue; 66 | } 67 | 68 | if (propDiff.DefaultedProperties.Select(p => p.Name).Contains(prop.Name, StringComparer.OrdinalIgnoreCase) || 69 | Facts.PropertiesNotNeededInCPS.Contains(prop.Name, StringComparer.OrdinalIgnoreCase)) 70 | { 71 | propGroup.RemoveChild(prop); 72 | } 73 | } 74 | 75 | // If a propertyGroup is empty we can remove it unless it had a condition from which a configuration is inferred. 76 | if (propGroup.Properties.Count == 0 && string.IsNullOrEmpty(configurationName)) 77 | { 78 | _projectRootElement.RemoveChild(propGroup); 79 | } 80 | } 81 | } 82 | 83 | private void RemoveOrUpdateItems() 84 | { 85 | foreach (var itemGroup in _projectRootElement.ItemGroups) 86 | { 87 | var configurationName = MSBuildUtilities.GetConfigurationName(itemGroup.Condition); 88 | var itemsDiff = _differs[configurationName].GetItemsDiff(); 89 | 90 | foreach (var item in itemGroup.Items) 91 | { 92 | ItemsDiff itemTypeDiff = itemsDiff.FirstOrDefault(id => id.ItemType.Equals(item.ItemType, StringComparison.OrdinalIgnoreCase)); 93 | if (!itemTypeDiff.DefaultedItems.IsDefault) 94 | { 95 | var defaultedItems = itemTypeDiff.DefaultedItems.Select(i => i.EvaluatedInclude); 96 | if (defaultedItems.Contains(item.Include, StringComparer.OrdinalIgnoreCase)) 97 | { 98 | itemGroup.RemoveChild(item); 99 | } 100 | } 101 | 102 | if(!itemTypeDiff.ChangedItems.IsDefault) 103 | { 104 | var changedItems = itemTypeDiff.ChangedItems.Select(i => i.EvaluatedInclude); 105 | if (changedItems.Contains(item.Include, StringComparer.OrdinalIgnoreCase)) 106 | { 107 | var path = item.Include; 108 | item.Include = null; 109 | item.Update = path; 110 | } 111 | } 112 | } 113 | 114 | if (itemGroup.Items.Count == 0) 115 | { 116 | _projectRootElement.RemoveChild(itemGroup); 117 | } 118 | } 119 | } 120 | 121 | private void AddItemRemovesForIntroducedItems() 122 | { 123 | var introducedItems = _differs.Values 124 | .SelectMany( 125 | differ => differ.GetItemsDiff() 126 | .Where(diff => Facts.GlobbedItemTypes.Contains(diff.ItemType, StringComparer.OrdinalIgnoreCase)) 127 | .SelectMany(diff => diff.IntroducedItems)) 128 | .Distinct(ProjectItemComparer.IncludeComparer); 129 | 130 | if (introducedItems.Any()) 131 | { 132 | var itemGroup = _projectRootElement.AddItemGroup(); 133 | foreach (var introducedItem in introducedItems) 134 | { 135 | var item = itemGroup.AddItem(introducedItem.ItemType, introducedItem.EvaluatedInclude); 136 | item.Include = null; 137 | item.Remove = introducedItem.EvaluatedInclude; 138 | } 139 | } 140 | } 141 | 142 | private void AddTargetFrameworkProperty() 143 | { 144 | if (_sdkBaselineProject.GlobalProperties.Contains("TargetFramework", StringComparer.OrdinalIgnoreCase)) 145 | { 146 | // The original project had a TargetFramework property. No need to add it again. 147 | return; 148 | } 149 | 150 | var propGroup = GetOrCreateEmptyPropertyGroup(); 151 | 152 | var targetFrameworkElement = _projectRootElement.CreatePropertyElement("TargetFramework"); 153 | targetFrameworkElement.Value = _sdkBaselineProject.Project.FirstConfiguredProject.GetProperty("TargetFramework").EvaluatedValue; 154 | propGroup.PrependChild(targetFrameworkElement); 155 | } 156 | 157 | private ProjectPropertyGroupElement GetOrCreateEmptyPropertyGroup() 158 | { 159 | bool IsAfterFirstImport(ProjectPropertyGroupElement propertyGroup) 160 | { 161 | if (_sdkBaselineProject.ProjectStyle == ProjectStyle.Default) 162 | return true; 163 | 164 | var firstImport = _projectRootElement.Imports.Where(i => i.Label != Facts.SharedProjectsImportLabel).First(); 165 | return propertyGroup.Location.Line > firstImport.Location.Line; 166 | } 167 | 168 | return _projectRootElement.PropertyGroups.FirstOrDefault(pg => pg.Condition == "" && 169 | IsAfterFirstImport(pg)) 170 | ?? _projectRootElement.AddPropertyGroup(); 171 | } 172 | 173 | private void AddTargetProjectProperties() 174 | { 175 | if (_sdkBaselineProject.TargetProjectProperties.IsEmpty) 176 | { 177 | return; 178 | } 179 | 180 | var propGroup = GetOrCreateEmptyPropertyGroup(); 181 | 182 | foreach (var prop in _sdkBaselineProject.TargetProjectProperties) 183 | { 184 | propGroup.AddProperty(prop.Key, prop.Value); 185 | } 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /ProjectSimplifier/Differ.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Immutable; 4 | using System.IO; 5 | using System.Linq; 6 | 7 | namespace ProjectSimplifier 8 | { 9 | internal class Differ 10 | { 11 | private readonly IProject _project; 12 | private readonly IProject _sdkBaselineProject; 13 | 14 | public Differ(IProject project, IProject sdkBaselineProject) 15 | { 16 | _project = project ?? throw new System.ArgumentNullException(nameof(project)); 17 | _sdkBaselineProject = sdkBaselineProject ?? throw new System.ArgumentNullException(nameof(sdkBaselineProject)); 18 | } 19 | 20 | public PropertiesDiff GetPropertiesDiff() 21 | { 22 | var defaultedProps = ImmutableArray.CreateBuilder(); 23 | var notDefaultedProps = ImmutableArray.CreateBuilder(); 24 | var changedProps = ImmutableArray.CreateBuilder<(IProjectProperty, IProjectProperty)>(); 25 | 26 | var propertiesInFile = _project.Properties.Where(p => p.IsDefinedInProject).Select(p => p.Name).Distinct(); 27 | 28 | foreach (var propInFile in propertiesInFile) 29 | { 30 | var originalEvaluatedProp = _project.GetProperty(propInFile); 31 | var newEvaluatedProp = _sdkBaselineProject.GetProperty(propInFile); 32 | if (newEvaluatedProp != null) 33 | { 34 | if (!originalEvaluatedProp.EvaluatedValue.Equals(newEvaluatedProp.EvaluatedValue, StringComparison.OrdinalIgnoreCase)) 35 | { 36 | changedProps.Add((originalEvaluatedProp, newEvaluatedProp)); 37 | } 38 | else 39 | { 40 | defaultedProps.Add(newEvaluatedProp); 41 | } 42 | } 43 | else 44 | { 45 | notDefaultedProps.Add(originalEvaluatedProp); 46 | } 47 | } 48 | 49 | return new PropertiesDiff(defaultedProps.ToImmutable(), notDefaultedProps.ToImmutable(), changedProps.ToImmutable()); 50 | } 51 | 52 | public ImmutableArray GetItemsDiff() 53 | { 54 | var oldItemGroups = from oldItem in _project.Items group oldItem by oldItem.ItemType; 55 | var newItemGroups = from newItem in _sdkBaselineProject.Items group newItem by newItem.ItemType; 56 | 57 | var addedRemovedGroups = from og in oldItemGroups 58 | from ng in newItemGroups 59 | where og.Key.Equals(ng.Key, StringComparison.OrdinalIgnoreCase) 60 | select new { 61 | ItemType = og.Key, 62 | DefaultedItems = ng.Intersect(og, ProjectItemComparer.MetadataComparer), 63 | IntroducedItems = ng.Except(og, ProjectItemComparer.IncludeComparer), 64 | NotDefaultedItems = og.Except(ng, ProjectItemComparer.IncludeComparer), 65 | ChangedItems = GetChangedItems(og, ng), 66 | }; 67 | 68 | var builder = ImmutableArray.CreateBuilder(); 69 | 70 | foreach (var group in addedRemovedGroups) 71 | { 72 | var defaultedItems = group.DefaultedItems.ToImmutableArray(); 73 | var notDefaultedItems = group.NotDefaultedItems.ToImmutableArray(); 74 | var introducedItems = group.IntroducedItems.ToImmutableArray(); 75 | var changedItems = group.ChangedItems.ToImmutableArray(); 76 | 77 | var diff = new ItemsDiff(group.ItemType, defaultedItems, notDefaultedItems, introducedItems, changedItems); 78 | builder.Add(diff); 79 | } 80 | 81 | return builder.ToImmutable(); 82 | } 83 | 84 | private IEnumerable GetChangedItems(IGrouping oldGroup, IGrouping newGroup) 85 | { 86 | var itemsWithSameInclude = newGroup.Intersect(oldGroup, ProjectItemComparer.IncludeComparer); 87 | var itemsWithSameMetadata = newGroup.Intersect(oldGroup, ProjectItemComparer.MetadataComparer); 88 | 89 | return itemsWithSameInclude.Except(itemsWithSameMetadata); 90 | } 91 | 92 | public void GenerateReport(string reportFilePath) 93 | { 94 | var report = new List(); 95 | report.AddRange(GetPropertiesDiff().GetDiffLines()); 96 | 97 | var itemDiffs = GetItemsDiff(); 98 | foreach (var diff in itemDiffs) 99 | { 100 | // Items that start with _ are private items. Not much value in reporting them. 101 | if (diff.ItemType.StartsWith("_")) 102 | { 103 | continue; 104 | } 105 | 106 | report.AddRange(diff.GetDiffLines()); 107 | } 108 | 109 | File.WriteAllLines(reportFilePath, report); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /ProjectSimplifier/Facts.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | 4 | namespace ProjectSimplifier 5 | { 6 | internal static class Facts 7 | { 8 | /// 9 | /// Props files which are known to be imported in standard projects created from templates that can be converted to use the SDK 10 | /// 11 | public static ImmutableArray PropsConvertibleToSDK => ImmutableArray.Create("Microsoft.Common.props"); 12 | 13 | /// 14 | /// Targets files which are known to be imported in standard projects created from templates that can be converted to use the SDK. 15 | /// 16 | public static ImmutableArray TargetsConvertibleToSDK => ImmutableArray.Create( 17 | "Microsoft.CSharp.targets", 18 | "Microsoft.VisualBasic.targets", 19 | "Microsoft.Portable.CSharp.targets", 20 | "Microsoft.Portable.VisualBasic.targets"); 21 | 22 | /// 23 | /// Mapping of PCL profiles to netstandard versions. 24 | /// 25 | public static ImmutableDictionary PCLToNetStandardVersionMapping => ImmutableDictionary.CreateRange(new Dictionary 26 | { 27 | { "Profile7", "1.1" }, 28 | { "Profile31", "1.0" }, 29 | { "Profile32", "1.2" }, 30 | { "Profile44", "1.2" }, 31 | { "Profile49", "1.0" }, 32 | { "Profile78", "1.0" }, 33 | { "Profile84", "1.0" }, 34 | { "Profile111", "1.0" }, 35 | { "Profile151", "1.0" }, 36 | { "Profile157", "1.0" }, 37 | { "Profile259", "1.0" }, 38 | }); 39 | 40 | public static ImmutableArray PropertiesNotNeededInCPS => ImmutableArray.Create( 41 | "ProjectGuid", // Guids are in-memory in CPS 42 | "ProjectTypeGuids", // Not used - capabilities are used instead 43 | "TargetFrameworkIdentifier", // Inferred from TargetFramework 44 | "TargetFrameworkVersion", // Inferred from TargetFramework 45 | "TargetFrameworkProfile" // Inferred from TargetFramework 46 | ); 47 | 48 | public static ImmutableArray GlobbedItemTypes => ImmutableArray.Create( 49 | "Compile", 50 | "EmbeddedResource", 51 | "None" 52 | ); 53 | 54 | public const string SharedProjectsImportLabel = "Shared"; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /ProjectSimplifier/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 |  2 | // This file is used by Code Analysis to maintain SuppressMessage 3 | // attributes that are applied to this project. 4 | // Project-level suppressions either have no target or are given 5 | // a specific target and scoped to a namespace, type, member, etc. 6 | 7 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0033:Use explicitly provided tuple name", Justification = "Appveyor doesnt support 15.3 yet.")] 8 | 9 | -------------------------------------------------------------------------------- /ProjectSimplifier/InternalsVisibleTo.cs: -------------------------------------------------------------------------------- 1 | [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ProjectSimplifier.Tests")] 2 | -------------------------------------------------------------------------------- /ProjectSimplifier/ItemsDiff.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using System.Linq; 4 | 5 | namespace ProjectSimplifier 6 | { 7 | internal struct ItemsDiff 8 | { 9 | public readonly string ItemType; 10 | public readonly ImmutableArray DefaultedItems; 11 | public readonly ImmutableArray NotDefaultedItems; 12 | public readonly ImmutableArray IntroducedItems; 13 | public readonly ImmutableArray ChangedItems; 14 | 15 | public ItemsDiff(string itemType, ImmutableArray defaultedItems, ImmutableArray notDefaultedItems, ImmutableArray introducedItems, ImmutableArray changedItems) : this() 16 | { 17 | ItemType = itemType; 18 | DefaultedItems = defaultedItems; 19 | NotDefaultedItems = notDefaultedItems; 20 | IntroducedItems = introducedItems; 21 | ChangedItems = changedItems; 22 | } 23 | 24 | public ImmutableArray GetDiffLines() 25 | { 26 | var lines = ImmutableArray.CreateBuilder(); 27 | 28 | if (!DefaultedItems.IsEmpty || !NotDefaultedItems.IsEmpty || !IntroducedItems.IsEmpty || !ChangedItems.IsEmpty) 29 | { 30 | lines.Add($"{ ItemType} items:"); 31 | if (!DefaultedItems.IsEmpty) 32 | { 33 | lines.AddRange(DefaultedItems.Select(s => $"- {s.EvaluatedInclude}")); 34 | } 35 | 36 | if (!NotDefaultedItems.IsEmpty) 37 | { 38 | lines.AddRange(NotDefaultedItems.Select(s => $"= {s.EvaluatedInclude}")); 39 | } 40 | 41 | if (!IntroducedItems.IsEmpty) 42 | { 43 | lines.AddRange(IntroducedItems.Select(s => $"+ {s.EvaluatedInclude}")); 44 | } 45 | 46 | lines.Add(""); 47 | } 48 | 49 | return lines.ToImmutable(); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /ProjectSimplifier/MSBuildProject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Build.Evaluation; 5 | 6 | namespace ProjectSimplifier 7 | { 8 | /// 9 | /// Interface used to Mock access to MSBuild's Project apis. 10 | /// 11 | public interface IProject 12 | { 13 | ICollection Properties { get; } 14 | 15 | ICollection Items { get; } 16 | 17 | IProjectProperty GetProperty(string name); 18 | 19 | string GetPropertyValue(string name); 20 | } 21 | 22 | public interface IProjectProperty 23 | { 24 | string Name { get; } 25 | string EvaluatedValue { get; } 26 | string UnevaluatedValue { get; } 27 | bool IsDefinedInProject { get; } 28 | } 29 | 30 | public interface IProjectItem 31 | { 32 | string ItemType { get; } 33 | string EvaluatedInclude { get; } 34 | IEnumerable DirectMetadata { get; } 35 | } 36 | 37 | public interface IProjectMetadata : IEquatable 38 | { 39 | string Name { get; } 40 | string UnevaluatedValue { get; } 41 | string EvaluatedValue { get; } 42 | } 43 | 44 | internal class MSBuildProjectProperty : IProjectProperty 45 | { 46 | private readonly ProjectProperty _property; 47 | 48 | public MSBuildProjectProperty(ProjectProperty property) 49 | { 50 | _property = property; 51 | } 52 | 53 | public string Name => _property.Name; 54 | 55 | public string EvaluatedValue => _property.EvaluatedValue; 56 | 57 | public string UnevaluatedValue => _property.UnevaluatedValue; 58 | 59 | public bool IsDefinedInProject => !_property.IsImported && 60 | !_property.IsEnvironmentProperty && 61 | !_property.IsGlobalProperty && 62 | !_property.IsReservedProperty; 63 | } 64 | 65 | internal class MSBuildProjectItem : IProjectItem 66 | { 67 | private readonly ProjectItem _item; 68 | 69 | public MSBuildProjectItem(ProjectItem item) 70 | { 71 | _item = item; 72 | } 73 | 74 | public string ItemType => _item.ItemType; 75 | 76 | public string EvaluatedInclude => _item.EvaluatedInclude; 77 | 78 | public IEnumerable DirectMetadata => _item.DirectMetadata.Select(md => new MSBuildProjectMetadata(md)); 79 | } 80 | 81 | internal class MSBuildProjectMetadata : IProjectMetadata 82 | { 83 | private readonly ProjectMetadata _projectMetadata; 84 | 85 | public MSBuildProjectMetadata(ProjectMetadata projectMetadata) 86 | { 87 | _projectMetadata = projectMetadata; 88 | } 89 | 90 | public string Name => _projectMetadata.Name; 91 | 92 | public string UnevaluatedValue => _projectMetadata.UnevaluatedValue; 93 | 94 | public string EvaluatedValue => _projectMetadata.EvaluatedValue; 95 | 96 | public bool Equals(IProjectMetadata other) 97 | { 98 | return _projectMetadata.Name.Equals(other.Name) && 99 | _projectMetadata.UnevaluatedValue.Equals(other.UnevaluatedValue) && 100 | _projectMetadata.EvaluatedValue.Equals(other.EvaluatedValue); 101 | } 102 | } 103 | 104 | internal class MSBuildProject : IProject 105 | { 106 | private readonly Project _project; 107 | 108 | public MSBuildProject(Project project) => _project = project ?? throw new ArgumentNullException(nameof(project)); 109 | 110 | public ICollection Properties => _project.Properties.Select(p => new MSBuildProjectProperty(p)).ToArray(); 111 | 112 | public ICollection Items => _project.Items.Select(i => new MSBuildProjectItem(i)).ToArray(); 113 | 114 | public IProjectProperty GetProperty(string name) => _project.GetProperty(name) != null ? new MSBuildProjectProperty(_project.GetProperty(name)) : null; 115 | 116 | public string GetPropertyValue(string name) => _project.GetPropertyValue(name); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /ProjectSimplifier/MSBuildProjectRootElement.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.Build.Construction; 3 | 4 | namespace ProjectSimplifier 5 | { 6 | public interface IProjectRootElement 7 | { 8 | string ToolsVersion { get; set; } 9 | string Sdk { get; set; } 10 | ICollection Imports { get; } 11 | ICollection ImportGroups { get; } 12 | ICollection PropertyGroups { get; } 13 | ICollection ItemGroups { get; } 14 | 15 | ProjectPropertyElement CreatePropertyElement(string propertyName); 16 | ProjectPropertyGroupElement AddPropertyGroup(); 17 | ProjectItemGroupElement AddItemGroup(); 18 | 19 | void Save(string path); 20 | void RemoveChild(ProjectElement child); 21 | void Reload(bool throwIfUnsavedChanges = true, bool? preserveFormatting = null); 22 | } 23 | 24 | 25 | internal class MSBuildProjectRootElement : IProjectRootElement 26 | { 27 | private readonly ProjectRootElement _rootElement; 28 | 29 | public MSBuildProjectRootElement(ProjectRootElement rootElement) 30 | { 31 | _rootElement = rootElement; 32 | } 33 | 34 | public string ToolsVersion { get => _rootElement.ToolsVersion; set => _rootElement.ToolsVersion = value; } 35 | public string Sdk { get => _rootElement.Sdk; set => _rootElement.Sdk = value; } 36 | public ICollection Imports => _rootElement.Imports; 37 | public ICollection ImportGroups => _rootElement.ImportGroups; 38 | public ICollection PropertyGroups => _rootElement.PropertyGroups; 39 | public ICollection ItemGroups => _rootElement.ItemGroups; 40 | 41 | public ProjectItemGroupElement AddItemGroup() => _rootElement.AddItemGroup(); 42 | 43 | public ProjectPropertyGroupElement AddPropertyGroup() => _rootElement.AddPropertyGroup(); 44 | public ProjectPropertyElement CreatePropertyElement(string name) => _rootElement.CreatePropertyElement(name); 45 | 46 | public void Reload(bool throwIfUnsavedChanges = true, bool? preserveFormatting = null) => _rootElement.Reload(throwIfUnsavedChanges, preserveFormatting); 47 | public void RemoveChild(ProjectElement child) => _rootElement.RemoveChild(child); 48 | public void Save(string path) => _rootElement.Save(path); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ProjectSimplifier/MSBuildUtilities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Immutable; 4 | using System.Linq; 5 | using System.Text.RegularExpressions; 6 | 7 | namespace ProjectSimplifier 8 | { 9 | internal static class MSBuildUtilities 10 | { 11 | /// 12 | /// matches $(name) pattern 13 | /// 14 | private static readonly Regex DimensionNameInConditionRegex = new Regex(@"^\$\(([^\$\(\)]*)\)$"); 15 | 16 | /// 17 | /// Converts configuration dimensional value vector to a msbuild condition 18 | /// Use the standard format of 19 | /// '$(DimensionName1)|$(DimensionName2)|...|$(DimensionNameN)'=='DimensionValue1|...|DimensionValueN' 20 | /// 21 | /// vector of configuration dimensional properties 22 | /// msbuild condition representation 23 | internal static string DimensionalValuePairsToCondition(ImmutableDictionary dimensionalValues) 24 | { 25 | if (null == dimensionalValues || 0 == dimensionalValues.Count) 26 | { 27 | return string.Empty; // no condition. Returns empty string to match MSBuild. 28 | } 29 | 30 | string left = string.Empty; 31 | string right = string.Empty; 32 | 33 | foreach (string key in dimensionalValues.Keys) 34 | { 35 | if (!string.IsNullOrEmpty(left)) 36 | { 37 | left = left + "|"; 38 | right = right + "|"; 39 | } 40 | 41 | left += "$(" + key + ")"; 42 | right += dimensionalValues[key]; 43 | } 44 | 45 | string condition = "'" + left + "'=='" + right + "'"; 46 | return condition; 47 | } 48 | 49 | /// 50 | /// Returns a name of a configuration like Debug|AnyCPU 51 | /// 52 | internal static string GetConfigurationName(ImmutableDictionary dimensionValues) => dimensionValues.IsEmpty ? "" : dimensionValues.Values.Aggregate((x, y) => $"{x}|{y}"); 53 | 54 | /// 55 | /// Returns a name of a configuration like Debug|AnyCPU 56 | /// 57 | internal static string GetConfigurationName(string condition) 58 | { 59 | if (ConditionToDimensionValues(condition, out var dimensionValues)) 60 | { 61 | return GetConfigurationName(dimensionValues); 62 | } 63 | 64 | return ""; 65 | } 66 | 67 | /// 68 | /// Tries to parse an MSBuild condition to a dimensional vector 69 | /// only matches standard pattern: 70 | /// '$(DimensionName1)|$(DimensionName2)|...|$(DimensionNameN)'=='DimensionValue1|...|DimensionValueN' 71 | /// 72 | /// msbuild condition string 73 | /// configuration dimensions vector (output) 74 | /// true on success 75 | internal static bool ConditionToDimensionValues(string condition, out ImmutableDictionary dimensionalValues) 76 | { 77 | string left; 78 | string right; 79 | dimensionalValues = ImmutableDictionary.Empty; 80 | 81 | if (string.IsNullOrEmpty(condition)) 82 | { 83 | // yes empty condition is recognized as a empty dimension vector 84 | return true; 85 | } 86 | 87 | int equalPos = condition.IndexOf("==", StringComparison.OrdinalIgnoreCase); 88 | if (equalPos <= 0) 89 | { 90 | return false; 91 | } 92 | 93 | left = condition.Substring(0, equalPos).Trim(); 94 | right = condition.Substring(equalPos + 2).Trim(); 95 | 96 | // left and right needs to ba a valid quoted strings 97 | if (!UnquoteString(ref left) || !UnquoteString(ref right)) 98 | { 99 | return false; 100 | } 101 | 102 | string[] dimensionNamesInCondition = left.Split(new char[] { '|' }); 103 | string[] dimensionValuesInCondition = right.Split(new char[] { '|' }); 104 | 105 | // number of keys need to match number of values 106 | if (dimensionNamesInCondition.Length == 0 || dimensionNamesInCondition.Length != dimensionValuesInCondition.Length) 107 | { 108 | return false; 109 | } 110 | 111 | Dictionary parsedDimensionalValues = new Dictionary(dimensionNamesInCondition.Length); 112 | 113 | for (int i = 0; i < dimensionNamesInCondition.Length; i++) 114 | { 115 | // matches "$(name)" patern. 116 | Match match = DimensionNameInConditionRegex.Match(dimensionNamesInCondition[i]); 117 | if (!match.Success) 118 | { 119 | return false; 120 | } 121 | 122 | string dimensionName = match.Groups[1].ToString(); 123 | if (string.IsNullOrEmpty(dimensionName)) 124 | { 125 | return false; 126 | } 127 | 128 | parsedDimensionalValues[dimensionName] = dimensionValuesInCondition[i]; 129 | } 130 | 131 | dimensionalValues = parsedDimensionalValues.ToImmutableDictionary(); 132 | return true; 133 | } 134 | 135 | /// 136 | /// Unquote string. It simply removes the starting and ending "'", and checks they are present before. 137 | /// 138 | /// string tu unquote 139 | /// true if string is successfuly unquoted 140 | private static bool UnquoteString(ref string s) 141 | { 142 | if (s.Length < 2 || s[0] != '\'' || s[s.Length - 1] != '\'') 143 | { 144 | return false; 145 | } 146 | 147 | s = s.Substring(1, s.Length - 2); 148 | return true; 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /ProjectSimplifier/Options.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CommandLine; 3 | 4 | namespace ProjectSimplifier 5 | { 6 | internal class Options 7 | { 8 | [Value(0, HelpText = "Full path to the project file", Required = true)] 9 | public string ProjectFilePath { get; set; } 10 | 11 | [Option('r', "roslyntargetspath", 12 | HelpText = "Path to the roslyn targets")] 13 | public string RoslynTargetsPath { get; set; } 14 | 15 | [Option('s', "msbuildsdkdspath", 16 | HelpText = "Path to the MSBuild SDKs")] 17 | public string MSBuildSdksPath { get; set; } 18 | 19 | [Option('m', "msbuildpath", 20 | HelpText = "Path to the MSBuild.exe")] 21 | public string MSBuildPath { get; set; } 22 | 23 | [Option('p', "properties", 24 | HelpText = "Properties to set in the target project before converting")] 25 | public IEnumerable TargetProjectProperties { get; set; } 26 | } 27 | 28 | [Verb("log", HelpText = "Log properties and items in the project and in a SDK-based baseline")] 29 | internal class LogOptions : Options 30 | { 31 | [Option('c', "currentProjectLogPath", 32 | HelpText = "Location to log the current project's properties and items", 33 | Default = "currentProject.log")] 34 | public string CurrentProjectLogPath { get; set; } 35 | 36 | [Option('b', "sdkBaseLineProjectLogPath", 37 | HelpText = "Location to log a sdk baseline project's properties and items", 38 | Default = "sdkBaseLineProject.log")] 39 | public string SdkBaseLineProjectLogPath { get; set; } 40 | } 41 | 42 | [Verb("diff", HelpText = "Diff a given project against a SDK baseline")] 43 | internal class DiffOptions : Options 44 | { 45 | [Option('d', "diffReportPath", 46 | HelpText = "Location to output a diff of the current project against a sdk baseline", 47 | Default = "report.diff")] 48 | public string DiffReportPath { get; set; } 49 | } 50 | 51 | [Verb("convert", HelpText = "Convert a given project to be based on the SDK")] 52 | internal class ConvertOptions : Options 53 | { 54 | [Option('o', "outputProjectPath", 55 | HelpText = "Location to output the converted project", 56 | Required = false)] 57 | public string OutputProjectPath { get; set; } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /ProjectSimplifier/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using CommandLine; 5 | 6 | namespace ProjectSimplifier 7 | { 8 | class Program 9 | { 10 | static int Main(string[] args) 11 | { 12 | var options = Parser.Default.ParseArguments(args); 13 | switch (options) 14 | { 15 | case Parsed command: 16 | var optionsValue = command.Value as Options; 17 | var msbuildPath = HookAssemblyResolveForMSBuild(optionsValue); 18 | if (msbuildPath != null) 19 | { 20 | return Run(optionsValue); 21 | } 22 | return -1; 23 | 24 | case NotParsed notParsed: 25 | foreach(var error in notParsed.Errors) 26 | { 27 | Console.WriteLine(error); 28 | } 29 | return 1; 30 | } 31 | return 1; 32 | } 33 | 34 | private static string HookAssemblyResolveForMSBuild(Options options) 35 | { 36 | var msbuildPath = GetMSBuildPath(options); 37 | if (msbuildPath == null) 38 | { 39 | Console.WriteLine("Cannot find MSBuild. Please pass in a path to msbuild using -m or run from a developer command prompt."); 40 | return null; 41 | } 42 | 43 | AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => 44 | { 45 | var targetAssembly = Path.Combine(msbuildPath, new AssemblyName(eventArgs.Name).Name + ".dll"); 46 | return File.Exists(targetAssembly) ? Assembly.LoadFrom(targetAssembly) : null; 47 | }; 48 | 49 | return msbuildPath; 50 | } 51 | 52 | private static int Run(Options options) 53 | { 54 | try 55 | { 56 | var projectLoader = new ProjectLoader(); 57 | projectLoader.LoadProjects(options); 58 | 59 | switch (options) 60 | { 61 | case LogOptions opt: 62 | projectLoader.Project.FirstConfiguredProject.LogProjectProperties(opt.CurrentProjectLogPath); 63 | projectLoader.SdkBaselineProject.Project.FirstConfiguredProject.LogProjectProperties(opt.SdkBaseLineProjectLogPath); 64 | break; 65 | case DiffOptions opt: 66 | var differ = new Differ(projectLoader.Project.FirstConfiguredProject, projectLoader.SdkBaselineProject.Project.FirstConfiguredProject); 67 | differ.GenerateReport(opt.DiffReportPath); 68 | break; 69 | case ConvertOptions opt: 70 | var converter = new Converter(projectLoader.Project, projectLoader.SdkBaselineProject, projectLoader.ProjectRootElement); 71 | converter.GenerateProjectFile(opt.OutputProjectPath ?? opt.ProjectFilePath); 72 | break; 73 | } 74 | } 75 | catch (Exception e) 76 | { 77 | Console.WriteLine(e.ToString()); 78 | return -1; 79 | } 80 | 81 | return 0; 82 | } 83 | 84 | private static string GetMSBuildPath(Options options) 85 | { 86 | // If the user specified a msbuild path use that. 87 | if (!string.IsNullOrEmpty(options.MSBuildPath)) 88 | { 89 | return options.MSBuildPath; 90 | } 91 | 92 | // If the user is running from a developer command prompt use the MSBuild of that VS 93 | var vsinstalldir = Environment.GetEnvironmentVariable("VSINSTALLDIR"); 94 | if (!string.IsNullOrEmpty(vsinstalldir)) 95 | { 96 | var path = Path.Combine(vsinstalldir, "MSBuild", "15.0", "Bin"); 97 | Console.WriteLine($"Found VS from VSINSTALLDIR (Dev Console): {path}"); 98 | return path; 99 | }else{ 100 | //Second chance for mono 101 | var systemLibLocation = typeof(System.Object).Assembly.Location; 102 | var monoMSBuildPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(systemLibLocation),"..","msbuild", "15.0", "bin")); 103 | if(Directory.Exists(monoMSBuildPath)){ 104 | return Path.GetFullPath(monoMSBuildPath); 105 | } 106 | 107 | } 108 | 109 | return null; 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /ProjectSimplifier/ProjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | 7 | namespace ProjectSimplifier 8 | { 9 | internal static class ProjectExtensions 10 | { 11 | public static void LogProjectProperties(this IProject project, string logFileName) 12 | { 13 | var lines = new List(); 14 | foreach (var prop in project.Properties.OrderBy(p => p.Name)) 15 | { 16 | lines.Add($"{prop.Name} = {prop.EvaluatedValue}"); 17 | } 18 | File.WriteAllLines(logFileName, lines); 19 | } 20 | 21 | public static string GetTargetFramework(this IProject project) 22 | { 23 | var tf = project.GetPropertyValue("TargetFramework"); 24 | if (!string.IsNullOrEmpty(tf)) 25 | { 26 | return tf; 27 | } 28 | 29 | var tfi = project.GetPropertyValue("TargetFrameworkIdentifier"); 30 | if (tfi == "") 31 | { 32 | throw new InvalidOperationException("TargetFrameworkIdentifier is not set!"); 33 | } 34 | 35 | var tfv = project.GetPropertyValue("TargetFrameworkVersion"); 36 | 37 | switch (tfi) 38 | { 39 | case ".NETFramework": 40 | tf = "net"; 41 | break; 42 | case ".NETStandard": 43 | tf = "netstandard"; 44 | break; 45 | case ".NETCoreApp": 46 | tf = "netcoreapp"; 47 | break; 48 | case ".NETPortable": 49 | tf = "netstandard"; 50 | break; 51 | default: 52 | throw new InvalidOperationException($"Unknown TargetFrameworkIdentifier {tfi}"); 53 | } 54 | 55 | if (tfi == ".NETPortable") 56 | { 57 | var profile = project.GetPropertyValue("TargetFrameworkProfile"); 58 | 59 | if (profile == string.Empty && tfv == "v5.0") 60 | { 61 | tf = GetTargetFrameworkFromProjectJson(project); 62 | } 63 | else 64 | { 65 | var netstandardVersion = Facts.PCLToNetStandardVersionMapping[profile]; 66 | tf += netstandardVersion; 67 | } 68 | } 69 | else 70 | { 71 | if (tfv == "") 72 | { 73 | throw new InvalidOperationException("TargetFrameworkVersion is not set!"); 74 | } 75 | 76 | tf += tfv.TrimStart('v'); 77 | } 78 | 79 | return tf; 80 | } 81 | 82 | private static string GetTargetFrameworkFromProjectJson(IProject project) 83 | { 84 | string projectFolder = project.GetPropertyValue("MSBuildProjectDirectory"); 85 | string projectJsonPath = Path.Combine(projectFolder, "project.json"); 86 | 87 | string projectJsonContents = File.ReadAllText(projectJsonPath); 88 | 89 | JObject json = JObject.Parse(projectJsonContents); 90 | 91 | var frameworks = json["frameworks"]; 92 | string tf = ((JProperty)frameworks.Single()).Name; 93 | return tf; 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /ProjectSimplifier/ProjectItemComparer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace ProjectSimplifier 5 | { 6 | public class ProjectItemComparer : IEqualityComparer 7 | { 8 | private readonly bool _compareMetadata; 9 | 10 | public static ProjectItemComparer IncludeComparer = new ProjectItemComparer(compareMetadata: false); 11 | public static ProjectItemComparer MetadataComparer = new ProjectItemComparer(compareMetadata: true); 12 | 13 | private ProjectItemComparer(bool compareMetadata) 14 | { 15 | _compareMetadata = compareMetadata; 16 | } 17 | 18 | public bool Equals(IProjectItem x, IProjectItem y) 19 | { 20 | // If y has all the metadata that x has then we declare them as equal. This is because 21 | // the sdk can add new metadata but there's not reason to remove them during conversion. 22 | var metadataEqual = _compareMetadata ? 23 | x.DirectMetadata.All(xmd => y.DirectMetadata.Any( 24 | ymd => xmd.Name.Equals(ymd.Name, System.StringComparison.OrdinalIgnoreCase) && 25 | xmd.EvaluatedValue.Equals(ymd.EvaluatedValue, System.StringComparison.OrdinalIgnoreCase))) 26 | : true; 27 | 28 | return x.ItemType == y.ItemType && x.EvaluatedInclude.Equals(y.EvaluatedInclude, System.StringComparison.OrdinalIgnoreCase) && metadataEqual; 29 | } 30 | 31 | public int GetHashCode(IProjectItem obj) 32 | { 33 | return (obj.EvaluatedInclude.ToLowerInvariant() + obj.ItemType).GetHashCode(); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /ProjectSimplifier/ProjectLoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Immutable; 3 | using System.IO; 4 | using System.Linq; 5 | using Microsoft.Build.Construction; 6 | using Microsoft.Build.Evaluation; 7 | 8 | namespace ProjectSimplifier 9 | { 10 | internal class ProjectLoader 11 | { 12 | public UnconfiguredProject Project { get; private set; } 13 | public BaselineProject SdkBaselineProject { get; private set; } 14 | public IProjectRootElement ProjectRootElement { get; private set; } 15 | 16 | public void LoadProjects(Options options) 17 | { 18 | string projectFilePath = Path.GetFullPath(options.ProjectFilePath); 19 | 20 | if (!File.Exists(projectFilePath)) 21 | { 22 | Console.Error.WriteLine($"The project file '{projectFilePath}' does not exist or is inaccessible."); 23 | return; 24 | } 25 | 26 | ImmutableDictionary globalProperties = InitializeGlobalProperties(options); 27 | var collection = new ProjectCollection(globalProperties); 28 | 29 | ProjectRootElement = new MSBuildProjectRootElement(Microsoft.Build.Construction.ProjectRootElement.Open(projectFilePath, collection, preserveFormatting: true)); 30 | var configurations = DetermineConfigurations(ProjectRootElement); 31 | 32 | Project = new UnconfiguredProject(configurations); 33 | Project.LoadProjects(collection, globalProperties, projectFilePath); 34 | Console.WriteLine($"Successfully loaded project file '{projectFilePath}'."); 35 | 36 | var targetProjectProperties = options.TargetProjectProperties.ToImmutableDictionary(p => p.Split('=')[0], p => p.Split('=')[1]); 37 | SdkBaselineProject = CreateSdkBaselineProject(projectFilePath, Project.FirstConfiguredProject, globalProperties, configurations, targetProjectProperties); 38 | ProjectRootElement.Reload(throwIfUnsavedChanges: false, preserveFormatting: true); 39 | Console.WriteLine($"Successfully loaded sdk baseline of project."); 40 | } 41 | 42 | private ImmutableDictionary> DetermineConfigurations(IProjectRootElement projectRootElement) 43 | { 44 | var builder = ImmutableDictionary.CreateBuilder>(); 45 | foreach (var propertyGroup in projectRootElement.PropertyGroups) 46 | { 47 | if (MSBuildUtilities.ConditionToDimensionValues(propertyGroup.Condition, out var dimensionValues)) 48 | { 49 | var name = MSBuildUtilities.GetConfigurationName(dimensionValues); 50 | builder.Add(name, dimensionValues.ToImmutableDictionary()); 51 | } 52 | } 53 | 54 | return builder.ToImmutable(); 55 | } 56 | 57 | public static ProjectStyle GetProjectStyle(IProjectRootElement project) 58 | { 59 | if (project.ImportGroups.Any()) 60 | { 61 | return ProjectStyle.Custom; 62 | } 63 | 64 | // Exclude shared project references since they show up as imports. 65 | var imports = project.Imports.Where(i => i.Label != Facts.SharedProjectsImportLabel); 66 | if (imports.Count() == 2) 67 | { 68 | var firstImport = project.Imports.First(); 69 | var lastImport = project.Imports.Last(); 70 | 71 | var firstImportFileName = Path.GetFileName(firstImport.Project); 72 | var lastImportFileName = Path.GetFileName(lastImport.Project); 73 | 74 | if (Facts.PropsConvertibleToSDK.Contains(firstImportFileName, StringComparer.OrdinalIgnoreCase) && 75 | Facts.TargetsConvertibleToSDK.Contains(lastImportFileName, StringComparer.OrdinalIgnoreCase)) 76 | { 77 | return ProjectStyle.Default; 78 | } 79 | 80 | } 81 | 82 | return ProjectStyle.DefaultWithCustomTargets; 83 | } 84 | 85 | private static ImmutableDictionary InitializeGlobalProperties(Options options) 86 | { 87 | var globalProperties = ImmutableDictionary.CreateBuilder(); 88 | if (!string.IsNullOrEmpty(options.RoslynTargetsPath)) 89 | { 90 | globalProperties.Add("RoslynTargetsPath", options.RoslynTargetsPath); 91 | } 92 | 93 | if (!string.IsNullOrEmpty(options.MSBuildSdksPath)) 94 | { 95 | globalProperties.Add("MSBuildSDKsPath", options.MSBuildSdksPath); 96 | } 97 | 98 | return globalProperties.ToImmutable(); 99 | } 100 | 101 | /// 102 | /// Clear out the project's construction model and add a simple SDK-based project to get a baseline. 103 | /// We need to use the same name as the original csproj and same path so that all the default that derive 104 | /// from name\path get the right values (there are a lot of them). 105 | /// 106 | private BaselineProject CreateSdkBaselineProject(string projectFilePath, 107 | IProject project, 108 | ImmutableDictionary globalProperties, 109 | ImmutableDictionary> configurations, 110 | ImmutableDictionary targetProjectProperties) 111 | { 112 | var projectStyle = GetProjectStyle(ProjectRootElement); 113 | var rootElement = Microsoft.Build.Construction.ProjectRootElement.Open(projectFilePath); 114 | 115 | rootElement.RemoveAllChildren(); 116 | switch (projectStyle) 117 | { 118 | case ProjectStyle.Default: 119 | rootElement.Sdk = "Microsoft.NET.Sdk"; 120 | break; 121 | case ProjectStyle.DefaultWithCustomTargets: 122 | var imports = ProjectRootElement.Imports; 123 | 124 | void CopyImport(ProjectImportElement import) 125 | { 126 | var newImport = rootElement.AddImport(import.Project); 127 | newImport.Condition = import.Condition; 128 | } 129 | CopyImport(imports.First()); 130 | CopyImport(imports.Last()); 131 | break; 132 | default: 133 | throw new NotSupportedException("This project has custom imports in a manner that's not supported."); 134 | } 135 | 136 | var propGroup = rootElement.AddPropertyGroup(); 137 | propGroup.AddProperty("TargetFramework", project.GetTargetFramework()); 138 | propGroup.AddProperty("OutputType", project.GetPropertyValue("OutputType") ?? throw new InvalidOperationException("OutputType is not set!")); 139 | 140 | var newGlobalProperties = globalProperties.AddRange(targetProjectProperties); 141 | // Create a new collection because a project with this name has already been loaded into the global collection. 142 | var pc = new ProjectCollection(newGlobalProperties); 143 | var newProject = new UnconfiguredProject(configurations); 144 | newProject.LoadProjects(pc, newGlobalProperties, rootElement); 145 | 146 | // If the original project had the TargetFramework property don't touch it during conversion. 147 | var propertiesInTheBaseline = ImmutableArray.Create("OutputType"); 148 | if (project.GetProperty("TargetFramework") != null) 149 | { 150 | propertiesInTheBaseline = propertiesInTheBaseline.Add("TargetFramework"); 151 | } 152 | return new BaselineProject(newProject, propertiesInTheBaseline, targetProjectProperties, projectStyle); 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /ProjectSimplifier/ProjectSimplifier.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /ProjectSimplifier/ProjectStyle.cs: -------------------------------------------------------------------------------- 1 | namespace ProjectSimplifier 2 | { 3 | internal enum ProjectStyle 4 | { 5 | /// 6 | /// The project has an import of Common.props and CSharp.targets. 7 | /// 8 | Default, 9 | 10 | /// 11 | /// The project imports props and targets but not the default ones. 12 | /// 13 | DefaultWithCustomTargets, 14 | 15 | /// 16 | /// Has more imports and the shape is unknown. 17 | /// 18 | Custom 19 | } 20 | } -------------------------------------------------------------------------------- /ProjectSimplifier/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | FileSystem 9 | Release 10 | netcoreapp1.0 11 | bin\Release\PublishOutput 12 | 13 | -------------------------------------------------------------------------------- /ProjectSimplifier/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Diff": { 4 | "commandName": "Project", 5 | "commandLineArgs": "diff \"C:\\Users\\srivatsn\\Documents\\Visual Studio 2017\\Projects\\ConsoleApp24\\ConsoleApp24\\ConsoleApp24.csproj\" -r \"C:\\Program Files\\dotnet\\sdk\\1.0.0\\Roslyn\"", 6 | "environmentVariables": { 7 | "RoslynTargetsPath": "C:\\Program Files\\dotnet\\sdk\\1.0.0\\Roslyn", 8 | "MSBuildSdksPath": "C:\\Program Files\\dotnet\\sdk\\1.0.0\\Sdks\\" 9 | } 10 | }, 11 | "Convert": { 12 | "commandName": "Project", 13 | "commandLineArgs": "convert C:\\roslyn\\src\\Compilers\\Core\\Portable\\CodeAnalysis.csproj -m \"C:\\Program Files (x86)\\Microsoft Visual Studio\\Preview\\Enterprise\\MSBuild\\15.0\\Bin\" -p EnableDefaultItems=true" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /ProjectSimplifier/PropertiesDiff.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using Microsoft.Build.Evaluation; 4 | 5 | namespace ProjectSimplifier 6 | { 7 | internal struct PropertiesDiff 8 | { 9 | public readonly ImmutableArray DefaultedProperties; 10 | public readonly ImmutableArray NotDefaultedProperties; 11 | public readonly ImmutableArray<(IProjectProperty oldProp, IProjectProperty newProp)> ChangedProperties; 12 | 13 | public PropertiesDiff(ImmutableArray defaultedProperties, ImmutableArray notDefaultedPropeties, ImmutableArray<(IProjectProperty, IProjectProperty)> changedProperties) : this() 14 | { 15 | DefaultedProperties = defaultedProperties; 16 | NotDefaultedProperties = notDefaultedPropeties; 17 | ChangedProperties = changedProperties; 18 | } 19 | 20 | public ImmutableArray GetDiffLines() 21 | { 22 | var lines = ImmutableArray.CreateBuilder(); 23 | 24 | if (!DefaultedProperties.IsEmpty) 25 | { 26 | lines.Add("Properties that are defaulted by the SDK:"); 27 | lines.AddRange(DefaultedProperties.Select(prop => $"- {prop.Name} = {prop.EvaluatedValue}")); 28 | lines.Add(""); 29 | } 30 | if (!NotDefaultedProperties.IsEmpty) 31 | { 32 | lines.Add("Properties that are not defaulted by the SDK:"); 33 | lines.AddRange(NotDefaultedProperties.Select(prop => $"+ {prop.Name} = {prop.EvaluatedValue}")); 34 | lines.Add(""); 35 | } 36 | if (!ChangedProperties.IsEmpty) 37 | { 38 | lines.Add("Properties whose value is different from the SDK's default:"); 39 | var changedProps = ChangedProperties.SelectMany((diff) => 40 | new[] 41 | { 42 | $"- {diff.oldProp.Name} = {diff.oldProp.EvaluatedValue}", 43 | $"+ {diff.newProp.Name} = {diff.newProp.EvaluatedValue}" 44 | } 45 | ); 46 | lines.AddRange(changedProps); 47 | lines.Add(""); 48 | } 49 | 50 | return lines.ToImmutable(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /ProjectSimplifier/UnconfiguredProject.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using Microsoft.Build.Construction; 4 | using Microsoft.Build.Evaluation; 5 | 6 | namespace ProjectSimplifier 7 | { 8 | class UnconfiguredProject 9 | { 10 | public ImmutableDictionary ConfiguredProjects { get; private set; } 11 | 12 | public IProject FirstConfiguredProject => ConfiguredProjects.First().Value; 13 | 14 | public ImmutableDictionary> Configurations { get; } 15 | 16 | public UnconfiguredProject(ImmutableDictionary> configurations) 17 | { 18 | Configurations = configurations; 19 | } 20 | 21 | internal void LoadProjects(ProjectCollection collection, ImmutableDictionary globalProperties, string projectFilePath) 22 | { 23 | var projectBuilder = ImmutableDictionary.CreateBuilder(); 24 | foreach (var config in Configurations) 25 | { 26 | var globalPropertiesWithDimensions = globalProperties.AddRange(config.Value); 27 | var project = new MSBuildProject(collection.LoadProject(projectFilePath, globalPropertiesWithDimensions, toolsVersion: null)); 28 | projectBuilder.Add(config.Key, project); 29 | 30 | } 31 | 32 | ConfiguredProjects = projectBuilder.ToImmutable(); 33 | } 34 | 35 | internal void LoadProjects(ProjectCollection collection, ImmutableDictionary globalProperties, ProjectRootElement rootElement) 36 | { 37 | var projectBuilder = ImmutableDictionary.CreateBuilder(); 38 | foreach (var config in Configurations) 39 | { 40 | var project = new MSBuildProject(new Project(rootElement, config.Value, null, collection)); 41 | projectBuilder.Add(config.Key, project); 42 | } 43 | 44 | ConfiguredProjects = projectBuilder.ToImmutable(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ProjectSimplifier 2 | This is a tool that can be used to help with the conversion of old-style csprojs to ones based on the .NET SDK. 3 | 4 | [![Build status](https://ci.appveyor.com/api/projects/status/dcg6k8sca3v83xba?svg=true)](https://ci.appveyor.com/project/SrivatsnNarayanan/msbuildsdkdiffer) 5 | 6 | # What does the tool do? 7 | It loads up a given project and evaluates it to get a list of all properties and items. It then replaces the project in memory with a simple .NET SDK based template and then re-evaluates it. 8 | It does the second evaluation in the same project folder so that items that are automatically picked up by globbing will be known as well. It then produces a diff of the two states to identify the following: 9 | - Properties that can now be removed from the project because they are already implicitly defined by the SDK and the project had the default value. 10 | - Properties that need to be kept in the project either because they override the default or it's a property not defined in the SDK. 11 | - Items that can be removed because they are implicitly brought in by globs in the SDK 12 | - Items that need to be changed to the Update syntax because although they're brought by the SDK, there is extra metadata being added. 13 | - Items that need to be kept because theyr are not implicit in the SDK. 14 | 15 | # Usage: 16 | 17 | From a VS 2017 Developer command prompt 18 | 19 | ProjectSimplifier convert a.csproj -out:b.csproj 20 | 21 | From a regular command prompt 22 | 23 | ProjectSimplifier convert a.csproj -out:b.csproj -m:`` 24 | 25 | 26 | Caveats: If your project has custom imports, you might be changing semantics in a very subtle way by moving to the SDK and this tool doesnt know to find those cases. 27 | 28 | --------------------------------------------------------------------------------