Skip to content

Instantly share code, notes, and snippets.

@devlead
Last active January 5, 2021 15:19
Show Gist options
  • Save devlead/ca566f58457f558dd33484a73f1352ed to your computer and use it in GitHub Desktop.
Save devlead/ca566f58457f558dd33484a73f1352ed to your computer and use it in GitHub Desktop.
Example downloading latest version of package from NuGet.org with Cake
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*[.json, .xml, .info]
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
tools/
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# JetBrains Rider
.idea/
*.sln.iml
##
## Visual Studio Code
##
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

Cake NuGet package download example

This is an example of how one could download an NuGet package from a V3 NuGet source in a Cake script.

Usage

  #load "nugetinstall.cake"

  await context.DownloadLatestPackage(
        "PackageId",
        "../Packages"
    );

Full example can be found in build.cake.

#load "nugetinstall.cake"
Task("DownloadPackages")
.Does(
async context => {
foreach(var packageId in new [] { "Cake.Core", "Cake.Common", "Cake.Git" })
{
await context.DownloadLatestPackage(
packageId,
"../Packages"
);
}
}
);
Task("Default")
.IsDependentOn("DownloadPackages");
RunTarget(Argument("target", "Default"));
{
"version": 1,
"isRoot": true,
"tools": {
"cake.tool": {
"version": "0.38.5",
"commands": [
"dotnet-cake"
]
}
}
}
{
"sdk": {
"version": "3.1.404",
"rollForward": "latestFeature"
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<!--To inherit the global NuGet package sources remove the <clear/> line below -->
<clear />
<add key="nuget" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
#addin nuget:?package=System.Text.Json&version=4.6.0&loaddependencies=true
#load "nugetmodel.cake"
using System.Net.Http;
using System.Text.Json;
public static async Task<T> GetAsync<T>(this HttpClient client, string uri)
{
using (var stream = await client.GetStreamAsync(uri))
{
return await JsonSerializer.DeserializeAsync<T>(
stream,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
}
}
public static async Task<bool> DownloadLatestPackage(this ICakeContext context, string packageId, DirectoryPath outputDirectory, string nuGetSource = "https://api.nuget.org/v3/index.json")
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (string.IsNullOrWhiteSpace(packageId))
{
throw new ArgumentNullException(nameof(packageId));
}
if (string.IsNullOrWhiteSpace(nuGetSource))
{
throw new ArgumentNullException(nameof(nuGetSource));
}
if (outputDirectory == null)
{
throw new ArgumentNullException(nameof(outputDirectory));
}
if (!context.DirectoryExists(outputDirectory))
{
throw new DirectoryNotFoundException($"{nameof(outputDirectory)} ({outputDirectory}) not found.");
}
using(var client = new HttpClient())
{
client.DefaultRequestHeaders.UserAgent.ParseAdd($"Cake NuGet Client/{context.Environment.Runtime.CakeVersion.ToString(3)}");
var nuGetIndex = await client.GetAsync<NuGetIndex>(nuGetSource);
var cakeBaseUrl = string.Concat(
nuGetIndex
?.Resources
?.Where(type => type.Type?.Length == 20
&& type.Type == "RegistrationsBaseUrl"
&& type.Id?.Length > 8 == true
&& type.Id.StartsWith("https://"))
.Select(url => url.Id)
.FirstOrDefault()
?? throw new Exception($"Failed to fetch RegistrationsBaseUrl from {nuGetSource}."),
$"{packageId.ToLowerInvariant()}/index.json"
);
var cakeNuGetIndex = await client.GetAsync<NuGetContainer<NuGetContainer<NuGetPackageEntry>>>(cakeBaseUrl);
var packageEntry = (
from item in cakeNuGetIndex.Items
from version in item.Items
orderby SemVersion.TryParse(
version.CatalogEntry.Version,
out var semVersion
)
? semVersion
: SemVersion.Zero
descending
select version.CatalogEntry
).FirstOrDefault();
if (string.IsNullOrWhiteSpace(packageEntry?.PackageContent))
{
throw new Exception($"Failed to found package uri for {packageId} on source {nuGetSource}");
}
var packageDirectory = outputDirectory.Combine($"{packageEntry.PackageId}.{packageEntry.Version}");
if(context.DirectoryExists(packageDirectory))
{
context.Information("Package {0} already downloaded.", packageDirectory);
return true;
}
context.Information("Downloading package {0}...", packageDirectory);
using (var stream = await client.GetStreamAsync(packageEntry?.PackageContent))
{
using (var zipStream = new System.IO.Compression.ZipArchive(stream))
{
foreach (var entry in zipStream.Entries)
{
var entryPath = packageDirectory.CombineWithFilePath(entry.FullName);
var directory = entryPath.GetDirectory();
context.EnsureDirectoryExists(directory);
using (System.IO.Stream source = entry.Open(),
target = context.FileSystem.GetFile(entryPath).OpenWrite())
{
source.CopyTo(target);
}
}
}
}
return context.DirectoryExists(packageDirectory);
}
}
#addin nuget:?package=System.Text.Json&version=4.6.0&loaddependencies=true
using System;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
public class NuGetIndex
{
[JsonPropertyName("version")]
public string Version { get; set; }
[JsonPropertyName("resources")]
public NuGetResource[] Resources { get; set; }
}
public class NuGetResource
{
[JsonPropertyName("@id")]
public string Id { get; set; }
[JsonPropertyName("@type")]
public string Type { get; set; }
}
public class NuGetCommit
{
[JsonPropertyName("@id")]
public string Id { get; set; }
[JsonPropertyName("commitId")]
public Guid CommitId { get; set; }
[JsonPropertyName("commitTimeStamp")]
public DateTimeOffset CommitTimeStamp { get; set; }
}
public class NuGetContainer<T> : NuGetCommit
{
[JsonPropertyName("count")]
public int Count { get; set; }
[JsonPropertyName("items")]
public T[] Items { get; set; }
}
public class NuGetPackageEntry: NuGetCommit
{
[JsonPropertyName("catalogEntry")]
public NuGetCatalogEntry CatalogEntry { get; set; }
}
public class NuGetCatalogEntry: NuGetResource
{
[JsonPropertyName("version")]
public string Version { get; set; }
[JsonPropertyName("packageContent")]
public string PackageContent { get; set; }
[JsonPropertyName("id")]
public string PackageId { get; set; }
}
public struct SemVersion : IComparable, IComparable<SemVersion>, IEquatable<SemVersion>
{
public static SemVersion Zero { get; } = new SemVersion(0,0,0, null, null, "0.0.0");
static readonly Regex SemVerRegex =
new Regex (
@"(?<Major>0|(?:[1-9]\d*))(?:\.(?<Minor>0|(?:[1-9]\d*))(?:\.(?<Patch>0|(?:[1-9]\d*)))?(?:\-(?<PreRelease>[0-9A-Z\.-]+))?(?:\+(?<Meta>[0-9A-Z\.-]+))?)?",
RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase
);
public int Major { get; }
public int Minor { get; }
public int Patch { get; }
public string PreRelease { get; }
public string Meta { get; }
public bool IsPreRelease { get; }
public bool HasMeta { get; }
public string VersionString { get; }
public SemVersion (int major, int minor, int patch, string preRelease = null, string meta = null) :
this (major, minor, patch, preRelease, meta, null)
{
}
private SemVersion (int major, int minor, int patch, string preRelease, string meta, string versionString)
{
Major = major;
Minor = minor;
Patch = patch;
IsPreRelease = !string.IsNullOrEmpty (preRelease);
HasMeta = !string.IsNullOrEmpty (meta);
PreRelease = IsPreRelease ? preRelease : null;
Meta = HasMeta ? meta : null;
if (!string.IsNullOrEmpty (versionString)) {
VersionString = versionString;
} else {
var sb = new StringBuilder ();
sb.AppendFormat (CultureInfo.InvariantCulture, "{0}.{1}.{2}", Major, Minor, Patch);
if (IsPreRelease) {
sb.AppendFormat (CultureInfo.InvariantCulture, "-{0}", PreRelease);
}
if (HasMeta) {
sb.AppendFormat (CultureInfo.InvariantCulture, "+{0}", Meta);
}
VersionString = sb.ToString ();
}
}
public static bool TryParse (string version, out SemVersion semVersion)
{
semVersion = Zero;
if (string.IsNullOrEmpty(version)) {
return false;
}
var match = SemVerRegex.Match (version);
if (!match.Success) {
return false;
}
if (!int.TryParse (
match.Groups["Major"].Value,
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out var major) ||
!int.TryParse (
match.Groups["Minor"].Value,
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out var minor) ||
!int.TryParse (
match.Groups["Patch"].Value,
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out var patch)) {
return false;
}
semVersion = new SemVersion (
major,
minor,
patch,
match.Groups["PreRelease"]?.Value,
match.Groups["Meta"]?.Value,
version);
return true;
}
public bool Equals (SemVersion other)
{
return Major == other.Major
&& Minor == other.Minor
&& Patch == other.Patch
&& string.Equals(PreRelease, other.PreRelease, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Meta, other.Meta, StringComparison.OrdinalIgnoreCase);
}
public int CompareTo (SemVersion other)
{
if (Equals(other))
{
return 0;
}
if (Major > other.Major) {
return 1;
}
if (Major < other.Major) {
return -1;
}
if (Minor > other.Minor) {
return 1;
}
if (Minor < other.Minor) {
return -1;
}
if (Patch > other.Patch) {
return 1;
}
if (Patch < other.Patch) {
return -1;
}
switch(StringComparer.InvariantCultureIgnoreCase.Compare(PreRelease, other.PreRelease)) {
case 1:
return 1;
case -1:
return -1;
default:
return StringComparer.InvariantCultureIgnoreCase.Compare (Meta, other.Meta);
}
}
public int CompareTo (object obj)
{
return (obj is SemVersion semVersion)
? CompareTo (semVersion)
: -1;
}
public override bool Equals (object obj)
{
return (obj is SemVersion semVersion)
&& Equals (semVersion);
}
public override int GetHashCode ()
{
unchecked {
var hashCode = Major;
hashCode = (hashCode * 397) ^ Minor;
hashCode = (hashCode * 397) ^ Patch;
hashCode = (hashCode * 397) ^ (PreRelease != null ? StringComparer.OrdinalIgnoreCase.GetHashCode (PreRelease) : 0);
hashCode = (hashCode * 397) ^ (Meta != null ? StringComparer.OrdinalIgnoreCase.GetHashCode (Meta) : 0);
return hashCode;
}
}
public override string ToString ()
=> VersionString;
// Define the is greater than operator.
public static bool operator > (SemVersion operand1, SemVersion operand2)
=> operand1.CompareTo (operand2) == 1;
// Define the is less than operator.
public static bool operator < (SemVersion operand1, SemVersion operand2)
=> operand1.CompareTo (operand2) == -1;
// Define the is greater than or equal to operator.
public static bool operator >= (SemVersion operand1, SemVersion operand2)
=> operand1.CompareTo (operand2) >= 0;
// Define the is less than or equal to operator.
public static bool operator <= (SemVersion operand1, SemVersion operand2)
=> operand1.CompareTo (operand2) <= 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment