Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find .CS files in a project folder that are no longer in the project?

As our projects have evolved over the years many .cs files have been removed from projects, renamed etc. but they remain in source control. So when you pull latest code you get all these .cs files that are no longer referenced in any .csproj file.

Anyone know an easy, reliable mechanism for detecting these files and eliminating them?

like image 382
Craig Wilcox Avatar asked Apr 17 '09 14:04

Craig Wilcox


1 Answers

It's best to use a scripting language for this task. I find that powershell is well suited for situations like this.

Step 1 is to find all of the actual .cs files that are inlcuded in your csproj files. The following function will search a directory structure for all csproj files and return the set of .cs files that are included in those files

function Get-IncludedCsFiles() {
  param ( $rootPath = $(throw "Need a path") )
  $projFiles = gci -re -in *.csproj $rootPath
  foreach ( $file in $projFiles ) { 
    $dir = split-path $file.FullName
    foreach ( $line in (gc $file) ) { 
      if ( $line -match 'Compile\s+Include="([^"]+)"' ) {
        join-path $dir $matches[1]
      }
    }
  }
}

Now all you need to do is wrap that into a dictionary and then do a search in the directory structure

$map = @{}
$pathToSearch = "Path\To\Search"
Get-IncludedCsFiles $pathToSearch | 
%{
    if(!$map.Contains($_))
    {
      $map.Add($_, $true)
    } 
}
$notIncluded = gci -re -in *.cs $path | ?{ -not $map.Contains($_.FullName) }
like image 101
JaredPar Avatar answered Nov 12 '22 03:11

JaredPar