简体   繁体   中英

Is there a way to throw a custom compilation error if some MsBuild property is set in any project within a solution file?

Background I have created a Directory.Build.props in my root repo folder with the following contents:

<Project>
  <PropertyGroup>
    <LangVersion>7.3</LangVersion>
  </PropertyGroup>
</Project>

I need to prevent the usage of C# 8 syntax within our codebase, since it is targeting .Net 4.7.2 The above file sets the LangVersion property for each project within the solution.

The problem

Our codebase is big. Many projects within one single solution with many programmers working in differents and / or adding new ones, this is not a problem itself but rather the fact that any programmer can override the LangVersion within their own .csproj file.

I know we can stop those changes in the code review phase or by sending reminders every hour to all the programmers telling them not to use C# 8 for this specific project. But I was wondering if I could just celebrate their boldness by giving them a nice and handsome compiler error.

Maybe with a custom code analizer with Roslyn? Is there any way?

Try something like this:

<Project>

    <Target Name="RestrictLangVersion" BeforeTargets="Compile">
        <PropertyGroup>
            <UnsupportedTarget Condition=" '$(MaxSupportedLangVersion)' == '7.3' AND '$(LangVersion)' == '8.0' ">true</UnsupportedTarget>
        </PropertyGroup>
        <Error Text="At *YOUR_COMPANY* we discourage the use of C# 8.0 on unsupported targets" Condition=" '$(UnsupportedTarget)' == 'true' " />
    </Target>

</Project>

You can pop that in a Directory.Build.targets high up in your CI agent and it should do the trick.

You'll need to add the logic for preview etc... (as there are other values of LangVersion that will result in 8.0 ) and some of those will be dependant on the version of csc , so I've left out the hard part.

Basically you'll need to replicate the logic here: https://github.com/dotnet/roslyn/blob/97123b393c3a5a91cc798b329db0d7fc38634784/src/Compilers/CSharp/Portable/LanguageVersion.cs#L353-L364

bearing in mind that it will change across different versions of csc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM