Skip to content

Commit

Permalink
Adding slim restore option (#576)
Browse files Browse the repository at this point in the history
* Adding slim restore option for skipping dependency installation and checking for already imported Unity libs on auto restore
  • Loading branch information
popara96 authored Oct 4, 2023
1 parent c58092e commit ad5eac2
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 48 deletions.
2 changes: 1 addition & 1 deletion src/NuGetForUnity.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static int Main(string[] args)
Application.SetUnityProjectPath(projectPath);

// need to disable dependency installation as UnityPreImportedLibraryResolver.GetAlreadyImportedLibs is not working outside Unity.
PackageRestorer.Restore(false);
PackageRestorer.Restore(true);
FixRoslynAnalyzerImportSettings();
return Debug.HasError ? 1 : 0;
}
Expand Down
27 changes: 25 additions & 2 deletions src/NuGetForUnity.Tests/Assets/Tests/Editor/NuGetTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void Cleanup()
[Order(1)]
public void SimpleRestoreTest()
{
PackageRestorer.Restore();
PackageRestorer.Restore(false);
}

[Test]
Expand Down Expand Up @@ -205,7 +205,7 @@ public void InstallStyleCopWithoutDependenciesTest()
{
var styleCopPlusId = new NugetPackageIdentifier("StyleCopPlus.MSBuild", "4.7.49.5");

NugetPackageInstaller.InstallIdentifier(styleCopPlusId, installDependencies: false);
NugetPackageInstaller.InstallIdentifier(styleCopPlusId, isSlimRestoreInstall: true);

// StyleCopPlus depends on StyleCop, so without 'installDependencies' they are both installed
Assert.That(InstalledPackagesManager.InstalledPackages, Is.EquivalentTo(new[] { styleCopPlusId }));
Expand Down Expand Up @@ -752,6 +752,29 @@ public void GetRelativePathTest(string path, string expected)
Assert.That(relativePath, Is.EqualTo(expected));
}

[Test]
[TestCase("Microsoft.Extensions.Logging", "7.0.0")]
public void TestSlimRestoreInstall(string packageId, string packageVersion)
{
var package = new NugetPackageIdentifier(packageId, packageVersion) { IsManuallyInstalled = true };

Assume.That(InstalledPackagesManager.IsInstalled(package), Is.False, "The package IS installed: {0} {1}", package.Id, package.Version);

var packagesConfigFile = new PackagesConfigFile();
packagesConfigFile.AddPackage(package);
packagesConfigFile.Save();

InstalledPackagesManager.ReloadPackagesConfig();
PackageRestorer.Restore(true);

Assert.IsTrue(InstalledPackagesManager.IsInstalled(package), "The package was NOT installed: {0} {1}", package.Id, package.Version);
Assert.IsTrue(
InstalledPackagesManager.InstalledPackages.Count() == 1,
"The dependencies WERE installed for package {0} {1}",
package.Id,
package.Version);
}

private static void ConfigureNugetConfig(InstallMode installMode)
{
var nugetConfigFile = ConfigurationManager.NugetConfigFile;
Expand Down
36 changes: 16 additions & 20 deletions src/NuGetForUnity/Editor/Configuration/NugetConfigFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ public class NugetConfigFile

private const string RequestTimeoutSecondsConfigKey = "RequestTimeoutSeconds";

private const string LockPackagesOnRestoreConfigKey = "LockPackagesOnRestore";

private const string PackagesConfigDirectoryPathConfigKey = "PackagesConfigDirectoryPath";

/// <summary>
Expand Down Expand Up @@ -88,6 +86,12 @@ public class NugetConfigFile
/// </summary>
public bool Verbose { get; set; }

/// <summary>
/// Gets or sets a value indicating whether to skip installing dependencies and checking for pre-imported Unity libs
/// while auto-restoring.
/// </summary>
public bool SlimRestore { get; set; } = true;

/// <summary>
/// Gets or sets a value indicating whether a package is installed from the cache (if present), or if it always downloads the package from the
/// server.
Expand Down Expand Up @@ -126,12 +130,6 @@ public string RelativePackagesConfigDirectoryPath
/// </summary>
public int RequestTimeoutSeconds { get; set; } = DefaultRequestTimeout;

/// <summary>
/// Gets or sets a value indicating whether the installed packages should be fixed, so only the packages that are configure inside the
/// 'package.config' are installed without installing the dependencies of them.
/// </summary>
public bool LockPackagesOnRestore { get; set; }

/// <summary>
/// Loads a NuGet.config file at the given file-path.
/// </summary>
Expand Down Expand Up @@ -260,6 +258,10 @@ public static NugetConfigFile Load([NotNull] string filePath)
{
configFile.Verbose = bool.Parse(value);
}
else if (string.Equals(key, "slimRestore", StringComparison.OrdinalIgnoreCase))
{
configFile.SlimRestore = bool.Parse(value);
}
else if (string.Equals(key, "InstallFromCache", StringComparison.OrdinalIgnoreCase))
{
configFile.InstallFromCache = bool.Parse(value);
Expand All @@ -272,10 +274,6 @@ public static NugetConfigFile Load([NotNull] string filePath)
{
configFile.RequestTimeoutSeconds = int.Parse(value, CultureInfo.InvariantCulture);
}
else if (string.Equals(key, LockPackagesOnRestoreConfigKey, StringComparison.OrdinalIgnoreCase))
{
configFile.LockPackagesOnRestore = bool.Parse(value);
}
else if (string.Equals(key, PackagesConfigDirectoryPathConfigKey, StringComparison.OrdinalIgnoreCase))
{
configFile.RelativePackagesConfigDirectoryPath = value;
Expand Down Expand Up @@ -306,6 +304,7 @@ public static NugetConfigFile CreateDefaultFile([NotNull] string filePath)
<config>
<add key=""repositoryPath"" value=""./Packages"" />
<add key=""PackagesConfigDirectoryPath"" value=""."" />
<add key=""slimRestore"" value=""true"" />
</config>
</configuration>";

Expand Down Expand Up @@ -402,6 +401,11 @@ public void Save([NotNull] string filePath)
config.Add(addElement);
}

addElement = new XElement("add");
addElement.Add(new XAttribute("key", "slimRestore"));
addElement.Add(new XAttribute("value", SlimRestore.ToString().ToLowerInvariant()));
config.Add(addElement);

if (!InstallFromCache)
{
addElement = new XElement("add");
Expand All @@ -426,14 +430,6 @@ public void Save([NotNull] string filePath)
config.Add(addElement);
}

if (LockPackagesOnRestore)
{
addElement = new XElement("add");
addElement.Add(new XAttribute("key", LockPackagesOnRestoreConfigKey));
addElement.Add(new XAttribute("value", LockPackagesOnRestore.ToString().ToLowerInvariant()));
config.Add(addElement);
}

var configuration = new XElement("configuration");
configuration.Add(packageSources);
configuration.Add(disabledPackageSources);
Expand Down
2 changes: 1 addition & 1 deletion src/NuGetForUnity/Editor/NugetAssetPostprocessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ internal static void OnPostprocessAllAssets(
}

InstalledPackagesManager.ReloadPackagesConfig();
PackageRestorer.Restore();
PackageRestorer.Restore(ConfigurationManager.NugetConfigFile.SlimRestore);
}

[NotNull]
Expand Down
16 changes: 8 additions & 8 deletions src/NuGetForUnity/Editor/NugetPackageInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ public static class NugetPackageInstaller
/// </summary>
/// <param name="package">The identifier of the package to install.</param>
/// <param name="refreshAssets">True to refresh the Unity asset database. False to ignore the changes (temporarily).</param>
/// <param name="installDependencies">True to also install all dependencies of the <paramref name="package" />.</param>
/// <param name="isSlimRestoreInstall">True to skip checking if lib is imported in Unity and skip installing dependencies.</param>
/// <returns>True if the package was installed successfully, otherwise false.</returns>
public static bool InstallIdentifier([NotNull] INugetPackageIdentifier package, bool refreshAssets = true, bool installDependencies = true)
public static bool InstallIdentifier([NotNull] INugetPackageIdentifier package, bool refreshAssets = true, bool isSlimRestoreInstall = false)
{
if (UnityPreImportedLibraryResolver.IsAlreadyImportedInEngine(package, false))
if (!isSlimRestoreInstall && UnityPreImportedLibraryResolver.IsAlreadyImportedInEngine(package, false))
{
NugetLogger.LogVerbose("Package {0} is already imported in engine, skipping install.", package);
return true;
Expand All @@ -41,19 +41,19 @@ public static bool InstallIdentifier([NotNull] INugetPackageIdentifier package,
}

foundPackage.IsManuallyInstalled = package.IsManuallyInstalled;
return Install(foundPackage, refreshAssets, installDependencies);
return Install(foundPackage, refreshAssets, isSlimRestoreInstall);
}

/// <summary>
/// Installs the given package.
/// </summary>
/// <param name="package">The package to install.</param>
/// <param name="refreshAssets">True to refresh the Unity asset database. False to ignore the changes (temporarily).</param>
/// <param name="installDependencies">True to also install all dependencies of the <paramref name="package" />.</param>
/// <param name="isSlimRestoreInstall">True to skip checking if lib is imported in Unity and skip installing dependencies.</param>
/// <returns>True if the package was installed successfully, otherwise false.</returns>
private static bool Install([NotNull] INugetPackage package, bool refreshAssets, bool installDependencies)
private static bool Install([NotNull] INugetPackage package, bool refreshAssets, bool isSlimRestoreInstall)
{
if (UnityPreImportedLibraryResolver.IsAlreadyImportedInEngine(package, false))
if (!isSlimRestoreInstall && UnityPreImportedLibraryResolver.IsAlreadyImportedInEngine(package, false))
{
NugetLogger.LogVerbose("Package {0} is already imported in engine, skipping install.", package);
return true;
Expand Down Expand Up @@ -110,7 +110,7 @@ private static bool Install([NotNull] INugetPackage package, bool refreshAssets,
EditorUtility.DisplayProgressBar($"Installing {package.Id} {package.Version}", "Installing Dependencies", 0.1f);
}

if (installDependencies)
if (!isSlimRestoreInstall)
{
var dependencies = package.Dependencies;

Expand Down
2 changes: 1 addition & 1 deletion src/NuGetForUnity/Editor/OnLoadNugetPackageRestorer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ static OnLoadNugetPackageRestorer()
ConfigurationManager.LoadNugetConfigFile();

// restore packages - this will be called EVERY time the project is loaded
PackageRestorer.Restore(!ConfigurationManager.NugetConfigFile.LockPackagesOnRestore);
PackageRestorer.Restore(ConfigurationManager.NugetConfigFile.SlimRestore);
}
}
}
8 changes: 5 additions & 3 deletions src/NuGetForUnity/Editor/PackageRestorer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ public static class PackageRestorer
/// <summary>
/// Restores all packages defined in packages.config.
/// </summary>
/// <param name="installDependencies">True to also install all dependencies of the packages listed in the <see cref="PackagesConfigFile" />.</param>
public static void Restore(bool installDependencies = true)
/// <param name="slimRestore">True if we want to skip installing dependencies and checking if the lib is imported in Unity</param>
public static void Restore(bool slimRestore)
{
InstalledPackagesManager.UpdateInstalledPackages();

Expand All @@ -41,7 +41,9 @@ public static void Restore(bool installDependencies = true)
$"Restoring {package.Id} {package.Version}",
currentProgress);
NugetLogger.LogVerbose("---Restoring {0} {1}", package.Id, package.Version);
NugetPackageInstaller.InstallIdentifier(package, installDependencies: installDependencies);
NugetPackageInstaller.InstallIdentifier(
package,
isSlimRestoreInstall: slimRestore);
somethingChanged = true;
}

Expand Down
26 changes: 15 additions & 11 deletions src/NuGetForUnity/Editor/Ui/NugetPreferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,21 @@ public override void OnGUI([CanBeNull] string searchContext)
ConfigurationManager.NugetConfigFile.Verbose = verbose;
}

var slimRestore = EditorGUILayout.Toggle(
new GUIContent(
"Slim Restore",
"Slim restore is a faster way of installing/restoring packages after opening the Unity project. " +
"To achieve this, the package installation step skips installing dependencies not listed inside the package.config, " +
"also it skips checking against Unity pre-imported libraries. If you have a complex project setup with multiple target " +
"platforms that include different packages, you might need to disable this feature. " +
"Manually restoring via menu option will ignore this setting."),
ConfigurationManager.NugetConfigFile.SlimRestore);
if (slimRestore != ConfigurationManager.NugetConfigFile.SlimRestore)
{
preferencesChangedThisFrame = true;
ConfigurationManager.NugetConfigFile.SlimRestore = slimRestore;
}

EditorGUILayout.BeginHorizontal();
{
var packagesConfigPath = ConfigurationManager.NugetConfigFile.PackagesConfigDirectoryPath;
Expand Down Expand Up @@ -133,17 +148,6 @@ public override void OnGUI([CanBeNull] string searchContext)
ConfigurationManager.NugetConfigFile.RequestTimeoutSeconds = requestTimeout;
}

var lockPackagesOnRestore = EditorGUILayout.Toggle(
new GUIContent(
"Lock Packages on Restore",
"When lock packages on restore is enabled only packages explicitly listed inside the 'packages.config' file will be installed. No dependencies are installed. This feature should only be used when having issues that unneeded or broken packages are installed."),
ConfigurationManager.NugetConfigFile.LockPackagesOnRestore);
if (lockPackagesOnRestore != ConfigurationManager.NugetConfigFile.LockPackagesOnRestore)
{
preferencesChangedThisFrame = true;
ConfigurationManager.NugetConfigFile.LockPackagesOnRestore = lockPackagesOnRestore;
}

EditorGUILayout.LabelField("Package Sources:");

scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
Expand Down
2 changes: 1 addition & 1 deletion src/NuGetForUnity/Editor/Ui/NugetWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ protected static void DisplayNugetWindow()
[MenuItem("NuGet/Restore Packages", false, 1)]
protected static void RestorePackages()
{
PackageRestorer.Restore(!ConfigurationManager.NugetConfigFile.LockPackagesOnRestore);
PackageRestorer.Restore(false);
foreach (var nugetWindow in Resources.FindObjectsOfTypeAll<NugetWindow>())
{
nugetWindow.ClearViewCache();
Expand Down

0 comments on commit ad5eac2

Please sign in to comment.