Visual Studio - 自動產生NuGet Package並移除舊版Package

02 November 2014 — Written by Sky Chang
#NuGet#Visual Studio

延續前一篇,這篇要談的是一個小小的不方便與問題,畢竟人類的懶惰是沒有極限的。

如果大家有測是下來,可能就會發現如下圖的問題,是的,產生了非常多的nupkg檔案…畢竟每次增加一個版本,就會多兩個nupkg檔案如下圖;當然如果一開始少少的可能還好,但越來越多的時候,就會感覺很髒亂…,所以這篇,我們就來看看如何建立的過程中,順便移除舊版的Package。

image

那要怎麼做呢??,其實每次建立的時候,都是透過NuGet.targets來觸發動作,所以我們要增加一些小東西到NuGet.targets裡面去。

image

首先,我們要先在前面填入以下的Code,這邊我們定義了OutputPackages的內容,是nupkg的路徑。

<ItemGroup>
    <OutputPackages Include="$(TargetDir)*.nupkg" />
</ItemGroup>  

將此Code放到下圖的位置。

image

接下來,我們要定義一個CleanDependsOn的標籤,當條件成立的時候,就會執行此標籤裡面的內容。

<CleanDependsOn Condition="$(BuildPackage) == 'true'">
  $(CleanDependsOn);
  CleanPackages;
</CleanDependsOn>

我們要把此標籤放到底下的位置。

image

最後,這個內容到底要做甚麼事情哩,就是最後面這個標籤的內容了,也就是Delete Files,要刪除的檔案,就是我們一開始定義的路徑。

<Target Name="CleanPackages">
  <Delete Files="@(OutputPackages)"></Delete>
</Target>

我們把此標籤放到以下的位置。

image

完成之後,我們要使用重建的動作,如果只用建置,是沒辦法觸發的。

image

重建之後,我們就可以發現,原本的nupkg檔案全部都被砍掉了,只留下最新版喔!!

image

最後的最後,附上完整的NuGet.targets xml給大家參考~

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <OutputPackages Include="$(TargetDir)*.nupkg" />
  </ItemGroup>  
  <PropertyGroup>
        <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>

        <!-- Enable the restore command to run before builds -->
        <RestorePackages Condition="  '$(RestorePackages)' == '' ">false</RestorePackages>

        <!-- Property that enables building a package from a project -->
        <BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>

        <!-- Determines if package restore consent is required to restore packages -->
        <RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>

        <!-- Download NuGet.exe if it does not already exist -->
        <DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
    </PropertyGroup>

    <ItemGroup Condition=" '$(PackageSources)' == '' ">
        <!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
        <!-- The official NuGet package source (https://www.nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
        <!--
            <PackageSource Include="https://www.nuget.org/api/v2/" />
            <PackageSource Include="https://my-nuget-source/nuget/" />
        -->
    </ItemGroup>

    <PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
        <!-- Windows specific commands -->
        <NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
    </PropertyGroup>

    <PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
        <!-- We need to launch nuget.exe with the mono command if we're not on windows -->
        <NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
    </PropertyGroup>

    <PropertyGroup>
        <PackagesProjectConfig Condition=" '$(OS)' == 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config</PackagesProjectConfig>
        <PackagesProjectConfig Condition=" '$(OS)' != 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config</PackagesProjectConfig>
    </PropertyGroup>

    <PropertyGroup>
      <PackagesConfig Condition="Exists('$(MSBuildProjectDirectory)\packages.config')">$(MSBuildProjectDirectory)\packages.config</PackagesConfig>
      <PackagesConfig Condition="Exists('$(PackagesProjectConfig)')">$(PackagesProjectConfig)</PackagesConfig>
    </PropertyGroup>

    <PropertyGroup>
        <!-- NuGet command -->
        <NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
        <PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>

        <NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
        <NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 "$(NuGetExePath)"</NuGetCommand>

        <PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>

        <RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
        <NonInteractiveSwitch Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' ">-NonInteractive</NonInteractiveSwitch>

        <PaddedSolutionDir Condition=" '$(OS)' == 'Windows_NT'">"$(SolutionDir) "</PaddedSolutionDir>
        <PaddedSolutionDir Condition=" '$(OS)' != 'Windows_NT' ">"$(SolutionDir)"</PaddedSolutionDir>

        <!-- Commands -->
        <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)"  $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>
        <BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>

        <!-- We need to ensure packages are restored prior to assembly resolve -->
        <BuildDependsOn Condition="$(RestorePackages) == 'true'">
            RestorePackages;
            $(BuildDependsOn);
        </BuildDependsOn>

        <!-- Make the build depend on restore packages -->
        <BuildDependsOn Condition="$(BuildPackage) == 'true'">
            $(BuildDependsOn);
            BuildPackage;
        </BuildDependsOn>

        <CleanDependsOn Condition="$(BuildPackage) == 'true'">
          $(CleanDependsOn);
          CleanPackages;
        </CleanDependsOn>
    </PropertyGroup>

    <Target Name="CheckPrerequisites">
        <!-- Raise an error if we're unable to locate nuget.exe  -->
        <Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
        <!--
        Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
        This effectively acts as a lock that makes sure that the download operation will only happen once and all
        parallel builds will have to wait for it to complete.
        -->
        <MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT;DownloadNuGetExe=$(DownloadNuGetExe)" />
    </Target>

    <Target Name="_DownloadNuGet">
        <DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
    </Target>

    <Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">        
        <Exec Command="$(RestoreCommand)"
              Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />

        <Exec Command="$(RestoreCommand)"
              LogStandardErrorAsError="true"
              Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
    </Target>

    <Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
        <Exec Command="$(BuildCommand)"
              Condition=" '$(OS)' != 'Windows_NT' " />

        <Exec Command="$(BuildCommand)"
              LogStandardErrorAsError="true"
              Condition=" '$(OS)' == 'Windows_NT' " />
    </Target>

    <Target Name="CleanPackages">
      <Delete Files="@(OutputPackages)"></Delete>
    </Target>

    <UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
            <OutputFilename ParameterType="System.String" Required="true" />
        </ParameterGroup>
        <Task>
            <Reference Include="System.Core" />
            <Using Namespace="System" />
            <Using Namespace="System.IO" />
            <Using Namespace="System.Net" />
            <Using Namespace="Microsoft.Build.Framework" />
            <Using Namespace="Microsoft.Build.Utilities" />
            <Code Type="Fragment" Language="cs">
                <![CDATA[
                try {
                    OutputFilename = Path.GetFullPath(OutputFilename);

                    Log.LogMessage("Downloading latest version of NuGet.exe...");
                    WebClient webClient = new WebClient();
                    webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);

                    return true;
                }
                catch (Exception ex) {
                    Log.LogErrorFromException(ex);
                    return false;
                }
            ]]>
            </Code>
        </Task>
    </UsingTask>
</Project>

基本上,到這邊,就完成嚕!!

參考資料

Sky & Study4.TW