Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/Azure.Functions.Sdk/Azure.Functions.Sdk.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,16 @@
<DevelopmentDependency>true</DevelopmentDependency>
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
<VersionPrefix>0.1.0</VersionPrefix>
<PolySharpExcludeGeneratedTypes>System.Runtime.CompilerServices.ModuleInitializerAttribute</PolySharpExcludeGeneratedTypes>
<PolySharpExcludeGeneratedTypes>System.Runtime.CompilerServices.ModuleInitializerAttribute;System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute</PolySharpExcludeGeneratedTypes>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.6" />
<PackageReference Include="TestableIO.System.IO.Abstractions.Wrappers" Version="22.0.15" />
</ItemGroup>

<ItemGroup>
<!-- These packages are provided by MSBuild / dotnet sdk at runtime, we want to reference but NOT include them. -->
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="17.11.48" ExcludeAssets="Runtime" />
<PackageReference Include="NuGet.ProjectModel" Version="6.14.0" ExcludeAssets="Runtime" />
</ItemGroup>
Expand Down
15 changes: 15 additions & 0 deletions src/Azure.Functions.Sdk/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Azure.Functions.Sdk;

/// <summary>
/// Commonly used constants.
/// </summary>
internal static class Constants
{
/// <summary>
/// The folder name where Azure Functions extensions are output.
/// </summary>
public const string ExtensionsOutputFolder = ".azurefunctions";
}
49 changes: 49 additions & 0 deletions src/Azure.Functions.Sdk/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace System;

/// <summary>
/// Extensions for exceptions.
/// </summary>
internal static class ExceptionExtensions
{
/// <summary>
/// Determines whether the exception is considered fatal and should not be caught.
/// </summary>
/// <param name="exception">The exception to check.</param>
/// <returns></returns>
public static bool IsFatal(this Exception? exception)
{
while (exception is not null)
{
if (exception
is (OutOfMemoryException and not InsufficientMemoryException)
or AppDomainUnloadedException
or BadImageFormatException
or CannotUnloadAppDomainException
or InvalidProgramException
or AccessViolationException)
{
return true;
}

if (exception is AggregateException aggregate)
{
foreach (Exception inner in aggregate.InnerExceptions)
{
if (inner.IsFatal())
{
return true;
}
}
}
else
{
exception = exception.InnerException;
}
}

return false;
}
}
53 changes: 53 additions & 0 deletions src/Azure.Functions.Sdk/ExtensionReference.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;

namespace Azure.Functions.Sdk;

/// <summary>
/// Represents an Azure Functions extension reference.
/// </summary>
public static class ExtensionReference
{
private const string ExtensionsInformationType = "Microsoft.Azure.Functions.Worker.Extensions.Abstractions.ExtensionInformationAttribute";

/// <summary>
/// Gets the root path of the Azure Functions SDK module.
/// </summary>
/// <param name="path">The path to the assembly.</param>
/// <param name="sourcePackageId">The source package ID.</param>
/// <param name="extensionReference">The resulting extension reference, if found.</param>
public static bool TryGetFromModule(
string path,
string sourcePackageId,
[NotNullWhen(true)] out ITaskItem? extensionReference)
{
// Read the assembly from the specified path
using AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(path);

// Find the extension attribute
foreach (CustomAttribute customAttribute in assembly.CustomAttributes)
{
if (string.Equals(
customAttribute.AttributeType.FullName,
ExtensionsInformationType,
StringComparison.Ordinal))
{
customAttribute.GetArguments(out string name, out string version);
extensionReference = new TaskItem(name);
extensionReference.SetVersion(version);
extensionReference.SetIsImplicitlyDefined(true);
extensionReference.SetSourcePackageId(sourcePackageId);

return true;
}
}

extensionReference = default;
return false;
}
}
26 changes: 26 additions & 0 deletions src/Azure.Functions.Sdk/FunctionsAssemblyScanner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Text.RegularExpressions;

namespace Azure.Functions.Sdk;

/// <summary>
/// Class to help with scanning functions related assemblies.
/// </summary>
public sealed partial class FunctionsAssemblyScanner
{
private static readonly Regex ExcludedPackagesRegex = new(
@"^(System|Azure\.Core|Azure\.Identity|Microsoft\.Bcl|Microsoft\.Extensions|Microsoft\.Identity|Microsoft\.NETCore|Microsoft\.NETStandard|Microsoft\.Win32|Grpc)(\..*|$)",
RegexOptions.Compiled);

/// <summary>
/// Checks if the given package name should be scanned or not.
/// </summary>
/// <param name="name">The name of the package.</param>
/// <returns><c>true</c> if package should be scanned, <c>false</c> otherwise.</returns>
public static bool ShouldScanPackage(string name)
{
return !string.IsNullOrEmpty(name) && !ExcludedPackagesRegex.IsMatch(name);
}
}
25 changes: 25 additions & 0 deletions src/Azure.Functions.Sdk/LockFileExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using NuGet.Packaging;
using NuGet.ProjectModel;

namespace Azure.Functions.Sdk;

/// <summary>
/// Extensions for NuGet lock files.
/// </summary>
public static class LockFileExtensions
{
/// <summary>
/// Gets a package path resolver for the given lock file.
/// </summary>
/// <param name="lockFile">The lock file.</param>
/// <returns></returns>
public static FallbackPackagePathResolver GetPathResolver(this LockFile lockFile)
{
Throw.IfNull(lockFile);
string? userPackageFolder = lockFile.PackageFolders.FirstOrDefault()?.Path;
return new(userPackageFolder, lockFile.PackageFolders.Skip(1).Select(folder => folder.Path));
}
}
195 changes: 195 additions & 0 deletions src/Azure.Functions.Sdk/MSBuildNugetLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.Common;

namespace Azure.Functions.Sdk;

/// <summary>
/// Provides an implementation of the NuGet logger that routes log messages to MSBuild's logging infrastructure.
/// </summary>
/// <param name="logger">The MSBuild task logging helper used to record log messages. Cannot be null.</param>
internal sealed class MSBuildNugetLogger(TaskLoggingHelper logger)
: NuGet.Common.ILogger
{
private readonly TaskLoggingHelper _logger = Throw.IfNull(logger);

private delegate void LogMessageWithDetails(string subcategory,
string code,
string helpKeyword,
string? file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
MessageImportance importance,
string message,
params object[] messageArgs);

private delegate void LogErrorWithDetails(string subcategory,
string code,
string helpKeyword,
string? file,
int lineNumber,
int columnNumber,
int endLineNumber,
int endColumnNumber,
string message,
params object[] messageArgs);

private delegate void LogMessageAsString(MessageImportance importance,
string message,
params object[] messageArgs);

private delegate void LogErrorAsString(string message,
params object[] messageArgs);

/// <inheritdoc />
public void Log(LogLevel level, string data)
{
switch (level)
{
case LogLevel.Warning:
_logger.LogWarning(data);
break;
case LogLevel.Error:
_logger.LogError(data);
break;
default:
MessageImportance importance = Convert(level);
_logger.LogMessage(importance, data);
break;
}
}

/// <inheritdoc />
public void Log(ILogMessage message)
{
INuGetLogMessage nugetMessage = message switch
{
INuGetLogMessage nugetLogMessage => nugetLogMessage,
_ => new RestoreLogMessage(message.Level, message.Message)
{
Code = message.Code,
FilePath = message.ProjectPath,
ProjectPath = message.ProjectPath,
},
};

if (nugetMessage.Code == NuGetLogCode.Undefined)
{
Log(nugetMessage.Level, nugetMessage.Message);
}
else
{
string enumName = Enum.GetName(typeof(NuGetLogCode), nugetMessage.Code);
switch (nugetMessage.Level)
{
case LogLevel.Warning:
_logger.LogWarning(string.Empty,
enumName,
enumName,
nugetMessage.FilePath,
nugetMessage.StartLineNumber,
nugetMessage.StartColumnNumber,
nugetMessage.EndLineNumber,
nugetMessage.EndColumnNumber,
nugetMessage.Message);
break;
case LogLevel.Error:
_logger.LogError(string.Empty,
enumName,
enumName,
nugetMessage.FilePath,
nugetMessage.StartLineNumber,
nugetMessage.StartColumnNumber,
nugetMessage.EndLineNumber,
nugetMessage.EndColumnNumber,
nugetMessage.Message);
break;
default:
_logger.LogMessage(string.Empty,
enumName,
enumName,
nugetMessage.FilePath,
nugetMessage.StartLineNumber,
nugetMessage.StartColumnNumber,
nugetMessage.EndLineNumber,
nugetMessage.EndColumnNumber,
Convert(nugetMessage.Level),
nugetMessage.Message);
break;
}
}
}

/// <inheritdoc />
public System.Threading.Tasks.Task LogAsync(LogLevel level, string data)
{
Log(level, data);
return System.Threading.Tasks.Task.CompletedTask;
}

/// <inheritdoc />
public System.Threading.Tasks.Task LogAsync(ILogMessage message)
{
Log(message);
return System.Threading.Tasks.Task.CompletedTask;
}

/// <inheritdoc />
public void LogDebug(string data)
{
Log(LogLevel.Debug, data);
}

/// <inheritdoc />
public void LogError(string data)
{
Log(LogLevel.Error, data);
}

/// <inheritdoc />
public void LogInformation(string data)
{
Log(LogLevel.Information, data);
}

/// <inheritdoc />
public void LogInformationSummary(string data)
{
LogInformation(data);
}

/// <inheritdoc />
public void LogMinimal(string data)
{
Log(LogLevel.Minimal, data);
}

/// <inheritdoc />
public void LogVerbose(string data)
{
Log(LogLevel.Verbose, data);
}

/// <inheritdoc />
public void LogWarning(string data)
{
Log(LogLevel.Warning, data);
}

private static MessageImportance Convert(LogLevel level)
{
return level switch
{
LogLevel.Debug => MessageImportance.Low,
LogLevel.Verbose => MessageImportance.Low,
LogLevel.Information => MessageImportance.Normal,
LogLevel.Minimal => MessageImportance.High,
_ => MessageImportance.Low,
};
}
}
Loading