重建sln的項目層級

編寫包含多個 csproj 的程序時,隨着項目數量的持續增加,可能涉及一些文件夾的變動,手動添加項目或者變動會變得非常麻煩,這個時候,可以利用 dotnet cli 幫助我們完成。

如果從零開始,我們可以新建一個解決方案。

dotnet new sln -n todo.sln

然後添加當前目錄內的所有 csproj 文件到解決方案。

$rootDir = Get-Location
$solutionFile = "$rootDir\todo.sln"

Get-ChildItem -Recurse -Filter *.csproj | ForEach-Object {
    $projectFile = $_.FullName
    $relativePath = $_.DirectoryName.Replace($rootDir, "").TrimStart("\")
    $solutionFolder = if ($relativePath) { "\$relativePath" } else { "" }
    dotnet sln $solutionFile add $projectFile --solution-folder $solutionFolder
}

這樣生成的項目會保留每一個文件夾結構(解決方案文件夾),與 Visual Studio 的默認行爲不同(會忽略與項目同名的解決方案文件夾創建)。

其實簡單一些,直接使用這個命令就可以了:

dotnet sln todo.sln add (ls -r **/*.csproj)

這個命令等效於:

$rootDir = Get-Location
$solutionFile = "$rootDir\todo.sln"

Get-ChildItem -Recurse -Filter *.csproj | ForEach-Object {
    $projectFile = $_.FullName
    $parentDirectoryName = Split-Path $_.DirectoryName -Leaf
    if ($_.Name -eq "$parentDirectoryName.csproj") {
        if($_.DirectoryName -ne $rootDir){
            $parentSolutionFolder = (Split-Path $_.DirectoryName -Parent).Replace($rootDir, "").TrimStart("\")
            $solutionFolder = if ($parentSolutionFolder) { "\$parentSolutionFolder" } else { "" }
        }
        else{
            $solutionFolder = ""
        }
    } else {
        $relativePath = $_.DirectoryName.Replace($rootDir, "").TrimStart("\")
        $solutionFolder = if ($relativePath) { "\$relativePath" } else { "" }
    }
    dotnet sln $solutionFile add $projectFile --solution-folder $solutionFolder
}

上面這個感覺很複雜,不過相當於給出了每一個步驟,如果後期有其他需求,可以在上面代碼的基礎上進行調整與改進。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章