private void PrintLocalResourcePath(string resourceName, string path) { if (string.IsNullOrWhiteSpace(path)) { Console.WriteWarning( LocalizedResourceManager.GetString( nameof(NuGetResources.LocalsCommand_LocalResourcePathNotSet)), resourceName); } else { Console.WriteLine($"{resourceName}: {path}"); } }
private void BuildProject() { if (Build) { if (TargetFramework != null) { Logger.Log( MessageLevel.Info, LocalizedResourceManager.GetString("BuildingProjectTargetingFramework"), _project.FullPath, TargetFramework); } using (var projectCollection = new ProjectCollection(ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile)) { BuildRequestData requestData = new BuildRequestData(_project.FullPath, ProjectProperties, _project.ToolsVersion, new string[0], null); var parameters = new BuildParameters(projectCollection) { Loggers = new[] { new ConsoleLogger { Verbosity = LoggerVerbosity.Quiet } }, NodeExeLocation = typeof(ProjectFactory).Assembly.Location, ToolsetDefinitionLocations = projectCollection.ToolsetLocations }; BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, requestData); // Build the project so that the outputs are created if (result.OverallResult == BuildResultCode.Failure) { // If the build fails, report the error throw new CommandLineException(LocalizedResourceManager.GetString("FailedToBuildProject"), Path.GetFileName(_project.FullPath)); } TargetPath = ResolveTargetPath(result); } } else { // If BaseTargetPath property is provided, then use its value for resolving the TargetPath // BaseTargetPath property only makes sense when Build==false. TargetPath = !string.IsNullOrWhiteSpace(BaseTargetPath) ? ResolveTargetPathByBaseTargetPath() : ResolveTargetPath(); // Make if the target path doesn't exist, fail if (!File.Exists(TargetPath)) { throw new CommandLineException(LocalizedResourceManager.GetString("UnableToFindBuildOutput"), TargetPath); } } }
private HashSet <PackageReference> GetInstalledPackageReferencesFromSolutionFile(string solutionFileFullPath) { ISolutionParser solutionParser; if (EnvironmentUtility.IsMonoRuntime) { solutionParser = new XBuildSolutionParser(); } else { solutionParser = new MSBuildSolutionParser(); } var installedPackageReferences = new HashSet <PackageReference>(new PackageReferenceComparer()); IEnumerable <string> projectFiles = Enumerable.Empty <string>(); try { projectFiles = solutionParser.GetAllProjectFileNames(solutionFileFullPath); } catch (System.Reflection.TargetInvocationException ex) { //if (ex.InnerException is InvalidProjectFileException) //{ // return GetPackageReferencesInDirectory(Path.GetDirectoryName(solutionFileFullPath)); //} throw; } foreach (var projectFile in projectFiles) { if (!File.Exists(projectFile)) { Console.WriteWarning(LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"), projectFile); continue; } string projectConfigFilePath = Path.Combine( Path.GetDirectoryName(projectFile), Constants.PackageReferenceFile); string projectName = Path.GetFileNameWithoutExtension(projectFile); CommandLineHelper.AddRange(installedPackageReferences, GetInstalledPackageReferences(projectConfigFilePath)); } return(installedPackageReferences); }
private async Task <IList <KeyValuePair <Configuration.PackageSource, string> > > GetListEndpointsAsync() { var configurationSources = SourceProvider.LoadPackageSources() .Where(p => p.IsEnabled) .ToList(); IList <Configuration.PackageSource> packageSources; if (Source.Count > 0) { packageSources = Source .Select(s => Common.PackageSourceProviderExtensions.ResolveSource(configurationSources, s)) .ToList(); } else { packageSources = configurationSources; } var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider); var listCommandResourceTasks = packageSources .Select(source => { var sourceRepository = sourceRepositoryProvider.CreateRepository(source); return(sourceRepository.GetResourceAsync <ListCommandResource>()); }) .ToList(); var listCommandResources = await Task.WhenAll(listCommandResourceTasks); var listEndpoints = packageSources.Zip( listCommandResources, (p, l) => new KeyValuePair <Configuration.PackageSource, string>(p, l?.GetListEndpoint())); var partitioned = listEndpoints.ToLookup(kv => kv.Value != null); foreach (var packageSource in partitioned[key: false].Select(kv => kv.Key)) { var message = string.Format( LocalizedResourceManager.GetString("ListCommand_ListNotSupported"), packageSource.Source); Console.LogWarning(message); } return(partitioned[key : true].ToList()); }
private IPackage BuildFromProjectFile(string path) { var factory = new ProjectFactory(path, Properties) { IsTool = Tool, Logger = Console, Build = Build, IncludeReferencedProjects = IncludeReferencedProjects }; // Add the additional Properties to the properties of the Project Factory foreach (var property in Properties) { if (factory.ProjectProperties.ContainsKey(property.Key)) { Console.WriteWarning(LocalizedResourceManager.GetString("Warning_DuplicatePropertyKey"), property.Key); } factory.ProjectProperties[property.Key] = property.Value; } // Create a builder for the main package as well as the sources/symbols package PackageBuilder mainPackageBuilder = factory.CreateBuilder(BasePath); // Build the main package IPackage package = BuildPackage(mainPackageBuilder); // If we're excluding symbols then do nothing else if (!Symbols) { return(package); } Console.WriteLine(); Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildSymbolsPackage"), Path.GetFileName(path)); factory.IncludeSymbols = true; PackageBuilder symbolsBuilder = factory.CreateBuilder(BasePath); symbolsBuilder.Version = mainPackageBuilder.Version; // Get the file name for the sources package and build it string outputPath = GetOutputPath(symbolsBuilder, symbols: true); BuildPackage(symbolsBuilder, outputPath); // this is the real package, not the symbol package return(package); }
private void BuildPackage(PackageBuilder builder, bool analyzePackage, string outputPath = null) { if (!String.IsNullOrEmpty(Version)) { builder.Version = new SemanticVersion(Version); } if (_minClientVersionValue != null) { builder.MinClientVersion = _minClientVersionValue; } outputPath = outputPath ?? GetOutputPath(builder); ExcludeFiles(builder.Files); // Track if the package file was already present on disk bool isExistingPackage = File.Exists(outputPath); try { using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } } catch { if (!isExistingPackage && File.Exists(outputPath)) { File.Delete(outputPath); } throw; } if (Verbosity == Verbosity.Detailed) { PrintVerbose(outputPath); } var package = new OptimizedZipPackage(outputPath); if (analyzePackage) { AnalyzePackage(package); } Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandSuccess"), outputPath); }
private void UpdateAllPackages(string solutionDir) { Console.WriteLine(LocalizedResourceManager.GetString("ScanningForProjects")); // Search recursively for all packages.xxx.config files string[] packagesConfigFiles = Directory.GetFiles( solutionDir, "*.config", SearchOption.AllDirectories); var projects = packagesConfigFiles.Where(s => Path.GetFileName(s).StartsWith("packages.", StringComparison.OrdinalIgnoreCase)) .Select(GetProject) .Where(p => p != null) .Distinct() .ToList(); if (projects.Count == 0) { Console.WriteLine(LocalizedResourceManager.GetString("NoProjectsFound")); return; } if (projects.Count == 1) { Console.WriteLine(LocalizedResourceManager.GetString("FoundProject"), projects.Single().ProjectName); } else { Console.WriteLine(LocalizedResourceManager.GetString("FoundProjects"), projects.Count, String.Join(", ", projects.Select(p => p.ProjectName))); } string repositoryPath = GetRepositoryPathFromSolution(solutionDir); IPackageRepository sourceRepository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source); foreach (var project in projects) { try { UpdatePackages(project, repositoryPath, sourceRepository); if (Verbose) { Console.WriteLine(); } } catch (Exception e) { Console.WriteWarning(e.Message); } } }
public override void ExecuteCommand() { if (SourceProvider == null) { throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_SourceProviderIsNull")); } if (Settings == null) { throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_SettingsIsNull")); } //Frist argument should be the ApiKey string apiKey = Arguments[0]; bool setSymbolServerKey = false; //If the user passed a source use it for the gallery location string source; if (String.IsNullOrEmpty(Source)) { source = NuGetConstants.DefaultGalleryServerUrl; // If no source was specified, set the default symbol server key to be the same setSymbolServerKey = true; } else { source = SourceProvider.ResolveAndValidateSource(Source); } Settings.SetEncryptedValue(CommandLineUtility.ApiKeysSectionName, source, apiKey); string sourceName = CommandLineUtility.GetSourceDisplayName(source); // Setup the symbol server key if (setSymbolServerKey) { Settings.SetEncryptedValue(CommandLineUtility.ApiKeysSectionName, NuGetConstants.DefaultSymbolServerUrl, apiKey); Console.WriteLine(LocalizedResourceManager.GetString("SetApiKeyCommandDefaultApiKeysSaved"), apiKey, sourceName, CommandLineUtility.GetSourceDisplayName(NuGetConstants.DefaultSymbolServerUrl)); } else { Console.WriteLine(LocalizedResourceManager.GetString("SetApiKeyCommandApiKeySaved"), apiKey, sourceName); } }
private void AddFileToBuilder(PackageBuilder builder, PhysicalPackageFile packageFile) { if (!builder.Files.Any(p => packageFile.Path.Equals(p.Path, StringComparison.OrdinalIgnoreCase))) { WriteDetail(LocalizedResourceManager.GetString("AddFileToPackage"), packageFile.SourcePath, packageFile.TargetPath); builder.Files.Add(packageFile); } else { _logger.Log( MessageLevel.Warning, LocalizedResourceManager.GetString("FileNotAddedToPackage"), packageFile.SourcePath, packageFile.TargetPath); } }
/// <summary> /// Clears the NuGet v3 HTTP cache. /// </summary> /// <returns><code>True</code> if the operation was successful; otherwise <code>false</code>.</returns> private bool ClearNuGetHttpCache() { var success = true; var httpCacheFolderPath = SettingsUtility.GetHttpCacheFolder(); if (!string.IsNullOrEmpty(httpCacheFolderPath)) { Console.WriteLine( LocalizedResourceManager.GetString(nameof(NuGetResources.LocalsCommand_ClearingNuGetHttpCache)), httpCacheFolderPath); success &= ClearCacheDirectory(httpCacheFolderPath); } return(success); }
private void PushPackageCore(string source, string apiKey, PackageServer packageServer, string packageToPush, TimeSpan timeout) { // Push the package to the server var package = new OptimizedZipPackage(packageToPush); string sourceName = CommandLineUtility.GetSourceDisplayName(source); Console.WriteLine(LocalizedResourceManager.GetString("PushCommandPushingPackage"), package.GetFullName(), sourceName); packageServer.PushPackage( apiKey, package, new FileInfo(packageToPush).Length, Convert.ToInt32(timeout.TotalMilliseconds)); Console.WriteLine(LocalizedResourceManager.GetString("PushCommandPackagePushed")); }
private void ClearLocalResource(LocalResourceName localResourceName) { var success = true; switch (localResourceName) { case LocalResourceName.HttpCache: success &= ClearNuGetHttpCache(); break; case LocalResourceName.PackagesCache: success &= ClearNuGetPackagesCache(); break; case LocalResourceName.GlobalPackagesFolder: success &= ClearNuGetGlobalPackagesFolder(); break; case LocalResourceName.Temp: success &= ClearNuGetTempFolder(); break; case LocalResourceName.All: success &= ClearNuGetHttpCache(); success &= ClearNuGetPackagesCache(); success &= ClearNuGetGlobalPackagesFolder(); success &= ClearNuGetTempFolder(); break; default: // Invalid local resource name provided. throw new CommandLineException( LocalizedResourceManager.GetString( nameof(NuGetResources.LocalsCommand_InvalidLocalResourceName))); } if (!success) { throw new CommandLineException( LocalizedResourceManager.GetString(nameof(NuGetResources.LocalsCommand_ClearFailed))); } else { Console.WriteLine( LocalizedResourceManager.GetString(nameof(NuGetResources.LocalsCommand_ClearedSuccessful))); } }
internal void AnalyzePackage(IPackage package) { var packageRules = new List <IPackageRule>(); foreach (var rule in Rules) { // Convert the aggregate DefaultPackageRules into a set of individual rules to allow for filtering. // We cannot modify the DefaultPackageRules.Rules since it may be used by extensions, such as the "analyze" one. if (rule is DefaultPackageRules) { packageRules.AddRange(DefaultPackageRules.RuleSet); } else { packageRules.Add(rule); } } if (!String.IsNullOrEmpty(package.Version.SpecialVersion)) { // If a package contains a special token, we'll warn users if it does not strictly follow semver guidelines. packageRules.Add(new StrictSemanticVersionValidationRule()); } if (!String.IsNullOrWhiteSpace(DisableRules)) { var disabledRulesList = DisableRules.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries); packageRules.RemoveAll(rule => disabledRulesList.Any(disabled => string.Equals(rule.GetType().Name, disabled, StringComparison.OrdinalIgnoreCase))); } if (Verbosity == Verbosity.Detailed) { Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandEnabledRules"), string.Join(";", packageRules.Select(rule => rule.GetType().Name))); } IList <PackageIssue> issues = package.Validate(packageRules).OrderBy(p => p.Title, StringComparer.CurrentCulture).ToList(); if (issues.Count > 0) { Console.WriteLine(); Console.WriteWarning(LocalizedResourceManager.GetString("PackageCommandPackageIssueSummary"), issues.Count, package.Id); foreach (var issue in issues) { PrintPackageIssue(issue); } } }
private void AddNewSource() { if (String.IsNullOrEmpty(Name)) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNameRequired")); } if (String.Equals(Name, LocalizedResourceManager.GetString("ReservedPackageNameAll"))) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandAllNameIsReserved")); } if (String.IsNullOrEmpty(Source)) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandSourceRequired")); } // Make sure that the Source given is a valid one. if (!PathValidator.IsValidSource(Source)) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandInvalidSource")); } ValidateCredentials(); // Check to see if we already have a registered source with the same name or source var sourceList = SourceProvider.LoadPackageSources().ToList(); bool hasName = sourceList.Any(ps => String.Equals(Name, ps.Name, StringComparison.OrdinalIgnoreCase)); if (hasName) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandUniqueName")); } bool hasSource = sourceList.Any(ps => String.Equals(Source, ps.Source, StringComparison.OrdinalIgnoreCase)); if (hasSource) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandUniqueSource")); } var newPackageSource = new PackageSource(Source, Name) { UserName = UserName, Password = Password, IsPasswordClearText = StorePasswordInClearText }; sourceList.Add(newPackageSource); SourceProvider.SavePackageSources(sourceList); Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandSourceAddedSuccessfully"), Name); }
private static void EnsurePackageRestoreConsent(XmlDocument document) { // Addressing this later. var node = document != null?document.SelectSingleNode(@"configuration/packageRestore/add[@key='enabled']/@value") : null; var settingsValue = node != null?node.Value.Trim() : ""; var envValue = (Environment.GetEnvironmentVariable("EnableNuGetPackageRestore") ?? String.Empty).Trim(); bool consent = settingsValue.Equals("true", StringComparison.OrdinalIgnoreCase) || settingsValue == "1" || envValue.Equals("true", StringComparison.OrdinalIgnoreCase) || envValue == "1"; if (!consent) { throw new InvalidOperationException(LocalizedResourceManager.GetString("RestoreConsent")); } }
public override void ExecuteCommand() { if (NoPrompt) { Console.WriteWarning(LocalizedResourceManager.GetString("Warning_NoPromptDeprecated")); NonInteractive = true; } //First argument should be the package ID string packageId = Arguments[0]; //Second argument should be the package Version string packageVersion = Arguments[1]; //If the user passed a source use it for the gallery location string source = SourceProvider.ResolveAndValidateSource(Source) ?? NuGetConstants.DefaultGalleryServerUrl; var gallery = new PackageServer(source, CommandLineConstants.UserAgent); gallery.SendingRequest += (sender, e) => { if (Console.Verbosity == NuGet.Verbosity.Detailed) { Console.WriteLine(ConsoleColor.Green, "{0} {1}", e.Request.Method, e.Request.RequestUri); } }; //If the user did not pass an API Key look in the config file string apiKey = GetApiKey(source); string sourceDisplayName = CommandLineUtility.GetSourceDisplayName(source); if (String.IsNullOrEmpty(apiKey)) { Console.WriteWarning(LocalizedResourceManager.GetString("NoApiKeyFound"), sourceDisplayName); } if (NonInteractive || Console.Confirm(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("DeleteCommandConfirm"), packageId, packageVersion, sourceDisplayName))) { Console.WriteLine(LocalizedResourceManager.GetString("DeleteCommandDeletingPackage"), packageId, packageVersion, sourceDisplayName); gallery.DeletePackage(apiKey, packageId, packageVersion); Console.WriteLine(LocalizedResourceManager.GetString("DeleteCommandDeletedPackage"), packageId, packageVersion); } else { Console.WriteLine(LocalizedResourceManager.GetString("DeleteCommandCanceled")); } }
public override void ExecuteCommand() { if (SourceProvider == null) { throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_SourceProviderIsNull")); } // Convert to update var action = Arguments.FirstOrDefault(); // TODO: Change these in to switches so we don't have to parse them here. if (String.IsNullOrEmpty(action) || action.Equals("List", StringComparison.OrdinalIgnoreCase)) { switch (Format) { case SourcesListFormat.Short: PrintRegisteredSourcesShort(); break; default: PrintRegisteredSourcesDetailed(); break; } } else if (action.Equals("Add", StringComparison.OrdinalIgnoreCase)) { AddNewSource(); } else if (action.Equals("Remove", StringComparison.OrdinalIgnoreCase)) { RemoveSource(); } else if (action.Equals("Enable", StringComparison.OrdinalIgnoreCase)) { EnableOrDisableSource(enabled: true); } else if (action.Equals("Disable", StringComparison.OrdinalIgnoreCase)) { EnableOrDisableSource(enabled: false); } else if (action.Equals("Update", StringComparison.OrdinalIgnoreCase)) { UpdatePackageSource(); } }
static IMSBuildProjectSystem GetMSBuildProject(string packageReferenceFilePath) { // Try to locate the project file associated with this packages.config file var directory = Path.GetDirectoryName(packageReferenceFilePath); var projectFiles = ProjectHelper.GetProjectFiles(directory).Take(2).ToArray(); if (projectFiles.Length == 0) { throw new CommandLineException(LocalizedResourceManager.GetString("UnableToLocateProjectFile"), packageReferenceFilePath); } if (projectFiles.Length > 1) { throw new CommandLineException(LocalizedResourceManager.GetString("MultipleProjectFilesFound"), packageReferenceFilePath); } return(new MSBuildProjectSystem(projectFiles[0])); }
private void InstallPackagesFromConfigFile(IFileSystem fileSystem, PackageReferenceFile configFile) { // display opt-out message if needed if (Console != null && RequireConsent && new PackageRestoreConsent(Settings).IsGranted) { string message = LocalizedResourceManager.RestoreCommandPackageRestoreOptOutMessage; Console.WriteLine(message); } var packageReferences = CommandLineUtility.GetPackageReferences(configFile, requireVersion: true); bool installedAny = ExecuteInParallel(fileSystem, packageReferences); if (!installedAny && packageReferences.Any()) { Console.WriteLine(LocalizedResourceManager.GetString("InstallCommandNothingToInstall"), Constants.PackageReferenceFile); } }
private void UpdatePackages(IMSBuildProjectSystem projectSystem, string repositoryPath = null, IPackageRepository sourceRepository = null) { // Resolve the repository path repositoryPath = repositoryPath ?? GetRepositoryPath(projectSystem.Root); var sharedRepositoryFileSystem = new PhysicalFileSystem(repositoryPath); var pathResolver = new DefaultPackagePathResolver(sharedRepositoryFileSystem); // Create the local and source repositories var sharedPackageRepository = new SharedPackageRepository(pathResolver, sharedRepositoryFileSystem, sharedRepositoryFileSystem); var localRepository = new PackageReferenceRepository(projectSystem, projectSystem.ProjectName, sharedPackageRepository); sourceRepository = sourceRepository ?? AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source); Console.WriteLine(LocalizedResourceManager.GetString("UpdatingProject"), projectSystem.ProjectName); UpdatePackages(localRepository, sharedRepositoryFileSystem, sharedPackageRepository, sourceRepository, localRepository, pathResolver, projectSystem); projectSystem.Save(); }
private void AddSolutionDir() { // Add the solution dir to the list of properties string solutionDir = GetSolutionDir(); // Add a path separator for Visual Studio macro compatibility solutionDir += Path.DirectorySeparatorChar; if (!String.IsNullOrEmpty(solutionDir)) { if (this.ProjectProperties.ContainsKey("SolutionDir")) { this.Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_DuplicatePropertyKey"), "SolutionDir"); } ProjectProperties["SolutionDir"] = solutionDir; } }
internal void SelfUpdate(string exePath, SemanticVersion version) { Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCheckingForUpdates"), NuGetConstants.V2FeedUrl); // Get the nuget command line package from the specified repository IPackageRepository packageRepository = _repositoryFactory.CreateRepository(NuGetConstants.V2FeedUrl); IPackage package = packageRepository.GetUpdates( new [] { new PackageName(NuGetCommandLinePackageId, version) }, includePrerelease: true, includeAllVersions: false, targetFrameworks: null, versionConstraints: null).FirstOrDefault(); Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCurrentlyRunningNuGetExe"), version); // Check to see if an update is needed if (package == null || version >= package.Version) { Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandNuGetUpToDate")); } else { Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandUpdatingNuGet"), package.Version); // Get NuGet.exe file from the package IPackageFile file = package.GetFiles().FirstOrDefault(f => Path.GetFileName(f.Path).Equals(NuGetExe, StringComparison.OrdinalIgnoreCase)); // If for some reason this package doesn't have NuGet.exe then we don't want to use it if (file == null) { throw new CommandLineException(LocalizedResourceManager.GetString("UpdateCommandUnableToLocateNuGetExe")); } // Get the exe path and move it to a temp file (NuGet.exe.old) so we can replace the running exe with the bits we got // from the package repository string renamedPath = exePath + ".old"; Move(exePath, renamedPath); // Update the file UpdateFile(exePath, file); Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandUpdateSuccessful")); } }
private void RestorePackagesForSolution(IFileSystem packagesFolderFileSystem, string solutionFileFullPath) { ISolutionParser solutionParser; if (EnvironmentUtility.IsMonoRuntime) { solutionParser = new XBuildSolutionParser(); } else { solutionParser = new MSBuildSolutionParser(); } var solutionDirectory = Path.GetDirectoryName(solutionFileFullPath); // restore packages for the solution var solutionConfigFilePath = Path.Combine( solutionDirectory, NuGetConstants.NuGetSolutionSettingsFolder, Constants.PackageReferenceFile); RestorePackagesFromConfigFile(solutionConfigFilePath, packagesFolderFileSystem); // restore packages for projects var packageReferences = new HashSet <PackageReference>(); foreach (var projectFile in solutionParser.GetAllProjectFileNames(FileSystem, solutionFileFullPath)) { if (!FileSystem.FileExists(projectFile)) { Console.WriteWarning(LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"), projectFile); continue; } string projectConfigFilePath = Path.Combine( Path.GetDirectoryName(projectFile), Constants.PackageReferenceFile); string projectName = Path.GetFileNameWithoutExtension(projectFile); packageReferences.AddRange(GetPackageReferences(projectConfigFilePath, projectName)); } InstallPackages(packagesFolderFileSystem, packageReferences); }
internal async Task SelfUpdate(string exePath, NuGetVersion version) { Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCheckingForUpdates"), NuGetConstants.DefaultFeedUrl); var metadataResource = _source.GetResource <MetadataResource>(); if (metadataResource != null) { ResolutionContext resolutionContext = new ResolutionContext(); var latestVersionKeyPair = await metadataResource.GetLatestVersions(new List <string>() { NuGetCommandLinePackageId }, resolutionContext.IncludePrerelease, resolutionContext.IncludeUnlisted, CancellationToken.None); var lastetVersion = latestVersionKeyPair.FirstOrDefault().Value; if (version >= lastetVersion) { Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandNuGetUpToDate")); } else { Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandUpdatingNuGet"), lastetVersion.Version.ToString()); // Get NuGet.exe file using (var targetPackageStream = new MemoryStream()) { await PackageDownloader.GetPackageStream(_source, new PackageIdentity(NuGetCommandLinePackageId, lastetVersion), targetPackageStream, CancellationToken.None); // If for some reason this package doesn't have NuGet.exe then we don't want to use it if (targetPackageStream == null) { throw new CommandLineException(LocalizedResourceManager.GetString("UpdateCommandUnableToLocateNuGetExe")); } // Get the exe path and move it to a temp file (NuGet.exe.old) so we can replace the running exe with the bits we got // from the package repository string renamedPath = exePath + ".old"; Move(exePath, renamedPath); // Update the file UpdateFile(exePath, targetPackageStream); Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandUpdateSuccessful")); } } } }
private void RemoveSource() { if (String.IsNullOrEmpty(Name)) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNameRequired")); } // Check to see if we already have a registered source with the same name or source var sourceList = SourceProvider.LoadPackageSources().ToList(); var matchingSources = sourceList.Where(ps => String.Equals(Name, ps.Name, StringComparison.OrdinalIgnoreCase)).ToList(); if (!matchingSources.Any()) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNoMatchingSourcesFound"), Name); } sourceList.RemoveAll(matchingSources.Contains); SourceProvider.SavePackageSources(sourceList); Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandSourceRemovedSuccessfully"), Name); }
string GetPackagesDir(string packagesDir) { if (!String.IsNullOrEmpty(packagesDir)) { // Get the full path to the packages directory packagesDir = Path.GetFullPath(packagesDir); // REVIEW: Do we need to check for existence? if (Directory.Exists(packagesDir)) { string currentDirectory = Directory.GetCurrentDirectory(); string relativePath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(currentDirectory), packagesDir); Console.WriteLine(LocalizedResourceManager.GetString("LookingForInstalledPackages"), relativePath); return(packagesDir); } } throw new CommandLineException(LocalizedResourceManager.GetString("UnableToLocatePackagesFolder")); }
private void UpdatePackageSource() { if (String.IsNullOrEmpty(Name)) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNameRequired")); } List <PackageSource> sourceList = SourceProvider.LoadPackageSources().ToList(); int existingSourceIndex = sourceList.FindIndex(ps => Name.Equals(ps.Name, StringComparison.OrdinalIgnoreCase)); if (existingSourceIndex == -1) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNoMatchingSourcesFound"), Name); } var existingSource = sourceList[existingSourceIndex]; if (!String.IsNullOrEmpty(Source) && !existingSource.Source.Equals(Source, StringComparison.OrdinalIgnoreCase)) { if (!PathValidator.IsValidSource(Source)) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandInvalidSource")); } // If the user is updating the source, verify we don't have a duplicate. bool duplicateSource = sourceList.Any(ps => String.Equals(Source, ps.Source, StringComparison.OrdinalIgnoreCase)); if (duplicateSource) { throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandUniqueSource")); } existingSource = new PackageSource(Source, existingSource.Name); } ValidateCredentials(); sourceList.RemoveAt(existingSourceIndex); existingSource.UserName = UserName; existingSource.Password = Password; existingSource.IsPasswordClearText = StorePasswordInClearText; sourceList.Insert(existingSourceIndex, existingSource); SourceProvider.SavePackageSources(sourceList); Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandUpdateSuccessful"), Name); }
public override void ExecuteCommand() { if (Verbose) { Console.WriteWarning(LocalizedResourceManager.GetString("Option_VerboseDeprecated")); Verbosity = Verbosity.Detailed; } // Get the input file string path = GetInputFile(); Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildPackage"), Path.GetFileName(path)); // If the BasePath is not specified, use the directory of the input file (nuspec / proj) file BasePath = String.IsNullOrEmpty(BasePath) ? Path.GetDirectoryName(Path.GetFullPath(path)) : BasePath; // Validate the BaseTargetPath, if it is provided if (!string.IsNullOrWhiteSpace(BaseTargetPath)) { if (Build) { // Providing BaseTargetPath only makes sense when the NuGet is not building the solution, // i.e. the solution is built by TFS Team Build. throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandIrrelevantBaseTargetPath")); } if (!Directory.Exists(BaseTargetPath)) { throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidBaseTargetPath")); } } if (!String.IsNullOrEmpty(MinClientVersion)) { if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue)) { throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidMinClientVersion")); } } BuildPackage(path); }
protected void CalculateEffectivePackageSaveMode() { string packageSaveModeValue = PackageSaveMode; if (string.IsNullOrEmpty(packageSaveModeValue)) { var settingValue = Settings.GetSettingValues("PackageSaveMode"); if (settingValue.Any()) { packageSaveModeValue = settingValue.FirstOrDefault().Value; } } EffectivePackageSaveMode = PackageSaveModes.None; if (!string.IsNullOrEmpty(packageSaveModeValue)) { foreach (var v in packageSaveModeValue.Split(';')) { if (v.Equals(PackageSaveModes.Nupkg.ToString(), StringComparison.OrdinalIgnoreCase)) { EffectivePackageSaveMode |= PackageSaveModes.Nupkg; } else if (v.Equals(PackageSaveModes.Nuspec.ToString(), StringComparison.OrdinalIgnoreCase)) { EffectivePackageSaveMode |= PackageSaveModes.Nuspec; } else { string message = String.Format( CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("Warning_InvalidPackageSaveMode"), v); Console.WriteWarning(message); } } } else { // Default to nupkg only EffectivePackageSaveMode = PackageSaveModes.Nupkg; } }
private void PushSymbols(string packagePath, TimeSpan timeout) { // Get the symbol package for this package string symbolPackagePath = GetSymbolsPath(packagePath); // Push the symbols package if it exists if (File.Exists(symbolPackagePath)) { string source = NuGetConstants.DefaultSymbolServerUrl; // See if the api key exists string apiKey = GetApiKey(source); if (String.IsNullOrEmpty(apiKey)) { Console.WriteWarning(LocalizedResourceManager.GetString("Warning_SymbolServerNotConfigured"), Path.GetFileName(symbolPackagePath), LocalizedResourceManager.GetString("DefaultSymbolServer")); } PushPackage(symbolPackagePath, source, apiKey, timeout); } }