public DeprecatedFrameworkModel(NuGetFramework deprecated, string migrationUrl, IReadOnlyList <string> projects) { TextBeforeLink = string.Format( CultureInfo.CurrentCulture, Strings.Text_DeprecatedFramework_DocumentLink_Before, deprecated.DotNetFrameworkName, deprecated.GetShortFolderName()); LinkText = Strings.Text_DeprecatedFramework_DocumentLink; TextAfterLink = Strings.Text_DeprecatedFramework_DocumentLink_After; ProjectListText = Strings.Text_DeprecatedFramework_ProjectList; MigrationUrl = migrationUrl; Projects = projects; }
/// <summary> /// Build a package spec in memory to execute the tool restore as if it were /// its own project. For now, we always restore for a null runtime and a single /// constant framework. /// </summary> public static PackageSpec GetSpec(string projectFilePath, string id, VersionRange versionRange, NuGetFramework framework, string packagesPath, IList <string> fallbackFolders, IList <PackageSource> sources, WarningProperties projectWideWarningProperties) { var frameworkShortFolderName = framework.GetShortFolderName(); var name = GetUniqueName(id, frameworkShortFolderName, versionRange); return(new PackageSpec() { Name = name, // make sure this package never collides with a dependency FilePath = projectFilePath, Dependencies = new List <LibraryDependency>(), TargetFrameworks = { new TargetFrameworkInformation { FrameworkName = framework, Dependencies = new List <LibraryDependency> { new LibraryDependency { LibraryRange = new LibraryRange(id, versionRange, LibraryDependencyTarget.Package) } } } }, RestoreMetadata = new ProjectRestoreMetadata() { ProjectStyle = ProjectStyle.DotnetCliTool, ProjectName = name, ProjectUniqueName = name, ProjectPath = projectFilePath, PackagesPath = packagesPath, FallbackFolders = fallbackFolders, Sources = sources, OriginalTargetFrameworks = { frameworkShortFolderName }, TargetFrameworks = { new ProjectRestoreMetadataFrameworkInfo { FrameworkName = framework, ProjectReferences ={ } } }, ProjectWideWarningProperties = projectWideWarningProperties ?? new WarningProperties() } }); }
private static List <PhysicalPackageFile> GetDefaultFiles() { return(new List <PhysicalPackageFile>() { new PhysicalPackageFile(new MemoryStream()) { TargetPath = "tools/empty.txt" }, new PhysicalPackageFile(new MemoryStream()) { TargetPath = $"lib/{TargetFramework.GetShortFolderName()}/_._" } }); }
public static IEnumerable <string> CreateArgs( [NotNull] NuGetFramework framework, [NotNull] string configuration, [CanBeNull] string buildBasePath, bool noBuild, bool verbose) => new[] { FrameworkOptionTemplate, framework.GetShortFolderName(), ConfigOptionTemplate, configuration, buildBasePath == null ? string.Empty : BuildBasePathOptionTemplate, buildBasePath ?? string.Empty, noBuild ? NoBuildOptionTemplate : string.Empty, verbose ? VerboseOptionTemplate : string.Empty };
public static string ToFriendlyName(this NuGetFramework frameworkName, bool allowRecurseProfile = true) { if (frameworkName == null) { throw new ArgumentNullException("frameworkName"); } var sb = new StringBuilder(); if (String.Equals(frameworkName.Framework, ".NETPortable", StringComparison.OrdinalIgnoreCase)) { sb.Append("Portable Class Library"); // Recursively parse the profile if (allowRecurseProfile) { sb.Append(" ("); var profiles = frameworkName.GetShortFolderName().Replace("portable-", string.Empty).Split('+'); sb.Append(String.Join(", ", profiles.Select(s => NuGetFramework.Parse(s).ToFriendlyName(allowRecurseProfile: false)))); sb.Append(")"); } } else { string version = null; if (frameworkName.Version.Build == 0) { version = frameworkName.Version.ToString(2); } else if (frameworkName.Version.Revision == 0) { version = frameworkName.Version.ToString(3); } else { version = frameworkName.Version.ToString(); } sb.AppendFormat("{0} {1}", frameworkName.Framework, version); if (!String.IsNullOrEmpty(frameworkName.Profile)) { sb.AppendFormat(" {0}", frameworkName.Profile); } } return(sb.ToString()); }
private static PackageDependencyGroup LoadDependencySet(JObject set) { var fxName = set.Value <string>(Properties.TargetFramework); NuGetFramework framework = NuGetFramework.AnyFramework; if (!String.IsNullOrEmpty(fxName)) { framework = NuGetFramework.Parse(fxName); fxName = framework.GetShortFolderName(); } return(new PackageDependencyGroup(framework, (set.Value <JArray>(Properties.Dependencies) ?? Enumerable.Empty <JToken>()).Select(obj => LoadDependency((JObject)obj)))); }
private static string[] GetNonSdkTargetFramework(IProjectFile file) { const string NonSdkTargetFramework = "TargetFrameworkVersion"; var tfms = GetTfms(file, NonSdkTargetFramework); for (var i = 0; i < tfms.Length; i++) { var version = Version.Parse(tfms[i].Trim('v', 'V')); var framework = new NuGetFramework(FrameworkConstants.FrameworkIdentifiers.Net, version); tfms[i] = framework.GetShortFolderName(); } return(tfms); }
private static string FormatFramework(NuGetFramework framework, string runtimeId) { if (string.IsNullOrEmpty(runtimeId)) { return(FormatFramework(framework)); } else { return(string.Format(CultureInfo.CurrentCulture, Strings.Log_FrameworkRIDDisplay, framework.GetShortFolderName(), framework.DotNetFrameworkName, runtimeId)); } }
public TestSetupFixture() { _buildRelativePath = Path.Combine("bin", Config, Framework.GetShortFolderName(), _Runtime); var testAssetsMgr = new TestAssetsManager(_desktopProjectsRoot); _testInstance = testAssetsMgr.CreateTestInstance("BindingRedirectSample") .WithLockFiles(); Setup(AppWithConfig, ref _appWithConfigProjectRoot, ref _appWithConfigBuildDir, ref _appWithConfigPublishDir); Setup(AppWithoutConfig, ref _appWithoutConfigProjectRoot, ref _appWithoutConfigBuildDir, ref _appWithoutConfigPublishDir); AppWithConfigBuildOutput = Path.Combine(_appWithConfigBuildDir, AppWithConfig + ".exe"); AppWithConfigPublishOutput = Path.Combine(_appWithConfigPublishDir, AppWithConfig + ".exe"); AppWithoutConfigBuildOutput = Path.Combine(_appWithoutConfigBuildDir, AppWithoutConfig + ".exe"); AppWithoutConfigPublishOutput = Path.Combine(_appWithoutConfigPublishDir, AppWithoutConfig + ".exe"); }
private static void AddFlattenedFrameworkDependency(NuGetFramework targetFramework, StringBuilder builder) { if (!SpecialFrameworks.Contains(targetFramework)) { try { builder.Append(":"); builder.Append(targetFramework?.GetShortFolderName()); } catch (FrameworkException) { // ignoring FrameworkException on purpose - we don't want the job crashing // whenever someone uploads an unsupported framework } } }
public static Stream BuildPackageStream(PackageCreationContext context) { var files = new List <PhysicalPackageFile>() { new PhysicalPackageFile(new MemoryStream()) { TargetPath = "tools/empty.txt" }, new PhysicalPackageFile(new MemoryStream()) { TargetPath = $"lib/{TargetFramework.GetShortFolderName()}/_._" } }; return(BuildPackageStreamForFiles(context, files, isSymbolsPackage: false)); }
public static string GetShortFrameworkName(this NuGetFramework frameworkName) { if (frameworkName == null || frameworkName == NuGetFramework.AnyFramework) { return(null); } if (frameworkName.Equals(new NuGetFramework(FrameworkConstants.FrameworkIdentifiers.Portable, new Version(5, 0)))) { // Avoid calling GetShortFrameworkName because NuGet throws ArgumentException // in this case. return("dotnet"); } return(frameworkName.GetShortFolderName()); }
MSBuildItem AddPackageReference(MSBuildProject project, NuGetFramework framework) { string originalFramework; if (!installationContext.OriginalFrameworks.TryGetValue(framework, out originalFramework)) { originalFramework = framework.GetShortFolderName(); } MSBuildItemGroup itemGroup = GetOrAddItemGroup(project, originalFramework); MSBuildItem packageReference = GetOrAddPackageReference(itemGroup); packageReference.Metadata.SetValue("Version", packageIdentity.Version.ToNormalizedString()); return(packageReference); }
public override string[] Locate(NuGetFramework framework) { if (_mappings == null) { _mappings = new Dictionary <string, string[]>(); var provider = new PackBasedFrameworkProvider(_frameworksPath); foreach (var(tfm, paths) in provider.Resolve()) { _mappings.Add(tfm, paths); } } var key = framework.GetShortFolderName(); _mappings.TryGetValue(key, out var mappingPaths); return(mappingPaths); }
// Creates a command to execute dotnet-aspnet-codegenerator-design private static Command CreateDipatchCommand( IProjectContext context, string[] args, string buildBasePath, string configuration, NuGetFramework frameworkToUse, ScaffoldingServer server) { var projectDirectory = Directory.GetParent(context.ProjectFullPath).FullName; // Command Resolution Args // To invoke dotnet-aspnet-codegenerator-design with the user project's dependency graph, // we need to pass in the runtime config and deps file to dotnet for netcore app projects. // For projects that target net4x, since the dotnet-aspnet-codegenerator-design.exe is in the project's bin folder // and `dotnet build` generates a binding redirect file for it, we can directly invoke the exe from output location. var targetDir = Path.GetDirectoryName(context.AssemblyFullPath); var runtimeConfigPath = Path.Combine(targetDir, context.RuntimeConfig); var depsFile = Path.Combine(targetDir, context.DepsFile); string dotnetCodeGenInsideManPath = context.CompilationAssemblies .Where(c => Path.GetFileNameWithoutExtension(c.Name) .Equals(DESIGN_TOOL_NAME, StringComparison.OrdinalIgnoreCase)) .Select(reference => reference.ResolvedPath) .FirstOrDefault(); if (string.IsNullOrEmpty(dotnetCodeGenInsideManPath)) { throw new InvalidOperationException(Resources.AddDesignPackage); } var dependencyArgs = ToolCommandLineHelper.GetProjectDependencyCommandArgs( args, frameworkToUse.GetShortFolderName(), server.Port.ToString()); return(DotnetToolDispatcher.CreateDispatchCommand( runtimeConfigPath: runtimeConfigPath, depsFile: depsFile, dependencyToolPath: dotnetCodeGenInsideManPath, dispatchArgs: dependencyArgs, framework: frameworkToUse, configuration: configuration, projectDirectory: projectDirectory, assemblyFullPath: context.AssemblyFullPath)); }
internal static BuildResult Build( string project, string configuration, NuGetFramework framework, string buildBasePath) { // TODO: Specify --runtime? var args = new List <string>() { project, "--configuration", configuration, "--framework", framework.GetShortFolderName(), }; if (buildBasePath != null) { // ProjectDependenciesCommandFactory cannot handle relative build base paths. buildBasePath = (!Path.IsPathRooted(buildBasePath)) ? Path.Combine(Directory.GetCurrentDirectory(), buildBasePath) : buildBasePath; args.Add("--build-base-path"); args.Add(buildBasePath); } var stdOutMsgs = new List <string>(); var stdErrorMsgs = new List <string>(); var command = Command.CreateDotNet( "build", args, framework, configuration) .OnErrorLine((str) => stdOutMsgs.Add(str)) .OnOutputLine((str) => stdErrorMsgs.Add(str)); var result = command.Execute(); return(new BuildResult() { Result = result, StdErr = stdErrorMsgs, StdOut = stdOutMsgs }); }
public DeprecatedFrameworkModel(NuGetFramework deprecated, string migrationUrl, IEnumerable <NuGetProject> projects) { TextBeforeLink = string.Format( CultureInfo.CurrentCulture, Resources.Text_DeprecatedFramework_DocumentLink_Before, deprecated.DotNetFrameworkName, deprecated.GetShortFolderName()); LinkText = Resources.Text_DeprecatedFramework_DocumentLink; TextAfterLink = Resources.Text_DeprecatedFramework_DocumentLink_After; ProjectListText = Resources.Text_DeprecatedFramework_ProjectList; MigrationUrl = migrationUrl; Projects = projects .Select(project => NuGetProject.GetUniqueNameOrName(project)) .OrderBy(name => name) .ToList(); }
// NuGet.Frameworks doesn't have the equivalent of the old VersionUtility.GetFrameworkString // which is relevant for building packages. This isn't needed for net5.0+ frameworks. public static string GetFrameworkString(this NuGetFramework self) { bool isNet5Era = (self.Version.Major >= 5 && StringComparer.OrdinalIgnoreCase.Equals(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, self.Framework)); if (isNet5Era) { return(self.GetShortFolderName()); } var frameworkName = new FrameworkName(self.DotNetFrameworkName); string name = frameworkName.Identifier + frameworkName.Version; if (string.IsNullOrEmpty(frameworkName.Profile)) { return(name); } return(name + "-" + frameworkName.Profile); }
public CachedPackage(PackageIdentity identity, NuGetFramework targetFramework) { PackageReference = new PackageReference(identity, targetFramework); _dependencies = new List <CachedPackage>(); // Create the element Element = new XElement(PackageElementName, new XAttribute(IdAttributeName, identity.Id), new XAttribute(VersionAttributeName, identity.Version)); if (targetFramework.IsSpecificFramework) { string frameworkShortName = targetFramework.GetShortFolderName(); if (!string.IsNullOrEmpty(frameworkShortName)) { Element.Add(new XAttribute(TargetFrameworkAttributeName, frameworkShortName)); } } }
private LockFileTargetLibrary GetToolLibraryForContext( LockFile lockFile, string commandName, NuGetFramework targetFramework) { var toolLibraries = lockFile.Targets .FirstOrDefault(t => t.TargetFramework.GetShortFolderName() .Equals(targetFramework.GetShortFolderName())) ?.Libraries.Where(l => l.Name == commandName || l.RuntimeAssemblies.Any(r => Path.GetFileNameWithoutExtension(r.Path) == commandName)).ToList(); if (toolLibraries?.Count() > 1) { throw new InvalidOperationException($"Ambiguous command name: {commandName}"); } Reporter.Verbose.WriteLine($"projectdependenciescommandresolver: tool library found {toolLibraries?.Count() > 0}"); return(toolLibraries?.FirstOrDefault()); }
public string GetLockFilePath(string packageId, NuGetVersion version, NuGetFramework framework) { if (version == null) { throw new ArgumentNullException(nameof(version)); } if (framework == null) { throw new ArgumentNullException(nameof(framework)); } return(Path.Combine( GetBaseToolPath(packageId), version.ToNormalizedString().ToLowerInvariant(), framework.GetShortFolderName(), "project.assets.json")); }
public static string ToShortNameOrNull(this NuGetFramework frameworkName) { if (frameworkName == null) { return(null); } var shortFolderName = frameworkName.GetShortFolderName(); // If the shortFolderName is "any", we want to return null to preserve NuGet.Core // compatibility in the V2 feed. if (String.Equals(shortFolderName, "any", StringComparison.OrdinalIgnoreCase)) { return(null); } return(shortFolderName); }
/// <summary> /// Возвращает информацию о файле пакета для указанного источника и фреймворка. /// </summary> /// <param name="packagePath">Путь к каталогу пакета.</param> /// <param name="sourcePath">Путь к файлу в каталоге пакетов.</param> /// <param name="sourcePart">Каталог файла пакета ('lib', 'content' и т.д.).</param> /// <param name="sourceFramework">Версия фремворка файла пакета.</param> private static PackageFile GetPackageItem(string packagePath, string sourcePath, string sourcePart, NuGetFramework sourceFramework) { // Путь файла в пакете обычно имеет вид 'lib/net45/some.dll' // или 'lib/some.dll' для NuGetFramework.AnyFramework sourcePath = sourcePath.Replace('/', Path.DirectorySeparatorChar); var installPath = sourcePath; // Определение части пути источника, которая указывает на NuGetFramework файла, // например, 'lib/net45/' или 'lib/' для NuGetFramework.AnyFramework var partFrameworkPath = sourcePart + Path.DirectorySeparatorChar; if (!Equals(sourceFramework, NuGetFramework.AnyFramework)) { partFrameworkPath += sourceFramework.GetShortFolderName() + Path.DirectorySeparatorChar; } // Определение относительного пути для установки файла, например, для источника // 'lib/net45/some.dll' путь для установки будет 'some.dll', а для источника // 'lib/net45/en-US/resources.dll' путь для установки будет 'en-US/resources.dll' if (sourcePath.StartsWith(partFrameworkPath, StringComparison.OrdinalIgnoreCase)) { installPath = sourcePath.Substring(partFrameworkPath.Length); } else if (!Equals(sourceFramework, NuGetFramework.AnyFramework)) { // Обработка нестандартных путей, например, 'lib/net45-full/log4net.dll' var index = sourcePath.IndexOf(Path.DirectorySeparatorChar, sourcePart.Length + 1); if (index >= 0) { installPath = sourcePath.Substring(index + 1); } } return(new PackageFile(Path.Combine(packagePath, sourcePath), installPath)); }
private static HashSet <string> GetMatchingFrameworkStrings(PackageSpec spec, NuGetFramework framework) { // Ignore case since msbuild does var matches = new HashSet <string>(StringComparer.OrdinalIgnoreCase); if (spec.RestoreMetadata != null) { matches.UnionWith(spec.RestoreMetadata.OriginalTargetFrameworks .Where(s => framework.Equals(NuGetFramework.Parse(s)))); } // If there were no matches, use the generated name if (matches.Count < 1) { matches.Add(framework.GetShortFolderName()); } return(matches); }
public async Task <GraphNode <RemoteResolveResult> > ResolvePackages(List <PackageId> packages) { var walkerContext = new RemoteWalkContext(_cache, _nuGetLogger); foreach (var sourceRepository in _repositoryProvider.Repositories) { var provider = new SourceRepositoryDependencyProvider(sourceRepository, _nuGetLogger, _cache, true, true); walkerContext.RemoteLibraryProviders.Add(provider); } walkerContext.ProjectLibraryProviders.Add(new ProjectLibraryProvider(packages)); var localProvider = new SourceRepositoryDependencyProvider(_localRepository, _nuGetLogger, _cache, true, true); walkerContext.LocalLibraryProviders.Add(localProvider); var fakeLib = new LibraryRange("Dropcraft", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Project); var walker = new RemoteDependencyWalker(walkerContext); return(await walker.WalkAsync(fakeLib, _framework, _framework.GetShortFolderName(), RuntimeGraph.Empty, true)); }
/// <summary> /// Given a package id, version and framework, returns the tool directory path where the assets/cache file are located for tools /// </summary> public string GetToolDirectoryPath(string packageId, NuGetVersion version, NuGetFramework framework) { var versionString = version.ToNormalizedString(); var frameworkString = framework.GetShortFolderName(); if (_isLowercase) { packageId = packageId.ToLowerInvariant(); versionString = versionString.ToLowerInvariant(); frameworkString = frameworkString.ToLowerInvariant(); } var basePath = GetPackagesToolsBasePath(); return(Path.Combine( basePath, packageId, versionString, frameworkString)); }
void Run() { // Json.NET 9.0.1 var frameworks = new [] { "net20", "net35", "net40", "net45", "netstandard1.0", "portable-net40+sl5+wp80+win8+wpa81", "portable-net45+wp80+win8+wpa81" }; // Json.NET 10.0.2 var frameworks2 = new [] { "net20", "net35", "net40", "net45", "netstandard1.0", "netstandard1.3", "portable-net40+sl5+wp80+win8+wpa81", "portable-net45+wp80+win8+wpa81" }; var frameworks3 = new [] { "portable-net45+win8", "netstandard1.1", }; NuGetFramework nearest = GetNearestFramework("xamarinios10", frameworks3); if (nearest != null) { Console.WriteLine("Nearest framework: {0}", nearest.GetShortFolderName()); } else { Console.WriteLine("No nearest framework."); } }
private CommandSpec ResolveCommandSpecFromToolLibrary( SingleProjectInfo toolLibraryRange, string commandName, IEnumerable <string> args, LockFile lockFile, IProject project) { var nugetPackagesRoot = lockFile.PackageFolders.First().Path; var toolLockFile = GetToolLockFile(toolLibraryRange, nugetPackagesRoot); var toolLibrary = toolLockFile.Targets .FirstOrDefault( t => t.TargetFramework.GetShortFolderName().Equals(s_toolPackageFramework.GetShortFolderName())) ?.Libraries.FirstOrDefault(l => l.Name == toolLibraryRange.Name); if (toolLibrary == null) { return(null); } var depsFileRoot = Path.GetDirectoryName(toolLockFile.Path); var depsFilePath = GetToolDepsFilePath(toolLibraryRange, toolLockFile, depsFileRoot); var normalizedNugetPackagesRoot = PathUtility.EnsureNoTrailingDirectorySeparator(nugetPackagesRoot); var commandSpec = _packagedCommandSpecFactory.CreateCommandSpecFromLibrary( toolLibrary, commandName, args, _allowedCommandExtensions, normalizedNugetPackagesRoot, s_commandResolutionStrategy, depsFilePath, null); commandSpec?.AddEnvironmentVariablesFromProject(project); return(commandSpec); }
private IReadOnlyDictionary <string, string> GetProjectMetadata(string filePath, NuGetFramework framework, string configuration, string outputDir) { var metadataFile = Path.GetTempFileName(); try { var args = new List <string> { "/t:_EFGetProjectMetadata", "/p:Configuration=" + configuration, "/p:_EFProjectMetadataFile=" + metadataFile }; if (outputDir != null) { args.Add("/p:OutputPath=" + outputDir); } if (framework != null) { args.Add("/p:TargetFramework=" + framework.GetShortFolderName()); } var command = Command.CreateDotNet("msbuild", args); var result = command.Execute(); if (result.ExitCode != 0) { throw new OperationErrorException( $"Couldn't read metadata for project '{filePath}'. Ensure the package 'Microsoft.EntityFrameworkCore.Tools' is installed."); } return(File.ReadLines(metadataFile).Select(l => l.Split(new[] { ':' }, 2)) .ToDictionary(s => s[0], s => s[1].TrimStart())); } finally { File.Delete(metadataFile); } }
private static string[] GetNonSdkTargetFramework(IProjectFile file) { var nugetTargetFramework = file.GetPropertyValue("NuGetTargetFramework"); if (nugetTargetFramework is not null && IsUAPProject(nugetTargetFramework)) { return(new string[] { GetUAPTargetFramework(nugetTargetFramework) }); } const string NonSdkTargetFramework = "TargetFrameworkVersion"; var tfms = GetTfms(file, NonSdkTargetFramework); for (var i = 0; i < tfms.Length; i++) { var version = Version.Parse(tfms[i].Trim('v', 'V')); var framework = new NuGetFramework(FrameworkConstants.FrameworkIdentifiers.Net, version); tfms[i] = framework.GetShortFolderName(); } return(tfms); }