Skip to content

Commit

Permalink
Fix: requirement on json.net and also ffimage generation (#114)
Browse files Browse the repository at this point in the history
* Fix: requirement on json.net and also ffimage generation

* removed unused project
  • Loading branch information
glennawatson authored Feb 24, 2020
1 parent 5f6a5e1 commit 18a86a8
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ private static ClassDeclarationSyntax GenerateStaticClass(string namespaceName,
.WithLeadingTrivia(XmlSyntaxFactory.GenerateSummarySeeAlsoComment("A class that contains extension methods to wrap events for classes contained within the {0} namespace.", namespaceName))
.WithMembers(List<MemberDeclarationSyntax>(declarations.Select(declaration =>
{
var eventsClassName = IdentifierName(declaration.Name + "Events");
var eventsClassName = IdentifierName("Rx" + declaration.Name + "Events");
return MethodDeclaration(eventsClassName, Identifier("Events"))
.WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
.WithParameterList(ParameterList(SingletonSeparatedList(
Expand All @@ -70,7 +70,7 @@ private static ConstructorDeclarationSyntax GenerateEventWrapperClassConstructor
{
const string dataParameterName = "data";
var constructor = ConstructorDeclaration(
Identifier(typeDefinition.Name + "Events"))
Identifier("Rx" + typeDefinition.Name + "Events"))
.WithModifiers(
TokenList(
Token(SyntaxKind.PublicKeyword)))
Expand Down
22 changes: 22 additions & 0 deletions src/Pharmacist.Core/NuGet/NuGetPackageHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,28 @@ public static async Task<InputAssembliesGroup> DownloadPackageFilesAndFolder(
return await DownloadPackageFilesAndFolder(packageIdentities, frameworks, downloadResource, getDependencies, packageFolders, packageOutputDirectory, token).ConfigureAwait(false);
}

/// <summary>
/// Gets the best matching PackageIdentity for the specified LibraryRange.
/// </summary>
/// <param name="identity">The library range to find the best patch for.</param>
/// <param name="nugetSource">Optional v3 nuget source. Will default to default nuget.org servers.</param>
/// <param name="token">A optional cancellation token.</param>
/// <returns>The best matching PackageIdentity to the specified version range.</returns>
public static async Task<PackageIdentity> GetBestMatch(LibraryRange identity, PackageSource? nugetSource = null, CancellationToken token = default)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}

// Use the provided nuget package source, or use nuget.org
var sourceRepository = new SourceRepository(nugetSource ?? new PackageSource(DefaultNuGetSource), Providers);

var findPackageResource = await sourceRepository.GetResourceAsync<FindPackageByIdResource>(token).ConfigureAwait(false);

return await GetBestMatch(identity, findPackageResource, token).ConfigureAwait(false);
}

/// <summary>
/// Gets the best matching PackageIdentity for the specified LibraryRange.
/// </summary>
Expand Down
28 changes: 28 additions & 0 deletions src/Pharmacist.Core/ObservablesForEventGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,34 @@ public static async Task WriteHeader(TextWriter writer, IReadOnlyCollection<Libr
await writer.FlushAsync().ConfigureAwait(false);
}

/// <summary>
/// Writes the header for a output.
/// </summary>
/// <param name="writer">The writer where to output to.</param>
/// <param name="packageIdentities">The packages included in the output.</param>
/// <returns>A task to monitor the progress.</returns>
public static async Task WriteHeader(TextWriter writer, IReadOnlyCollection<PackageIdentity> packageIdentities)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}

if (packageIdentities == null)
{
throw new ArgumentNullException(nameof(packageIdentities));
}

await WriteHeader(writer).ConfigureAwait(false);

foreach (var packageIdentity in packageIdentities)
{
await writer.WriteLineAsync($"// Package included: {packageIdentity}").ConfigureAwait(false);
}

await writer.FlushAsync().ConfigureAwait(false);
}

/// <summary>
/// Writes the header for a output.
/// </summary>
Expand Down
1 change: 0 additions & 1 deletion src/Pharmacist.Core/Pharmacist.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
<PackageReference Include="NuGet.LibraryModel" Version="5.2.0" />
<PackageReference Include="polly" Version="7.2.0" />
<PackageReference Include="splat" Version="9.3.11" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.7.0" />
</ItemGroup>

<ItemGroup Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<PackageDescription>Produces from NuGet packages System.Reactive Observables for all events within the NuGet packages inside the project..</PackageDescription>
<TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);PackBuildOutputs</TargetsForTfmSpecificContentInPackage>
<NoWarn>$(NoWarn);CA1819</NoWarn>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
Expand All @@ -36,6 +37,5 @@
<ItemGroup>
<ProjectReference Include="..\Pharmacist.Core\Pharmacist.Core.csproj" PrivateAssets="All" />
<ProjectReference Include="..\Pharmacist.Common\Pharmacist.Common.csproj" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.7.0" PrivateAssets="all" />
</ItemGroup>
</Project>
90 changes: 66 additions & 24 deletions src/Pharmacist.MsBuild.NuGet/PharmacistNuGetTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging.Core;
using NuGet.Versioning;

using Pharmacist.Core;
Expand All @@ -30,6 +32,7 @@ namespace Pharmacist.MsBuild.NuGet
public class PharmacistNuGetTask : Task, IEnableLogger
{
private static readonly Regex _versionRegex = new Regex(@"(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex _packageRegex = new Regex("^(.*)/(.*)$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static readonly Dictionary<Guid, string> _guidToFramework = new Dictionary<Guid, string>()
{
[new Guid("EFBA0AD7-5A72-4C68-AF49-83D382785DCF")] = "MonoAndroid",
Expand Down Expand Up @@ -85,7 +88,7 @@ [new Guid("A3F8F2AB-B479-4A4A-A458-A89E7DC349F1")] = "Xamarin.Mac",
/// <inheritdoc />
public override bool Execute()
{
var jsonSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented };
var lockFile = OutputFile + ".lock";
var funcLogManager = new FuncLogManager(type => new WrappingFullLogger(new WrappingPrefixLogger(new MsBuildLogger(Log, LogLevel.Debug), type)));
Locator.CurrentMutable.RegisterConstant(funcLogManager, typeof(ILogManager));

Expand All @@ -104,28 +107,14 @@ public override bool Execute()

var packages = GetPackages();

if (File.Exists(LockFile) && File.Exists(OutputFile))
var lockPackages = ReadPackages(lockFile);

if (lockPackages != null && lockPackages.Count == packages.Count && lockPackages.All(packages.Contains))
{
try
{
var fileContents = File.ReadAllText(LockFile);
var lockedLibraries = JsonConvert.DeserializeObject<List<LibraryRange>>(fileContents, jsonSettings);
if (lockedLibraries != null && lockedLibraries.Count == packages.Count && lockedLibraries.All(packages.Contains))
{
return true;
}
}
catch (JsonException ex)
{
Log.LogWarningFromException(ex);
}
catch (Exception ex)
{
Log.LogWarningFromException(ex);
}
return true;
}

using (var writer = new StreamWriter(Path.Combine(OutputFile)))
using (var writer = new StreamWriter(Path.Combine(OutputFile), false, Encoding.UTF8))
{
ObservablesForEventGenerator.WriteHeader(writer, packages).ConfigureAwait(false).GetAwaiter().GetResult();

Expand All @@ -140,7 +129,8 @@ public override bool Execute()
}
}

File.WriteAllText(LockFile, JsonConvert.SerializeObject(packages, jsonSettings));
WritePackages(packages, lockFile);

return true;
}

Expand Down Expand Up @@ -175,9 +165,9 @@ private IReadOnlyCollection<NuGetFramework> GetTargetFrameworks()
return nugetFrameworks;
}

private List<LibraryRange> GetPackages()
private List<PackageIdentity> GetPackages()
{
var packages = new List<LibraryRange>();
var packages = new List<PackageIdentity>();

// Include all package references that aren't ourselves.
foreach (var packageReference in PackageReferences)
Expand All @@ -195,11 +185,63 @@ private List<LibraryRange> GetPackages()
continue;
}

var packageIdentity = new LibraryRange(include, nuGetVersion, LibraryDependencyTarget.Package);
var libraryRange = new LibraryRange(include, nuGetVersion, LibraryDependencyTarget.Package);
var packageIdentity = NuGetPackageHelper.GetBestMatch(libraryRange).GetAwaiter().GetResult();
packages.Add(packageIdentity);
}

return packages;
}

private void WritePackages(List<PackageIdentity> packageIdentities, string lockFileName)
{
using var streamWriter = new StreamWriter(lockFileName, false, Encoding.UTF8);
foreach (var packageIdentity in packageIdentities)
{
streamWriter.WriteLine($"{packageIdentity.Id}/{packageIdentity.Version}");
}
}

private List<PackageIdentity> ReadPackages(string lockFileName)
{
if (string.IsNullOrWhiteSpace(lockFileName))
{
throw new ArgumentException("Cannot have a empty lock file name", nameof(lockFileName));
}

var packageIdentities = new List<PackageIdentity>();

if (File.Exists(lockFileName) == false)
{
return packageIdentities;
}

try
{
using var streamReader = new StreamReader(lockFileName, Encoding.UTF8, true);

string line;

while ((line = streamReader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}

var match = _packageRegex.Match(line);

var packageIdentity = new PackageIdentity(match.Groups[1].Value, NuGetVersion.Parse(match.Groups[2].Value));

packageIdentities.Add(packageIdentity);
}
}
catch
{
packageIdentities = new List<PackageIdentity>();
}

return packageIdentities;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,5 @@
<ItemGroup>
<ProjectReference Include="..\Pharmacist.Core\Pharmacist.Core.csproj" PrivateAssets="All" />
<ProjectReference Include="..\Pharmacist.Common\Pharmacist.Common.csproj" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.7.0" PrivateAssets="all" />
</ItemGroup>
</Project>

0 comments on commit 18a86a8

Please sign in to comment.