为 NuGet 创建 x-script 资产缓存源

注意

本部分介绍 vcpkg 的一项试验性功能,该功能随时可能会更改或移除。

在此示例中,我们将使用脚本还原和推送项目,将 NuGet 信息源设置为资产缓存源。

先决条件

  • nuget.exe
  • NuGet 包信息源

步骤 1:创建 asset-source.nuspec

使用以下内容创建 NuGet 包规范模板:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>$sha$</id>
        <version>1.0.0</version>
        <description>vcpkg download asset</description>
        <authors>vcpkg</authors>
    </metadata>
    <files>
        <file src="$file$" />
    </files>
</package>

步骤 2:创建资产提供程序脚本

现在,你需要创建一个脚本,从 NuGet 信息源下载包(如果可用),并将缺少的包上传到信息源(如果不存在)。

使用下面提供的内容创建 asset-provider.bat,确保将 NuGet 信息源 URL 和 asset-source.nuspec 路径替换为系统中的正确值。

@echo off
set url=%1
set sha512=%2
set dst=%3
set "_dst=%dst:/=\%"
set "_sha512=%sha512:~0,90%"

cd /d %~dp3
%NUGET% install %sha512:~0,90% -Source https://your-nuget-feed-url
echo.
if exist %_sha512%.1.0.0 (
    echo "Pull from the NuGet feed"
    cd %_sha512%.1.0.0

    REM Assume both are files not directories
    echo "F" | xcopy /f *.part %_dst%
) else (
    echo "Fetch from the url"
    curl.exe -L %url% --create-dirs --output %dst%
    REM Replace with the correct path
    %NUGET% pack C:\path\to\asset-source.nuspec -BasePath %~dp3 -Properties "sha=%_sha512%;file=%dst%" -OutputDirectory %TEMP%
    %NUGET% push -ApiKey az -SkipDuplicate %TEMP%\%_sha512%.1.0.0.nupkg -Source https://your-nuget-feed-url
)

步骤 3:配置资产缓存源

现在,你已经创建资产提供程序脚本,需要指示 vcpkg 将其用作资产缓存源。 为此,请设置以下环境变量:

$env:X_VCPKG_ASSET_SOURCES="clear;x-script,C:/path/to/asset-provider.bat {url} {sha512} {dst};x-block-origin"
$env:NUGET="C:/path/to/nuget.exe"
$env:VCPKG_KEEP_ENV_VARS="NUGET"

注意:请确保将资产提供程序脚本和 nuget.exe 的占位符路径替换为系统中的正确路径。

X_VCPKG_ASSET_SOURCES 是用于设置 vcpkg 使用的资产缓存源的环境变量。 在本例中,我们设置以下值:

  • clear 将删除默认资产缓存位置。
  • x-script 将脚本添加为资产缓存源,第一个参数指示应调用命令行 vcpkg;在本例中,我们将调用 asset-provider.bat 脚本并转发一些必需的参数。
  • x-block-origin 强制所有下载均来自配置的资产缓存源。

VCPKG_KEEP_ENV_VARS 用于将环境变量转发到 vcpkg 的构建环境。 在构建期间,vcpkg 会创建一个干净的环境;通过将 NUGET 添加到 VCPKG_KEEP_ENV_VARS,我们确保在构建期间转发 NuGet 可执行文件位置。

正确设置所有内容后,任何时候 vcpkg 下载资产,它就会将其上传到你的 NuGet 信息源,以供将来下载使用。 你会注意到,缓存的资产以其文件 SHA512 和 asset-source.nuspec 中指定的版本命名。 如果想要为包提供更有意义的名称,可以使用自己的逻辑修改包模板和资产提供程序脚本。