Open sandboxFocusImprove this doc

LAMA0307: The project includes the same source file several times

Severity Warning
Reported by Metalama.Framework
Message Several source files of this project have the path '<Path>'. Metalama analyzes only one of them, so a declaration of the others is not seen by aspects. Verify that the file is not included several times by the project file, for instance by a Compile item that repeats a glob, by Link metadata, or by a shared project.

Cause

In the IDE, the project system creates one document for each Compile item of the project. When two items point to the same file, the compilation that the IDE gives to analyzers contains two source files with the same path, <Path> in the message. This happens, for instance, when:

  • a Compile Include item repeats a file that the default glob of the SDK already includes;
  • two globs overlap, for instance in the project file and in a Directory.Build.props file;
  • two items point to the same file through Link metadata;
  • a shared project (.projitems) is imported several times, or includes a file that the project also includes.

Metalama identifies source files by their path, so it analyzes only the first of these files and ignores the others. Aspects and fabrics don't see the declarations of the ignored files, so the generated code, the diagnostics, and the code fixes shown in the IDE can differ from those of the build. Metalama reports LAMA0307 once, at the start of the file it analyzes.

The command-line build isn't affected: the C# compiler removes the duplicate files itself and reports the warning CS2002 instead.

This diagnostic depends on the project configuration and appears only in the IDE, so it can't be shown in an example.

Resolution

Remove the duplicate inclusion, so that each source file is included only once:

  1. Look for the CS2002 warning in the build output. It names the file that's included several times.
  2. List the Compile items of the project to find where the duplicates come from, for instance with dotnet msbuild -getItem:Compile in the project directory.
  3. Fix the item that includes the file a second time:
    • To change the metadata of a file that the default glob already includes, use Update instead of Include:

      <ItemGroup>
        <Compile Update="Generated\Settings.cs" DependentUpon="Settings.settings" />
      </ItemGroup>
      
    • If you want to list all source files explicitly, disable the default glob by setting the EnableDefaultCompileItems property to false.

    • Make sure that a file linked from another directory with Link metadata isn't also included by a glob, and that each shared project is imported only once.

  4. Reload the project in the IDE, if the IDE doesn't reload it automatically. The warning disappears.

See also