Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Analyzer #116

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions MSBuildLocator.sln
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.10
# Visual Studio Version 16
VisualStudioVersion = 16.0.30807.9
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Locator", "src\MSBuildLocator\Microsoft.Build.Locator.csproj", "{2F4700C6-A6F6-49DF-ABF1-6213AAC4BCFD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Locator.Tests", "src\MSBuildLocator.Tests\Microsoft.Build.Locator.Tests.csproj", "{81407A1F-D2DD-466F-8F6C-D53FE04B4931}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuilderApp", "samples\BuilderApp\BuilderApp.csproj", "{70F35A21-43E2-47CB-8B96-B160C6758EAA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSBuildLocatorAnalyzer", "src\MSBuildLocatorAnalyzer\MSBuildLocatorAnalyzer.csproj", "{BFF38CC3-651E-4BCF-BD06-792DE348EA2C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MSBuildLocatorAnalyzer.CodeFixes", "src\MSBuildLocatorAnalyzer.CodeFixes\MSBuildLocatorAnalyzer.CodeFixes.csproj", "{78A91E45-74F2-438A-8B4B-8DEDE153E1E5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{872EA464-8296-4ECA-932F-FC33841252EF}"
ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props
Expand All @@ -33,6 +37,14 @@ Global
{70F35A21-43E2-47CB-8B96-B160C6758EAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70F35A21-43E2-47CB-8B96-B160C6758EAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70F35A21-43E2-47CB-8B96-B160C6758EAA}.Release|Any CPU.Build.0 = Release|Any CPU
{BFF38CC3-651E-4BCF-BD06-792DE348EA2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BFF38CC3-651E-4BCF-BD06-792DE348EA2C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BFF38CC3-651E-4BCF-BD06-792DE348EA2C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BFF38CC3-651E-4BCF-BD06-792DE348EA2C}.Release|Any CPU.Build.0 = Release|Any CPU
{78A91E45-74F2-438A-8B4B-8DEDE153E1E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{78A91E45-74F2-438A-8B4B-8DEDE153E1E5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{78A91E45-74F2-438A-8B4B-8DEDE153E1E5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{78A91E45-74F2-438A-8B4B-8DEDE153E1E5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
14 changes: 12 additions & 2 deletions samples/BuilderApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,18 @@ private static void Main(string[] args)

MSBuildLocator.RegisterMSBuildPath(msbuildDeploymentToUse.MSBuildPath);
}
var assembly = typeof(Project).Assembly;
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);

Console.WriteLine();
Console.WriteLine($"BuildApp running using MSBuild version {fvi.FileVersion}");
Console.WriteLine(Path.GetDirectoryName(assembly.Location));
Console.WriteLine();

var result = new Builder().Build(projectFilePath);
var pre = ProjectRootElement.Open(projectFilePath);
var project = new Project(pre);
var result = project.Build(new Builder.Logger());
//var result = new Builder().Build(projectFilePath);
Console.WriteLine();

Console.ForegroundColor = result ? ConsoleColor.Green : ConsoleColor.Red;
Expand Down Expand Up @@ -154,7 +164,7 @@ public bool Build(string projectFile)
return project.Build(new Logger());
}

private class Logger : ILogger
public class Logger : ILogger
{
public void Initialize(IEventSource eventSource)
{
Expand Down
72 changes: 72 additions & 0 deletions src/MSBuildLocatorAnalyzer.CodeFixes/CodeFixResources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

124 changes: 124 additions & 0 deletions src/MSBuildLocatorAnalyzer.CodeFixes/CodeFixResources.resx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CodeFixTitle" xml:space="preserve">
<value>Make uppercase</value>
<comment>The title of the code fix.</comment>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net48;netcoreapp3.1</TargetFrameworks>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This must be netstandard2.0

I missed reviewing this earlier and only looked when you asked for how this is going to be shipped.

<IsPackable>true</IsPackable>
<RootNamespace>MSBuildLocatorAnalyzer</RootNamespace>
<IncludeBuildOutput>false</IncludeBuildOutput>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>

<PropertyGroup>
<PackageId>Microsoft.Build.Locator.Analyzer.CodeFixes</PackageId>
<PackageVersion>1.0.0</PackageVersion>
<Authors>Microsoft</Authors>
<RepositoryUrl>https://github.com/microsoft/MSBuildLocator</RepositoryUrl>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Description>A code fix for the MSBuildLocator analyzer.</Description>
<PackageReleaseNotes>Code fix for the analyzer.</PackageReleaseNotes>
<Copyright>Copyright</Copyright>
<PackageTags>MSBuild, MSBuildLocator, Microsoft Build, code fix, analyzers</PackageTags>
<NoPackageAnalysis>true</NoPackageAnalysis>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.3.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\MSBuildLocatorAnalyzer\MSBuildLocatorAnalyzer.csproj" />
</ItemGroup>

<ItemGroup>
<Compile Update="CodeFixResources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="CodeFixResources.resx" />
<EmbeddedResource Update="CodeFixResources.resx" Generator="ResXFileCodeGenerator" LastGenOutput="CodeFixResources.Designer.cs" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;

namespace MSBuildLocatorAnalyzer
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MSBuildLocatorAnalyzerCodeFixProvider)), Shared]
public class MSBuildLocatorAnalyzerCodeFixProvider : CodeFixProvider
{
private const string title = "Move MSBuild use to separate method";

public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(MSBuildLocatorAnalyzerAnalyzer.DiagnosticId); }
}

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();

// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: title,
createChangedDocument: c => MoveMSBuildUseToSeparateMethod(context.Document, diagnostic, root),
equivalenceKey: title),
diagnostic);
}

Task<Document> MoveMSBuildUseToSeparateMethod(Document document, Diagnostic diagnostic, SyntaxNode root)
{
StatementSyntax statement = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<StatementSyntax>();
SyntaxNode method;
for (method = root.FindNode(diagnostic.Location.SourceSpan); !(method is MethodDeclarationSyntax); method = method.Parent);
SyntaxTokenList modifiers = (method as MethodDeclarationSyntax).Modifiers.Any(mod => mod.ValueText.Equals("static")) ?
SyntaxFactory.TokenList(SyntaxFactory.Identifier("private"), SyntaxFactory.Identifier("static")) :
SyntaxFactory.TokenList(SyntaxFactory.Identifier("private"));
MethodDeclarationSyntax toInsert = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), "UseMSBuild")
.WithModifiers(modifiers)
.WithBody(SyntaxFactory.Block(statement))
.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = root.InsertNodesAfter(method, new List<SyntaxNode>() { toInsert });

statement = newRoot.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<StatementSyntax>();
ExpressionStatementSyntax expression = SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(toInsert.Identifier.ValueText))
.WithArgumentList(SyntaxFactory.ArgumentList()
.WithOpenParenToken(SyntaxFactory.Token(SyntaxKind.OpenParenToken))
.WithCloseParenToken(SyntaxFactory.Token(SyntaxKind.CloseParenToken))));
newRoot = newRoot.ReplaceNode(statement, expression);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
}
}
31 changes: 31 additions & 0 deletions src/MSBuildLocatorAnalyzer/MSBuildLocatorAnalyzer.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net48;netcoreapp3.1</TargetFrameworks>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This must be netstandard2.0

<IsPackable>true</IsPackable>
<IncludeBuildOutput>false</IncludeBuildOutput>
Comment on lines +5 to +6

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This mixes tabs & spaces.

<GeneratePackageOnBuild>True</GeneratePackageOnBuild>

<!-- Avoid ID conflicts with the package project. -->
<PackageId>Microsoft.Build.Locator.Analyzer</PackageId>
<PackageVersion>1.0.0</PackageVersion>
<Authors>Microsoft</Authors>
<RepositoryUrl>https://github.com/microsoft/MSBuildLocator</RepositoryUrl>
<PackageRequiredLicenseAcceptance>false</PackageRequiredLicenseAcceptance>
<Description>Analyzers for MSBuildLocator</Description>
<PackageReleaseNotes>An analyzer that identifies the common problem in MSBuildLocator of registering MSBuild in the same method that uses it.</PackageReleaseNotes>
<Copyright>Copyright</Copyright>
<PackageTags>MSBuildLocator, Build, MSBuild, Analyzers</PackageTags>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="2.9.8" />

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: This version is quite old and has known annoying bugs.

<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.1" />
</ItemGroup>

<ItemGroup>
<Compile Update="Resources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Resources.resx" />
<EmbeddedResource Update="Resources.resx" Generator="ResXFileCodeGenerator" LastGenOutput="Resources.Designer.cs" />
</ItemGroup>

</Project>
Loading