Add implicit usings analyzer and csproj formatter

This commit is contained in:
Matthew Parker [SSW]
2023-08-30 18:59:41 +10:00
parent c343612873
commit 526ff1b43d
8 changed files with 226 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
using System.Text;
using System.Xml;
namespace SolutionParityChecker;
public static class FormatCsproj
{
public static void FormatCsprojFile(string csprojFilePath)
{
using TextReader rd = new StreamReader(csprojFilePath, Encoding.Default);
XmlDocument doc = new XmlDocument();
doc.Load(rd);
if (rd != Console.In)
{
rd.Close();
}
using var wr = new StreamWriter(csprojFilePath, false, Encoding.Default);
var settings =
new XmlWriterSettings
{
Indent = true,
IndentChars = "\t",
NewLineOnAttributes = false,
OmitXmlDeclaration = true
};
using (var writer = XmlWriter.Create(wr, settings))
{
doc.WriteContentTo(writer);
writer.Close();
}
}
}

View File

@@ -0,0 +1,60 @@
using Microsoft.Build.Construction;
namespace SolutionParityChecker;
public static class ImplicitUsings
{
public static List<ProjectRootElement> FindCSharpProjectsMissingImplicitUsings(List<ProjectRootElement> projectList)
{
var projectsMissingImplicitUsings = new List<ProjectRootElement>();
foreach (var project in projectList)
{
var implicitUsings = project.PropertyGroups
.SelectMany(x => x.Properties)
.FirstOrDefault(x => x.Name == "ImplicitUsings");
if (implicitUsings is null || implicitUsings.Value is not "enable")
{
projectsMissingImplicitUsings.Add(project);
}
}
return projectsMissingImplicitUsings;
}
public static void AddMissingImplicitUsings(List<ProjectRootElement> projectsMissingImplicitUsings)
{
foreach (var project in projectsMissingImplicitUsings)
{
if (ProjectIsMissingImplicitUsings(project))
{
project.AddProperty("ImplicitUsings", "enable");
project.Save();
FormatCsproj.FormatCsprojFile(project.FullPath);
}
}
}
public static void EnableDisabledImplicitUsings(List<ProjectRootElement> projectsMissingImplicitUsings)
{
throw new NotImplementedException();
}
public static void EnableAllImplicitUsings(List<ProjectRootElement> projectsMissingImplicitUsings)
{
throw new NotImplementedException();
}
public static bool ProjectIsMissingImplicitUsings(ProjectRootElement project)
{
var implicitUsings = project.PropertyGroups
.SelectMany(x => x.Properties)
.FirstOrDefault(x => x.Name == "ImplicitUsings");
if (implicitUsings is null)
{
return true;
}
return false;
}
}

View File

@@ -60,4 +60,15 @@ public static class SolutionParityChecker
return projectsMissingFromSolution;
}
public static List<ProjectRootElement> GetCSharpProjectObjectsFromSolutionFile(
SolutionFile solutionFile
)
{
var projectList = solutionFile.ProjectsByGuid
.Where(x => x.Value.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat)
.Select(s => ProjectRootElement.Open(s.Value.AbsolutePath))
.ToList();
return projectList;
}
}