Skip to content

Commit

Permalink
Migrate to MinVer for versioning
Browse files Browse the repository at this point in the history
  • Loading branch information
SKProCH committed Jan 28, 2024
1 parent af292a4 commit 32214d9
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 84 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ on:
push:
branches:
- master
- 'release/*'

jobs:
ubuntu-latest:
Expand All @@ -34,8 +35,8 @@ jobs:
.nuke/temp
~/.nuget/packages
key: ${{ runner.os }}-${{ hashFiles('**/global.json', '**/*.csproj', '**/Directory.Packages.props') }}
- name: 'Run: PublishNugetPackages, AppendNightlyVersionIfNeeded'
run: ./build.cmd PublishNugetPackages AppendNightlyVersionIfNeeded
- name: 'Run: PublishNugetPackages'
run: ./build.cmd PublishNugetPackages
env:
NuGetApiKey: ${{ secrets.NUGET_API_KEY }}
- name: 'Publish: nuget'
Expand Down
10 changes: 5 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ jobs:
env:
NuGetApiKey: ${{ secrets.NUGET_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: 'Publish: demo'
uses: actions/upload-artifact@v3
with:
name: demo
path: artifacts/demo
- name: 'Publish: nuget'
uses: actions/upload-artifact@v3
with:
name: nuget
path: artifacts/nuget
- name: 'Publish: demo'
uses: actions/upload-artifact@v3
with:
name: demo
path: artifacts/demo
4 changes: 0 additions & 4 deletions .nuke/build.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,9 @@
"items": {
"type": "string",
"enum": [
"AppendNightlyVersionIfNeeded",
"Clean",
"Compile",
"CreateIntermediateNugetPackages",
"FetchNuget",
"PackDemoApp",
"PackNugetPackages",
"PublishNugetPackages",
Expand All @@ -104,11 +102,9 @@
"items": {
"type": "string",
"enum": [
"AppendNightlyVersionIfNeeded",
"Clean",
"Compile",
"CreateIntermediateNugetPackages",
"FetchNuget",
"PackDemoApp",
"PackNugetPackages",
"PublishNugetPackages",
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Version>3.2.2</Version>
<PackageReleaseNotes>https://github.com/AvaloniaCommunity/Material.Avalonia/releases/tag/v3.2.2</PackageReleaseNotes>
<PackageReleaseNotes>https://github.com/AvaloniaCommunity/Material.Avalonia/releases/tag/v$(Version)</PackageReleaseNotes>

<AccelerateBuildsInVisualStudio>true</AccelerateBuildsInVisualStudio>
</PropertyGroup>
Expand Down
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<PackageVersion Include="ShowMeTheXaml.Avalonia.Generator" Version="$(ShowMeTheXamlVersion)" />
<!--For _build-->
<PackageVersion Include="Nuke.Common" Version="8.0.0" />
<PackageVersion Include="MinVer" Version="4.3.0" />
<PackageVersion Include="NuGet.Protocol" Version="6.7.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
</ItemGroup>
Expand Down
17 changes: 15 additions & 2 deletions build/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@
using Nuke.Common.Git;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.MinVer;
using Serilog;
// ReSharper disable AllUnderscoreLocalParameterName
// ReSharper disable InconsistentNaming

[GitHubActions("main", GitHubActionsImage.UbuntuLatest, AutoGenerate = true,
OnPushBranches = ["master"],
InvokedTargets = [nameof(PublishNugetPackages), nameof(AppendNightlyVersionIfNeeded)],
OnPushBranches = ["master", "release/*"],
InvokedTargets = [nameof(PublishNugetPackages)],
ImportSecrets = [nameof(NuGetApiKey)])]
[GitHubActions("release", GitHubActionsImage.UbuntuLatest, AutoGenerate = true,
OnPushTags = ["*"],
Expand All @@ -19,6 +22,7 @@
ImportSecrets = [nameof(NuGetApiKey)],
EnableGitHubToken = true)]
partial class Build : NukeBuild {
[MinVer] MinVer MinVer = null!;
[GitRepository] readonly GitRepository Repository = null!;
[Solution] readonly Solution Solution = null!;
BuildParameters Parameters { get; set; } = null!;
Expand Down Expand Up @@ -102,6 +106,15 @@ void PublishFor(string rid, string fileExtension = "") {

/// <inheritdoc />
protected override void OnBuildInitialized() {
MinVer = MinVerTasks.MinVer(s => s
.DisableProcessLogOutput()
.SetTagPrefix("v")
.SetDefaultPreReleasePhase("nightly"))
.Result;

Parameters = new BuildParameters(this);

Log.Information("Building version {Version} of Material.Avalonia ({Configuration}) using version {NukeVersion} of Nuke",
Parameters.Version, Parameters.Configuration, typeof(NukeBuild).Assembly.GetName().Version!.ToString());
}
}
92 changes: 35 additions & 57 deletions build/BuildOnPipelines.cs
Original file line number Diff line number Diff line change
@@ -1,60 +1,20 @@
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using Nuke.Common;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.GitHub;
using Octokit;
using Octokit.Internal;
using Serilog;
partial class Build {
Target FetchNuget => _ => _
.Unlisted()
.OnlyWhenDynamic(() => Parameters.ShouldPublishNugetPackages)
.Executes(async () => {
var logger = NugetLogger.Instance;
var cancellationToken = CancellationToken.None;
var cache = new SourceCacheContext();
var repository = NuGet.Protocol.Core.Types.Repository.Factory.GetCoreV3(Parameters.NugetFeedUrl);
var resource = await repository.GetResourceAsync<PackageMetadataResource>();
var parametersNugetPackages = await resource.GetMetadataAsync(
"Material.Avalonia",
true,
false,
cache,
logger,
cancellationToken);

var packages = parametersNugetPackages as IPackageSearchMetadata[] ?? parametersNugetPackages.ToArray();
Parameters.NugetPackages = packages;

Log.Information("Fetched {PackagesCount} package versions from nuget", packages.Length);
});

Target AppendNightlyVersionIfNeeded => _ => _
.Unlisted()
.DependsOn(FetchNuget)
.Before(CreateIntermediateNugetPackages)
.OnlyWhenDynamic(() => Parameters.ShouldPublishNugetPackages)
.Executes(() => {
var isVersionPublished = Parameters.NugetPackages
.Where(metadata => metadata.Identity.HasVersion)
.Any(metadata => metadata.Identity.Version.ToString() == Parameters.Version);

Parameters.IsReleaseToPublish = !isVersionPublished;
if (isVersionPublished) {
Log.Information("Found already published version {Version}. Appending .{NightlyNumber}-nightly tag", Parameters.Version, Parameters.NightlyHeight);
Parameters.Version += $".{Parameters.NightlyHeight}-nightly";
}
});

Target PublishNugetPackages => _ => _
.OnlyWhenDynamic(() => Parameters.NugetApiKey is not null)
.OnlyWhenDynamic(() => Parameters.ShouldPublishNugetPackages)
Expand All @@ -69,9 +29,10 @@ partial class Build {

Target PublishRelease => _ => _
.Unlisted()
.OnlyWhenDynamic(() => Parameters.IsRunningOnGitHubActions)
.DependsOn(FetchNuget, PackDemoApp)
.Triggers(PublishNugetPackages)
.OnlyWhenDynamic(() => Parameters.NugetApiKey is not null)
.OnlyWhenDynamic(() => Parameters.ShouldPublishNugetPackages)
.DependsOn(PackDemoApp)
.DependsOn(PublishNugetPackages)
.Executes(async () => {
var releaseVersion = NuGetVersion.Parse(GitHubActions.Instance.RefName.TrimStart('v'));
var tagName = $"v{releaseVersion}";
Expand All @@ -87,7 +48,7 @@ partial class Build {
var oldRelease = await GitHubTasks.GitHubClient.Repository.Release.Get(owner, name, tagName);
await GitHubTasks.GitHubClient.Repository.Release.Delete(owner, name, oldRelease.Id);
}
catch (Exception _) {
catch (Exception) {
// ignored
}

Expand All @@ -96,23 +57,40 @@ partial class Build {
GenerateReleaseNotes = true
};
var release = await GitHubTasks.GitHubClient.Repository.Release.Create(owner, name, newRelease);
var artifacts = NugetRoot.GetFiles("*.nupkg")
.Concat(DemoDir.GetFiles());
var nugetArtifacts = NugetRoot.GetFiles("*.nupkg").ToImmutableArray();
var artifacts = nugetArtifacts.Concat(DemoDir.GetFiles());
foreach (var artifactPath in artifacts) {
await using var fileStream = File.OpenRead(artifactPath);
var releaseAssetUpload = new ReleaseAssetUpload(artifactPath.Name, "application/octet-stream", fileStream, null);
await GitHubTasks.GitHubClient.Repository.Release.UploadAsset(release, releaseAssetUpload);
}

var outdatedVersions = Parameters.NugetPackages
.Where(metadata => metadata.Identity.HasVersion)
.Where(metadata => metadata.Identity.Version.IsPrerelease)
.Where(metadata => metadata.Identity.Version < releaseVersion);
foreach (var outdatedVersion in outdatedVersions) {
var packageUpdateResource = await NuGet.Protocol.Core.Types.Repository.Factory.GetCoreV3(Parameters.NugetFeedUrl)
.GetResourceAsync<PackageUpdateResource>();
await packageUpdateResource.Delete("Material.Avalonia", outdatedVersion.Identity.ToString(),
_ => Parameters.NugetApiKey, _ => true, false, NugetLogger.Instance);
var nuget = NuGet.Protocol.Core.Types.Repository.Factory.GetCoreV3(Parameters.NugetFeedUrl);
foreach (var nugetArtifact in nugetArtifacts) {
var packageName = nugetArtifact.Name.Split(Parameters.Version)[0];
await HideOutdatedPackages(nuget, releaseVersion, packageName);
}
return;

async Task HideOutdatedPackages(SourceRepository sourceRepository, NuGetVersion nuGetVersion, string packageName) {
var resource = await sourceRepository.GetResourceAsync<PackageMetadataResource>();
var parametersNugetPackages = await resource.GetMetadataAsync(
packageName,
true,
false,
new SourceCacheContext(),
NugetLogger.Instance,
CancellationToken.None);

var outdatedVersions = parametersNugetPackages
.Where(metadata => metadata.Identity.HasVersion)
.Where(metadata => metadata.Identity.Version.IsPrerelease)
.Where(metadata => metadata.Identity.Version < nuGetVersion);
foreach (var outdatedVersion in outdatedVersions) {
var packageUpdateResource = await sourceRepository.GetResourceAsync<PackageUpdateResource>();
await packageUpdateResource.Delete(packageName, outdatedVersion.Identity.ToString(),
_ => Parameters.NugetApiKey, _ => true, false, NugetLogger.Instance);
}
}
});
}
16 changes: 3 additions & 13 deletions build/BuildParameters.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using NuGet.Protocol.Core.Types;
using Nuke.Common;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;

public partial class Build {
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
Expand Down Expand Up @@ -45,10 +40,11 @@ public BuildParameters(Build b) {
IsMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, RepositoryBranch);
IsReleasable = Configuration.Release == Configuration;

ShouldPublishNugetPackages = IsRunningOnGitHubActions && IsMasterBranch && IsReleasable;
ShouldPublishNugetPackages = IsRunningOnGitHubActions && IsMasterBranch && IsReleasable
&& (b.MinVer.MinVerPreRelease is null || !b.MinVer.MinVerPreRelease.EndsWith(".0"));

// VERSION
Version = b.ForceVersion ?? GetVersion();
Version = b.ForceVersion ?? b.MinVer.Version;
}
public Configuration Configuration { get; }
public string MainRepo { get; }
Expand All @@ -64,12 +60,6 @@ public BuildParameters(Build b) {
public bool ShouldPublishNugetPackages { get; set; }
public string NugetFeedUrl { get; set; }
public string? NugetApiKey { get; set; }
public IEnumerable<IPackageSearchMetadata> NugetPackages { get; set; } = null!;
public bool IsReleaseToPublish { get; set; }

static string GetVersion() {
var xdoc = XDocument.Load(RootDirectory / "Directory.Build.props");
return xdoc.Descendants().First(x => x.Name.LocalName == "Version").Value;
}
}
}
12 changes: 12 additions & 0 deletions build/_build.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,20 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MinVer">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NuGet.Protocol" />
<PackageReference Include="Nuke.Common" />
</ItemGroup>

<ItemGroup>
<PackageDownload Include="minver-cli" Version="[4.3.0]" />
</ItemGroup>

<PropertyGroup>
<MinVerTagPrefix>v</MinVerTagPrefix>
<MinVerDefaultPreReleaseIdentifiers>nightly</MinVerDefaultPreReleaseIdentifiers>
</PropertyGroup>
</Project>

0 comments on commit 32214d9

Please sign in to comment.