Example #1
0
        private static async Task Browse(IOwinContext context)
        {
            string redirectTo;

            var q    = context.Request.Query;
            var hash = q["hash"];

            if (string.IsNullOrEmpty(hash))
            {
                string       error        = null;
                var          source       = q["source"];
                var          packageId    = q["packageId"];
                var          version      = q["version"];
                NuGetVersion nugetVersion = null;

                if (string.IsNullOrWhiteSpace(packageId))
                {
                    error = "Package ID is required";
                }
                else if (!string.IsNullOrWhiteSpace(version) && !NuGetVersion.TryParse(version, out nugetVersion))
                {
                    error = "Version is not valid as NuGetVersion";
                }

                if (error != null)
                {
                    await context.Response.Error(400, new ErrorModel(error)).ConfigureAwait(false);

                    return;
                }

                var packageDir = await NuGetUtility.GetPackage(source, packageId, nugetVersion).ConfigureAwait(false);

                var s = packageDir.FullName.Split(Path.DirectorySeparatorChar);
                redirectTo = string.Format("repositories/{0}/{1}/",
                                           s[s.Length - 2], // repository hash
                                           s[s.Length - 1]  // package name and version
                                           );
            }
            else
            {
                redirectTo = string.Concat("upload/", hash, "/");
            }

            context.Response.StatusCode = 303;
            context.Response.Headers.Set("Location", string.Concat(
                                             context.Request.Uri.GetLeftPart(UriPartial.Path),
                                             "/",
                                             redirectTo
                                             ));
        }
Example #2
0
        public void TestDetectingNewestFramework()
        {
            var autoDetectedFW = NuGetUtility.TryAutoDetectThisProcessFramework();
            var specifiedFW    = NuGetFramework.ParseFolder(Environment.GetEnvironmentVariable("THIS_TFM"));

            //XDocument csProj;
            //using ( var fs = File.Open( Path.GetFullPath( Path.Combine( Environment.GetEnvironmentVariable( "GIT_DIR" ), "Source", "Tests", "Tests.NuGetUtils.Lib.Common", "Tests.NuGetUtils.Lib.Common.csproj" ) ), FileMode.Open, FileAccess.Read, FileShare.Read ) )
            //{
            //   csProj = await XDocument.LoadAsync( fs, LoadOptions.None, default );
            //}

            //var csProjFW = NuGetFramework.ParseFolder( csProj.XPathSelectElement( "/Project/PropertyGroup/TargetFramework" ).Value );

            Assert.AreEqual(specifiedFW, autoDetectedFW, "CSProj and process frameworks must match.");
        }
Example #3
0
        private static IEnumerable <String> GetSuitableFiles(
            NuGetFramework thisFramework,
            Lazy <RuntimeGraph> runtimeGraph,
            String runtimeIdentifier,
            LockFileTargetLibrary targetLibrary,
            Lazy <IDictionary <String, LockFileLibrary> > libraries
            )
        {
            var retVal = NuGetUtility.GetRuntimeAssembliesDelegate(runtimeGraph, runtimeIdentifier, targetLibrary, libraries);

            if (!retVal.Any() && libraries.Value.TryGetValue(targetLibrary.Name, out var lib))
            {
                // targetLibrary does not list stuff like build/net45/someassembly.dll
                // So let's do manual matching
                var fwGroups = lib.Files.Where(f =>
                {
                    return(f.StartsWith(PackagingConstants.Folders.Build, StringComparison.OrdinalIgnoreCase) &&
                           PackageHelper.IsAssembly(f) &&
                           Path.GetDirectoryName(f).Length > PackagingConstants.Folders.Build.Length + 1);
                }).GroupBy(f =>
                {
                    try
                    {
                        return(NuGetFramework.ParseFolder(f.Split('/')[1]));
                    }
                    catch
                    {
                        return(null);
                    }
                })
                               .Where(g => g.Key != null)
                               .Select(g => new FrameworkSpecificGroup(g.Key, g));

                var matchingGroup = NuGetFrameworkUtility.GetNearest(
                    fwGroups,
                    thisFramework,
                    g => g.TargetFramework);
                retVal = matchingGroup?.Items;
            }

            return(retVal);
        }
Example #4
0
        public void RuntimeGraphRoundTrips()
        {
            string file = $"{nameof(RuntimeGraphRoundTrips)}.json";

            if (File.Exists(file))
            {
                File.Delete(file);
            }

            RuntimeGraph runtimeGraph = new RuntimeGraph(new[] { new RuntimeDescription("RID") });

            // Issue: https://github.com/NuGet/Home/issues/9532
            // When this is fixed, this test should fail. Fix it by deleting the NuGetUtility.WriteRuntimeGraph
            // method and replacing with JsonRuntimeFormat.WriteRuntimeGraph.
            NuGetUtility.WriteRuntimeGraph(file, runtimeGraph);

            File.Exists(file).Should().BeTrue();

            RuntimeGraph readRuntimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(file);

            readRuntimeGraph.Should().NotBeNull();
            readRuntimeGraph.Should().Be(runtimeGraph);
        }
Example #5
0
 private Task BrowseUpload(IOwinContext context, string hash, string path)
 {
     return(this.BrowseImpl(context, NuGetUtility.GetUploadedPackage(hash), path));
 }
        public override async Task Invoke(IOwinContext context)
        {
            var httpContent = new StreamContent(context.Request.Body);

            foreach (var kvp in context.Request.Headers)
            {
                httpContent.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value);
            }

            if (!httpContent.IsMimeMultipartContent("form-data"))
            {
                await context.Response.Error(415, new ErrorModel(
                                                 "Unsupported Media Type",
                                                 "You must upload nupkgs with multipart/form-data."
                                                 )).ConfigureAwait(false);

                return;
            }

            var provider = await httpContent
                           .ReadAsMultipartAsync(new MultipartFormDataStreamProvider(Path.GetTempPath()))
                           .ConfigureAwait(false);

            var formData = provider.FormData;

            var hash   = formData["hash"];
            var method = formData["method"];

            if (method == null)
            {
                await context.Response.Error(400, new ErrorModel(
                                                 "Bad Request",
                                                 "\"method\" parameter is required."
                                                 )).ConfigureAwait(false);

                return;
            }

            var file = provider.FileData
                       .FirstOrDefault(f => f.Headers.ContentDisposition.Name.Trim('"') == "file");

            if (file != null && new FileInfo(file.LocalFileName).Length > 0)
            {
                hash = await NuGetUtility.ExtractUploadedFile(file).ConfigureAwait(false);
            }
            else if (string.IsNullOrEmpty(hash))
            {
                await context.Response.Error(400, new ErrorModel(
                                                 "Bad Request",
                                                 "\"file\" parameter is required."
                                                 )).ConfigureAwait(false);

                return;
            }

            var baseUriEnv = Environment.GetEnvironmentVariable("NUGETCALC_BASEURI");
            var baseUri    = baseUriEnv != null
                ? new Uri(new Uri(baseUriEnv), context.Request.Path.Value)
                : context.Request.Uri;
            var redirectUri = new UriBuilder(new Uri(baseUri, method));

            redirectUri.Query = string.Join("&",
                                            Enumerable.Range(0, formData.Count)
                                            .Select(i => Tuple.Create(formData.GetKey(i), formData.Get(i)))
                                            .Where(t => t.Item1 != "method" && t.Item1 != "hash" && !string.IsNullOrEmpty(t.Item2))
                                            .Concat(new[] { Tuple.Create("hash", hash) })
                                            .Select(t => string.Concat(Uri.EscapeDataString(t.Item1), "=", Uri.EscapeDataString(t.Item2)))
                                            );

            context.Response.StatusCode = 303;
            context.Response.Headers.Set("Location", redirectUri.ToString());
        }
Example #7
0
        public override async Task Invoke(IOwinContext context)
        {
            if (context.RespondNotModified())
            {
                return;
            }

            var q               = context.Request.Query;
            var hash            = q["hash"];
            var source          = q["source"];
            var packageId       = q["packageId"];
            var version         = q["version"];
            var targetFramework = q["targetFramework"];

            var model = new CompatibilityModel
            {
                PackageSelector = new PackageSelectorModel
                {
                    DefaultSource          = source,
                    DefaultPackageId       = packageId,
                    DefaultVersion         = version,
                    DefaultTargetFramework = targetFramework
                }
            };
            var statusCode = 200;

            try
            {
                PackageFolderReader package;

                if (string.IsNullOrEmpty(hash))
                {
                    if (string.IsNullOrWhiteSpace(packageId))
                    {
                        // Homepage of NuGetCalc Online
                        await context.Response.View(new Views.CompatibilityStatic(), model.PackageSelector).ConfigureAwait(false);

                        return;
                    }
                    if (string.IsNullOrWhiteSpace(targetFramework))
                    {
                        statusCode  = 400;
                        model.Error = "Target Framework is required.";
                        goto RESPOND;
                    }

                    NuGetVersion nugetVersion = null;
                    if (!string.IsNullOrWhiteSpace(version) && !NuGetVersion.TryParse(version, out nugetVersion))
                    {
                        statusCode  = 400;
                        model.Error = "Version is not valid as NuGetVersion.";
                        goto RESPOND;
                    }

                    var packageDir = NuGetUtility.GetPackage(source, packageId, nugetVersion).Result; // avoid compile error on mono
                    package = new PackageFolderReader(packageDir);
                }
                else
                {
                    package = new PackageFolderReader(NuGetUtility.GetUploadedPackage(hash));
                    model.PackageSelector.UploadHash      = hash;
                    model.PackageSelector.UploadedPackage = package.GetIdentity();
                }

                using (package)
                {
                    context.Request.CallCancelled.ThrowIfCancellationRequested();

                    var identity = package.GetIdentity();
                    model.PackageSelector.DefaultPackageId = identity.Id;
                    model.PackageSelector.DefaultVersion   = identity.Version.ToString();
                    // NuGetFramework.Parse will throw only ArgumentNullException
                    var nugetFramework = NuGetFramework.Parse(targetFramework);

                    var referenceItems = NuGetUtility.FindMostCompatibleReferenceGroup(package, nugetFramework);
                    if (referenceItems != null)
                    {
                        model.ReferenceAssemblies = referenceItems.Items;
                    }

                    var depenencyItems = NuGetUtility.FindMostCompatibleDependencyGroup(package, nugetFramework);
                    if (depenencyItems != null)
                    {
                        model.Dependencies = depenencyItems.Packages;
                    }
                }

                GC.Collect(); // to release a handle of nuspec file
            }
            catch (NuGetUtilityException ex)
            {
                statusCode  = 500;
                model.Error = ex.Message;
                if (ex.InnerException != null)
                {
                    model.Exception = ex.InnerException;
                }
            }

RESPOND:
            context.Response.StatusCode = statusCode;
            await context.Response.View(new Views.Compatibility(), model).ConfigureAwait(false);
        }
Example #8
0
        public static async Task Execute(
            Input input,
            Func <String> projectFileGetter,
            CancellationToken token
            )
        {
            var packageFilePath = input.PackageFilePath;

            if (!packageFilePath.IsNullOrEmpty())
            {
                var sourceNames = input.SourceNames;
                if (!sourceNames.IsNullOrEmpty())
                {
                    var settings = NuGetUtility.GetNuGetSettingsWithDefaultRootDirectory(
                        Path.GetDirectoryName(projectFileGetter()),
                        input.NuGetConfigurationFilePath);
                    var psp         = new PackageSourceProvider(settings);
                    var packagePath = Path.GetFullPath(packageFilePath);

                    var identity = new AsyncLazy <PackageIdentity>(async() =>
                    {
                        using (var reader = new PackageArchiveReader(packagePath))
                        {
                            return(await reader.GetIdentityAsync(token));
                        }
                    });
                    var allRepositories = new Lazy <NuGetv3LocalRepository[]>(() =>
                                                                              SettingsUtility.GetGlobalPackagesFolder(settings)
                                                                              .Singleton()
                                                                              .Concat(SettingsUtility.GetFallbackPackageFolders(settings))
                                                                              .Select(repoPath => new NuGetv3LocalRepository(repoPath))
                                                                              .ToArray()
                                                                              );

                    await Task.WhenAll(sourceNames.Select( sourceItem => PerformPushToSingleSourceAsync(
                                                               settings,
                                                               packagePath,
                                                               psp,
                                                               identity,
                                                               allRepositories,
                                                               new TextWriterLogger()
                    {
                        VerbosityLevel = input.LogLevel
                    },
                                                               sourceItem,
                                                               input.RetryTimeoutForDirectoryDeletionFail,
                                                               token
                                                               ))
                                       .ToArray()
                                       );
                }
                else
                {
                    await Console.Error.WriteLineAsync($"No sources specified for push command, please specify at least one source via \"{nameof( input.SourceNames )}\" property.");
                }
            }
            else
            {
                await Console.Error.WriteLineAsync($"No package file path specified for push command, please specify it via \"{nameof( input.PackageFilePath )}\" property.");
            }
        }
Example #9
0
        /// <summary>
        /// Creates new instance of <see cref="BoundRestoreCommandUser"/> with given parameters.
        /// </summary>
        /// <param name="nugetSettings">The settings to use.</param>
        /// <param name="thisFramework">The framework to bind to.</param>
        /// <param name="runtimeIdentifier">The runtime identifier. Will be used by <see cref="E_NuGetUtils.ExtractAssemblyPaths{TResult}(BoundRestoreCommandUser, LockFile, Func{String, IEnumerable{String}, TResult}, GetFileItemsDelegate, IEnumerable{String})"/> method.</param>
        /// <param name="runtimeGraph">Optional value indicating runtime graph information: either <see cref="global::NuGet.RuntimeModel.RuntimeGraph"/> directly, or <see cref="String"/> containing package ID of package holding <c>runtime.json</c> file, containing serialized runtime graph definition. If neither is specified, then <c>"Microsoft.NETCore.Platforms"</c> package ID used to locate <c>runtime.json</c> file, as per <see href="https://docs.microsoft.com/en-us/dotnet/core/rid-catalog">official documentation</see>.</param>
        /// <param name="nugetLogger">The logger to use in restore command.</param>
        /// <param name="sourceCacheContext">The optional <see cref="SourceCacheContext"/> to use.</param>
        /// <param name="nuspecCache">The optional <see cref="LocalPackageFileCache"/> to use.</param>
        /// <param name="clientPolicyContext">The optional <see cref="ClientPolicyContext"/> to use.</param>
        /// <param name="leaveSourceCacheOpen">Whether to leave the <paramref name="sourceCacheContext"/> open when disposing this <see cref="BoundRestoreCommandUser"/>.</param>
        /// <param name="lockFileCacheDir">The directory where to store serialized lock files returned by <see cref="RestoreIfNeeded"/>. If <c>null</c> or empty, then <paramref name="lockFileCacheEnvironmentVariableName"/> will be used. Set <paramref name="disableLockFileCacheDir"/> to true to disable caching lock files to file system.</param>
        /// <param name="lockFileCacheEnvironmentVariableName">The name of the environment variable containing the value for lock file cache directory. If <c>null</c> or empty, then environment variable reading will be skipped. If the environment variable itself is <c>null</c> or empty, then the user's home directory in conjunction with <paramref name="getDefaultLockFileCacheDir"/> will be used to deduce lock file cache directory. Set <paramref name="disableLockFileCacheDir"/> to true to disable caching lock files to file system.</param>
        /// <param name="getDefaultLockFileCacheDir">This callback will be used when <paramref name="lockFileCacheEnvironmentVariableName"/> is <c>null</c> or empty or when the named environment variable itself was <c>null</c> or empty. This callback will receive current user's home directory as parameter and should return the lock file cache directory. If <c>null</c>, then <see cref="GetDefaultLockFileDir"/> will be used. Set <paramref name="disableLockFileCacheDir"/> to true to disable caching lock files to file system.</param>
        /// <param name="disableLockFileCacheDir">This variable controls whether the results of <see cref="RestoreIfNeeded"/> will be stored to file system lock file cache directory. By default, the lock file caching is enabled. Set this parameter to <c>true</c> to completely disable caching lock files to file system.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="nugetSettings"/> is <c>null</c>.</exception>
        public BoundRestoreCommandUser(
            ISettings nugetSettings,
            NuGetFramework thisFramework = null,
            String runtimeIdentifier     = null,
            EitherOr <RuntimeGraph, String> runtimeGraph = default,
            ILogger nugetLogger = null,
            SourceCacheContext sourceCacheContext   = null,
            LocalPackageFileCache nuspecCache       = null,
            ClientPolicyContext clientPolicyContext = null,
            Boolean leaveSourceCacheOpen            = false,
            String lockFileCacheDir = null,
            String lockFileCacheEnvironmentVariableName      = DEFAULT_LOCK_FILE_CACHE_DIR_ENV_NAME,
            Func <String, String> getDefaultLockFileCacheDir = null,
            Boolean disableLockFileCacheDir = false
            )
        {
            ArgumentValidator.ValidateNotNull(nameof(nugetSettings), nugetSettings);
            this.ThisFramework = thisFramework ?? NuGetUtility.TryAutoDetectThisProcessFramework();
            if (nugetLogger == null)
            {
                nugetLogger = NullLogger.Instance;
            }

            var global    = SettingsUtility.GetGlobalPackagesFolder(nugetSettings);
            var fallbacks = SettingsUtility.GetFallbackPackageFolders(nugetSettings);

            if (sourceCacheContext == null)
            {
                leaveSourceCacheOpen = false;
            }
            var ctx = sourceCacheContext ?? new SourceCacheContext();
            var psp = new PackageSourceProvider(nugetSettings);
            var csp = new CachingSourceProvider(psp);

            this.RuntimeIdentifier          = NuGetUtility.TryAutoDetectThisProcessRuntimeIdentifier(runtimeIdentifier);
            this._cacheContext              = ctx;
            this._disposeSourceCacheContext = !leaveSourceCacheOpen;

            this.NuGetLogger             = nugetLogger;
            this._restoreCommandProvider = RestoreCommandProviders.Create(
                global,
                fallbacks,
                new PackageSourceProvider(nugetSettings).LoadPackageSources().Where(s => s.IsEnabled).Select(s => csp.CreateRepository(s)),
                ctx,
                nuspecCache ?? new LocalPackageFileCache(),
                nugetLogger
                );
            this._nugetRestoreRootDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            this._restoreTargetFW     = new TargetFrameworkInformation()
            {
                FrameworkName = this.ThisFramework
            };
            this.LocalRepositories = this._restoreCommandProvider.GlobalPackages.Singleton()
                                     .Concat(this._restoreCommandProvider.FallbackPackageFolders)
                                     .ToImmutableDictionary(r => r.RepositoryRoot, r => r);
            this.RuntimeGraph = new Lazy <RuntimeGraph>(() =>
            {
                var rGraph = runtimeGraph.GetFirstOrDefault();
                if (rGraph == null)
                {
                    var packageName = runtimeGraph.GetSecondOrDefault();
                    if (String.IsNullOrEmpty(packageName))
                    {
                        packageName = DEFAULT_RUNTIME_GRAPH_PACKAGE_ID;
                    }
                    var platformsPackagePath = this.LocalRepositories.Values
                                               .SelectMany(r => r.FindPackagesById(packageName))
                                               .OrderByDescending(p => p.Version)
                                               .FirstOrDefault()
                                               ?.ExpandedPath;
                    rGraph = String.IsNullOrEmpty(platformsPackagePath) ?
                             null :
                             JsonRuntimeFormat.ReadRuntimeGraph(Path.Combine(platformsPackagePath, global::NuGet.RuntimeModel.RuntimeGraph.RuntimeGraphFileName));
                }
                return(rGraph);
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            if (!disableLockFileCacheDir)
            {
                this.DiskCacheDirectory = lockFileCacheDir
                                          .OrIfNullOrEmpty(String.IsNullOrEmpty(lockFileCacheEnvironmentVariableName) ? null : Environment.GetEnvironmentVariable(lockFileCacheEnvironmentVariableName))
                                          .OrIfNullOrEmpty((getDefaultLockFileCacheDir ?? GetDefaultLockFileDir)(Environment.GetEnvironmentVariable(
#if NET46
                                                                                                                     Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE
#else
                                                                                                                     System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)
#endif
                  ? "USERPROFILE" : "HOME"))
                                                           )
                                          .OrIfNullOrEmpty(null);
            }
            this._allLockFiles        = new ConcurrentDictionary <ImmutableSortedSet <String>, ImmutableDictionary <ImmutableArray <NuGetVersion>, String> >();
            this._lockFileFormat      = new LockFileFormat();
            this._clientPolicyContext = clientPolicyContext ?? ClientPolicyContext.GetClientPolicy(nugetSettings, nugetLogger);
        }
Example #10
0
    private static async Task <(LockFile, String, NuGetFramework)> RestoreAndFilterOutSDKPackages(
        this NuGetDeploymentConfiguration config,
        BoundRestoreCommandUser restorer,
        CancellationToken token,
        String restoreSDKPackageID,
        String restoreSDKPackageVersion
        )
    {
        var packageID = config.PackageID;
        var lockFile  = await restorer.RestoreIfNeeded(packageID, config.PackageVersion, token);

        // TODO better error messages
        var packagePath = restorer.ResolveFullPath(
            lockFile,
            lockFile.Libraries.FirstOrDefault(l => String.Equals(l.Name, packageID, StringComparison.OrdinalIgnoreCase))?.Path
            );
        var epAssemblyPath = NuGetUtility.GetAssemblyPathFromNuGetAssemblies(
            packageID,
            lockFile
            .Targets[0]
            .GetTargetLibrary(packageID)
            .RuntimeAssemblies
            .Select(ra => Path.GetFullPath(Path.Combine(packagePath, ra.Path)))
            .ToArray(),
            config.AssemblyPath
            );

        // We might be restoring .NETStandard package against .NETCoreApp framework, so find out the actual framework the package was built against.
        // So from path "/path/to/nuget/repo/package-id/package-version/lib/target-fw/package-id.dll" we want to extract the target-fw portion.
        // packagePath variable holds everything before the 'lib', so we just need to name of the folder 1 hierarchy level down from packagePath.
        var start            = GetNextSeparatorIndex(epAssemblyPath, packagePath.Length + 1) + 1;
        var end              = GetNextSeparatorIndex(epAssemblyPath, start);
        var packageFramework = NuGetFramework.ParseFolder(epAssemblyPath.Substring(start, end - start));

        //}
        //var targetFramework = restorer.ThisFramework;
        //sdkPackageID = NuGetUtility.GetSDKPackageID( targetFramework, config.ProcessSDKFrameworkPackageID ?? sdkPackageID );
        //sdkPackageVersion = NuGetUtility.GetSDKPackageVersion( targetFramework, sdkPackageID, config.ProcessSDKFrameworkPackageVersion ?? sdkPackageVersion );

        // Warning: The code below exploits the de facto behaviour that package named "System.XYZ" will contain assembly named "System.XYZ". Should sometime in the future this change, this code will then result in possibly wrong behaviour.
        // TODO I wonder if this assumption is needed anymore with .NET Standard and .NET Core 2+?

        var packageSDKPackageID = packageFramework.GetSDKPackageID(config.PackageSDKFrameworkPackageID);
        var sdkPackages         = new HashSet <String>(StringComparer.OrdinalIgnoreCase);

        if (!String.Equals(packageSDKPackageID, restoreSDKPackageID, StringComparison.OrdinalIgnoreCase))
        {
            // Typically when package is for .NET Standard and target framework is .NET Core
            var restoreLockFile = await restorer.RestoreIfNeeded(restoreSDKPackageID, restoreSDKPackageVersion, token);

            sdkPackages.UnionWith(restoreLockFile.Targets[0].GetAllDependencies(restoreSDKPackageID.Singleton())
                                  .SelectMany(lib => lib.Name.Singleton().Concat(lib.CompileTimeAssemblies.Select(cta => Path.GetFileNameWithoutExtension(cta.Path)).FilterUnderscores()))
                                  );
        }
        sdkPackages.UnionWith(lockFile.Targets[0].GetAllDependencies(packageSDKPackageID.Singleton()).Select(lib => lib.Name));


        var packageSDKPackageVersion = packageFramework.GetSDKPackageVersion(packageSDKPackageID, config.PackageSDKFrameworkPackageVersion);
        // In addition, check all compile assemblies from sdk package (e.g. Microsoft.NETCore.App )
        // Starting from 2.0.0, all assemblies from all dependent packages are marked as compile-assemblies stored in sdk package.
        var sdkPackageContainsAllPackagesAsAssemblies = config.PackageFrameworkIsPackageBased;

        Version.TryParse(packageSDKPackageVersion, out var sdkPkgVer);
        if (sdkPackageContainsAllPackagesAsAssemblies.IsTrue() ||
            (!sdkPackageContainsAllPackagesAsAssemblies.HasValue && packageFramework.IsPackageBased) // sdkPackageID == NuGetUtility.SDK_PACKAGE_NETCORE && sdkPkgVer != null && sdkPkgVer.Major >= 2 )
            )
        {
            var sdkPackageLibraries = lockFile.Targets[0].Libraries.Where(l => l.Name == packageSDKPackageID);

            if (sdkPkgVer != null)
            {
                sdkPackageLibraries = sdkPackageLibraries.Where(l => l.Version.Version >= sdkPkgVer);
            }

            var sdkPackageLibrary = sdkPackageLibraries.FirstOrDefault();

            if (sdkPackageLibrary == null && sdkPkgVer != null)
            {
                // We need to restore the correctly versioned SDK package
                sdkPackageLibrary = (await restorer.RestoreIfNeeded(packageSDKPackageID, packageSDKPackageVersion, token)).Targets[0].GetTargetLibrary(packageSDKPackageID);
            }

            if (sdkPackageLibrary != null)
            {
                sdkPackages.UnionWith(sdkPackageLibrary.CompileTimeAssemblies.Select(cta => Path.GetFileNameWithoutExtension(cta.Path)).FilterUnderscores());
            }
        }

        // Actually -> return LockFile, but modify it so that sdk packages are removed
        var targetLibs = lockFile.Targets[0].Libraries;

        for (var i = 0; i < targetLibs.Count;)
        {
            var curLib   = targetLibs[i];
            var contains = sdkPackages.Contains(curLib.Name);
            if (contains ||
                (
                    (curLib.RuntimeAssemblies.Count <= 0 || !curLib.RuntimeAssemblies.Select(ra => ra.Path).FilterUnderscores().Any()) &&
                    curLib.RuntimeTargets.Count <= 0 &&
                    curLib.ResourceAssemblies.Count <= 0 &&
                    curLib.NativeLibraries.Count <= 0
                )
                )
            {
                targetLibs.RemoveAt(i);
                if (!contains)
                {
                    sdkPackages.Add(curLib.Name);
                }
            }
            else
            {
                ++i;
            }
        }

        var libs = lockFile.Libraries;

        for (var i = 0; i < libs.Count;)
        {
            var curLib = libs[i];
            if (sdkPackages.Contains(curLib.Name))
            {
                libs.RemoveAt(i);
            }
            else
            {
                ++i;
            }
        }

        return(lockFile, epAssemblyPath, packageFramework);
    }