Using $(SolutionDir) when running template via TextTransform.exe

后端 未结 3 1239
我在风中等你
我在风中等你 2020-12-19 05:59

I\'m trying to get our T4 templates to run at build time, without adding dependencies on the Visual Studio Modeling SDK. I\'ve successfully used a variant of the batch file

3条回答
  •  忘掉有多难
    2020-12-19 06:19

    I used an approach very similar to piers7 -- except in my case, I actually needed to keep the *.tt file in the same directory (because of runtime lookup of files based on relative paths), but didn't care if the file itself was named differently. As such, instead of having $templateTemp create a temporary file in a temp directory, I kept it in the same folder.

    I also needed to recursively search for the *.tt files anywhere in the solution directory.

    Here is the resulting script, taking piers7's and modifying it:

    <#
    .Synopsis
    Executes all the T4 templates within designated areas of the containing project
    #>
    param(
    
    )
    
    $ErrorActionPreference = 'stop';
    $scriptDir = Split-Path $MyInvocation.MyCommand.Path
    
    $commonProgramFiles32 = $env:CommmonProgramFiles
    if (Test-Path environment::"CommonProgramFiles(x86)") { $commonProgramFiles32 = (gi "Env:CommonProgramFiles(x86)").Value };
    
    $t4 = Resolve-Path "$commonProgramFiles32\Microsoft Shared\TextTemplating\12.0\texttransform.exe";
    $solutionDir = Resolve-Path "$scriptDir\"
    $templates = Get-ChildItem -Path $scriptDir -Filter *.tt -Recurse
    $extension = '.ts';
    
    pushd $scriptDir;
    try{
        foreach($template in $templates){
            # keeping the same path (because my template references relative paths), 
            #    but copying under different name:
            $templateTemp = $template.FullName + "____temporary"
            $targetfile = [IO.Path]::ChangeExtension($template.FullName, $extension);
            Write-Host "Running $($template.Name)"
            Write-Host "...output to $targetFile";
    
            # When run from outside VisualStudio you can't use $(SolutionDir)
            # ...so have to modify the template to get this to work...
            # ...do this by cloning to a temp file, and running this instead
            Get-Content $template.FullName | % {
                $_.Replace('$(SolutionDir)',"$solutionDir")
            } | Out-File -FilePath:$templateTemp
    
            try{
                & $t4 $templateTemp -out $targetfile -I $template.DirectoryName;
            }finally{
                if(Test-Path $templateTemp){ Remove-Item $templateTemp; }
            }
        }
    }finally{
        popd;
    }
    

提交回复
热议问题