Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn Source Generator skipped because of trailing space in .cs file name [closed]

I had an issue where a Roslyn source generator was not being called at all in a .NET project, the breakpoint of the Initialize method did not hit, while the launchSettings.json was correct and it did in fact work for some other projects.

like image 262
Rubenisme Avatar asked Dec 05 '25 14:12

Rubenisme


1 Answers

The cause was a filename with a space at the end before the .cs extension, in my example it was: ValueTypeMapping .cs

Because of this trailing space, Roslyn silently skipped analyzers and source generators during the build for the project — without any indication or error messages. I did do /bl build and had the MS build structured log viewer where it didn't look like it had anything, I also did a /pp build and that proved the analyzer was not passed <Analyzer Include= should show {SourceGeneratorName}.dll, which it didn't.

To prevent this in the future, I added a build validation step to fail fast if any file has a trailing space:

<Target Name="ValidateNoTrailingSpacesInFileNames" BeforeTargets="CoreCompile">
    <ItemGroup>
        <!-- Check if the Filename part (without extension) ends with a space using Regex -->
        <FilesWithTrailingSpaces
            Include="@(Compile)"
            Condition="'%(Filename)' != '' AND $([System.Text.RegularExpressions.Regex]::IsMatch('%(Filename)', '\s$'))"
             />
        <!-- Explanation:
             '$([System.Text.RegularExpressions.Regex]::IsMatch('%(Filename)', '\s$'))'
             Calls the static Regex.IsMatch method.
             Input: '%(Filename)'
             Pattern: '\s$' (whitespace \s at the end $)
             MSBuild evaluates the boolean result ('True'/'False') directly in the condition.
        -->
    </ItemGroup>

    <Error
        Text="File '%(FilesWithTrailingSpaces.Identity)' has trailing spaces before its extension (Filename: '%(FilesWithTrailingSpaces.Filename)'). Please rename it."
        Condition="@(FilesWithTrailingSpaces) != ''" />
</Target>

To my Directory.Build.props file (on the repository level).

like image 197
Rubenisme Avatar answered Dec 08 '25 19:12

Rubenisme