Skip to content

Commit

Permalink
fix analyzer DLLs configuration (#646)
Browse files Browse the repository at this point in the history
* fix asset postprocessor to work with newer unity version
* also fix case where analyzer setting was not applied
* wrapp asset importing in StartAssetEditing / StopAssetEditing
  • Loading branch information
JoC0de authored Jun 1, 2024
1 parent 630d3db commit b9f895b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 43 deletions.
13 changes: 13 additions & 0 deletions src/NuGetForUnity.Tests/Assets/Tests/Editor/NuGetTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NugetForUnity;
using NugetForUnity.Configuration;
Expand All @@ -14,6 +15,7 @@
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;

public class NuGetTests
{
Expand Down Expand Up @@ -942,6 +944,8 @@ public void TestSerializeNugetPackageIdentifier(string version)
[TestCase("jQuery", "3.7.0")]
public void TestPostprocessInstall(string packageId, string packageVersion)
{
IgnorePackagesConfigImportError();

var package = new NugetPackageIdentifier(packageId, packageVersion) { IsManuallyInstalled = true };

var filepath = ConfigurationManager.NugetConfigFile.PackagesConfigFilePath;
Expand All @@ -960,6 +964,8 @@ public void TestPostprocessInstall(string packageId, string packageVersion)
[TestCase("jQuery", "3.7.0")]
public void TestPostprocessUninstall(string packageId, string packageVersion)
{
IgnorePackagesConfigImportError();

var package = new NugetPackageIdentifier(packageId, packageVersion) { IsManuallyInstalled = true };

var filepath = ConfigurationManager.NugetConfigFile.PackagesConfigFilePath;
Expand All @@ -980,6 +986,8 @@ public void TestPostprocessUninstall(string packageId, string packageVersion)
[TestCase("jQuery", "3.7.0", "3.6.4")]
public void TestPostprocessDifferentVersion(string packageId, string packageVersionOld, string packageVersionNew)
{
IgnorePackagesConfigImportError();

var packageOld = new NugetPackageIdentifier(packageId, packageVersionOld) { IsManuallyInstalled = true };
var packageNew = new NugetPackageIdentifier(packageId, packageVersionNew) { IsManuallyInstalled = true };

Expand Down Expand Up @@ -1076,6 +1084,11 @@ public void TestSourceCodePackageInstall(string packageId, string packageVersion
Assert.IsFalse(InstalledPackagesManager.IsInstalled(package, false), "The package is STILL installed: {0} {1}", package.Id, package.Version);
}

private static void IgnorePackagesConfigImportError()
{
LogAssert.Expect(LogType.Error, new Regex("NuGetForUnity: failed to process: .*packages.config' \\(ConfigurationFile\\)"));
}

private static void ConfigureNugetConfig(InstallMode installMode)
{
var nugetConfigFile = ConfigurationManager.NugetConfigFile;
Expand Down
87 changes: 44 additions & 43 deletions src/NuGetForUnity/Editor/NugetAssetPostprocessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,16 +87,26 @@ internal static void OnPostprocessAllAssets(
}

var packagesConfigFilePath = ConfigurationManager.NugetConfigFile.PackagesConfigFilePath;
var foundPackagesConfigAsset = importedAssets.Any(
importedAsset => Path.GetFullPath(importedAsset).Equals(packagesConfigFilePath, StringComparison.Ordinal));

if (!foundPackagesConfigAsset)
if (importedAssets.Any(
path => path.EndsWith(PackagesConfigFile.FileName) &&
Path.GetFullPath(path).Equals(packagesConfigFilePath, StringComparison.Ordinal)))
{
return;
InstalledPackagesManager.ReloadPackagesConfig();
PackageRestorer.Restore(ConfigurationManager.NugetConfigFile.SlimRestore);
}

InstalledPackagesManager.ReloadPackagesConfig();
PackageRestorer.Restore(ConfigurationManager.NugetConfigFile.SlimRestore);
var absoluteRepositoryPath = GetNuGetRepositoryPath();

AssetDatabase.StartAssetEditing();

try
{
LogResults(importedAssets.SelectMany(assetPath => HandleAsset(assetPath, absoluteRepositoryPath, true)));
}
finally
{
AssetDatabase.StopAssetEditing();
}
}

[NotNull]
Expand Down Expand Up @@ -128,7 +138,7 @@ internal static void OnPostprocessAllAssets(
var assetPathComponents = GetPathComponents(assetPathRelativeToRepository);
var packageNameParts = assetPathComponents.Length > 0 ? assetPathComponents[0].Split('.') : Array.Empty<string>();
var packageName = string.Join(".", packageNameParts.TakeWhile(part => !part.All(char.IsDigit)));
var packageConfig = InstalledPackagesManager.PackagesConfigFile.GetPackageConfigurationById(packageName);
var configurationOfPackage = InstalledPackagesManager.PackagesConfigFile.GetPackageConfigurationById(packageName);

if (!GetPluginImporter(projectRelativeAssetPath, out var plugin))
{
Expand All @@ -144,26 +154,37 @@ internal static void OnPostprocessAllAssets(
yield break;
}

if (packageConfig != null)
var assetLablesToSet = new List<string>();
if (configurationOfPackage != null)
{
ModifyImportSettingsOfGeneralPlugin(packageConfig, plugin, reimport);
assetLablesToSet.AddRange(ModifyImportSettingsOfGeneralPlugin(configurationOfPackage, plugin));
yield return ("GeneralSetting", projectRelativeAssetPath, ResultStatus.Success);
}

if (assetPathComponents.Length > 1 && assetPathComponents[1].Equals(AnalyzersFolderName, StringComparison.OrdinalIgnoreCase))
{
ModifyImportSettingsOfRoslynAnalyzer(plugin, reimport);
assetLablesToSet.AddRange(ModifyImportSettingsOfRoslynAnalyzer(plugin));
yield return ("RoslynAnalyzer", projectRelativeAssetPath, ResultStatus.Success);
}
else if (assetPathComponents.Length > 0 &&
UnityPreImportedLibraryResolver.GetAlreadyImportedEditorOnlyLibraries()
.Contains(Path.GetFileNameWithoutExtension(assetPathComponents[assetPathComponents.Length - 1])))
{
assetLablesToSet.AddRange(ModifyImportSettingsOfPlayerOnly(plugin));
yield return ("PlayerOnly", projectRelativeAssetPath, ResultStatus.Success);
}

if (assetLablesToSet.Count == 0)
{
yield break;
}

if (assetPathComponents.Length > 0 &&
UnityPreImportedLibraryResolver.GetAlreadyImportedEditorOnlyLibraries()
.Contains(Path.GetFileNameWithoutExtension(assetPathComponents[assetPathComponents.Length - 1])))
AssetDatabase.SetLabels(plugin, assetLablesToSet.Distinct().ToArray());

if (reimport)
{
ModifyImportSettingsOfPlayerOnly(plugin, reimport);
yield return ("PlayerOnly", projectRelativeAssetPath, ResultStatus.Success);
// Persist and reload the change to the meta file
plugin.SaveAndReimport();
}
}

Expand Down Expand Up @@ -228,7 +249,7 @@ private static NugetPackageVersion GetRoslynVersionNumberFromAnalyzerPath(string
return string.IsNullOrEmpty(versionString) ? null : new NugetPackageVersion(versionString);
}

private static void ModifyImportSettingsOfRoslynAnalyzer([NotNull] PluginImporter plugin, bool reimport)
private static string[] ModifyImportSettingsOfRoslynAnalyzer([NotNull] PluginImporter plugin)
{
plugin.SetCompatibleWithAnyPlatform(false);
plugin.SetCompatibleWithEditor(false);
Expand Down Expand Up @@ -271,28 +292,15 @@ private static void ModifyImportSettingsOfRoslynAnalyzer([NotNull] PluginImporte
}
}

AssetDatabase.SetLabels(plugin, enableRoslynAnalyzer ? new[] { RoslynAnalyzerLabel, ProcessedLabel } : new[] { ProcessedLabel });

if (reimport)
{
// Persist and reload the change to the meta file
plugin.SaveAndReimport();
}

NugetLogger.LogVerbose("Configured asset '{0}' as a Roslyn-Analyzer.", plugin.assetPath);
return enableRoslynAnalyzer ? new[] { RoslynAnalyzerLabel, ProcessedLabel } : new[] { ProcessedLabel };
}

private static void ModifyImportSettingsOfGeneralPlugin([NotNull] PackageConfig packageConfig, [NotNull] PluginImporter plugin, bool reimport)
private static string[] ModifyImportSettingsOfGeneralPlugin([NotNull] PackageConfig packageConfig, [NotNull] PluginImporter plugin)
{
PluginImporterIsExplicitlyReferencedProperty.SetValue(plugin, !packageConfig.AutoReferenced);

AssetDatabase.SetLabels(plugin, new[] { ProcessedLabel });

if (reimport)
{
// Persist and reload the change to the meta file
plugin.SaveAndReimport();
}
return new[] { ProcessedLabel };
}

/// <summary>
Expand All @@ -301,21 +309,14 @@ private static void ModifyImportSettingsOfGeneralPlugin([NotNull] PackageConfig
/// <seealso cref="UnityPreImportedLibraryResolver.GetAlreadyImportedEditorOnlyLibraries" />.
/// </summary>
/// <param name="plugin">The asset to edit.</param>
/// <param name="reimport">Whether or not to save and re-import the file.</param>
private static void ModifyImportSettingsOfPlayerOnly([NotNull] PluginImporter plugin, bool reimport)
private static string[] ModifyImportSettingsOfPlayerOnly([NotNull] PluginImporter plugin)
{
plugin.SetCompatibleWithAnyPlatform(true);
plugin.SetExcludeEditorFromAnyPlatform(true);

AssetDatabase.SetLabels(plugin, new[] { ProcessedLabel });

if (reimport)
{
// Persist and reload the change to the meta file
plugin.SaveAndReimport();
}

NugetLogger.LogVerbose("Configured asset '{0}' as a Player Only.", plugin.assetPath);

return new[] { ProcessedLabel };
}

/// <summary>
Expand Down

0 comments on commit b9f895b

Please sign in to comment.