visual-studiocode-metricscsharp-source-generator

How to count generated lines of code in Visual Studio?


I'm working on a project in which the majority of the code is generated. I'm fully aware of what a useless metric SLOC is, but I'd like to brag about how much work and potential human error the code generators are saving as a KPI to dazzle the PHBs.

How can I count generated SLOC? VS Code Metrics doesn't seem to distinguish between hand-written code and code generated by an IIncrementalGenerator. Actually, I'm not entirely sure it's counting the generated lines at all. The generated code can't go in a separate project because many of the generated files are partial classes with a few bits hand-written.


Solution

  • You can use the tool NDepend to count generated lines of code in Visual Studio. A free full featured trial available for download here.

    To avoid reporting issues on generated code, the tool has a system based on notmycode code queries to match what is generated code.

    Here are default notmycode code queries that can be adapted to your own situations. For example by looking at CQLinq source code in this link, you can see something like:

    ...
    let sourceFilesPathsToDiscard = (
    from filePath in asmSourceFilesPaths 
    let filePathLower= filePath.ToString().ToLower()
    where     
      filePathLower.EndsWithAny(
        ".g.cs",        // Popular pattern to name generated files.
        ".g.vb",
        ".generated.cs",
        ".generated.vb") ||     
      filePathLower.EndsWithAny(
        ".xaml",        // notmycode WPF xaml code
        ".designer.cs", // notmycode C# Windows Forms designer code
        ".designer.vb") // notmycode VB.NET Windows Forms designer code
    ...
    

    Then in VisualNDepend.exe (standalone) or in the Visual Studio NDepend extension there is a dashboard that displays the number of generated lines of code (in red in the screenshot below)

    enter image description here

    Disclaimer: I work at NDepend