Skip to content

Commit

Permalink
[c#] support for <Using Remove=XXX> in csproj files (#5239)
Browse files Browse the repository at this point in the history
  • Loading branch information
xavierpinho authored Jan 20, 2025
1 parent 55fce4b commit a498a15
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ object ImplicitUsingsCollector {
)
}

/** Extracts implicit usings based on the project type, i.e. based on the `<Project Sdk="XXX">` tag.
*/
private def from(rootElem: Elem): List[String] = {
val projectType = rootElem.label match
case "Project" => rootElem.attribute("Sdk").flatMap(_.headOption.map(_.text))
Expand All @@ -74,8 +76,18 @@ object ImplicitUsingsCollector {
.collect { case x if x.label == "ImplicitUsings" => x.text }
.exists(x => x == "true" || x == "enable")

val exclusions = rootElem.child
.collect { case x if x.label == "ItemGroup" => x.child }
.flatten
.collect {
case x if x.label == "Using" && x.attribute("Remove").isDefined =>
x.attribute("Remove").flatMap(_.headOption.map(_.text))
}
.flatten
.toList

if (projectType.isDefined && implicitUsingsEnabled) {
projectTypeMapping.getOrElse(projectType.get, Nil)
projectTypeMapping.getOrElse(projectType.get, Nil).diff(exclusions)
} else {
Nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,31 @@ class ImplicitUsingsTests extends CSharpCode2CpgFixture {
}
}

"accompanied by a NET.Sdk csproj with ImplicitUsings enabled but excluding `System`" should {
val cpg = code("""
|Console.WriteLine("Foo");
|""".stripMargin)
.moreCode(
"""
|<Project Sdk="Microsoft.NET.Sdk">
| <PropertyGroup>
| <OutputType>Exe</OutputType>
| <ImplicitUsings>enable</ImplicitUsings>
| </PropertyGroup>
| <ItemGroup>
| <Using Remove="System" />
| </ItemGroup>
|</Project>
|""".stripMargin,
fileName = "App.csproj"
)

"not resolve WriteLine call" in {
cpg.call.nameExact("WriteLine").methodFullName.l shouldBe List(
"<unresolvedNamespace>.WriteLine:<unresolvedSignature>"
)
}
}
}

}

0 comments on commit a498a15

Please sign in to comment.