public void ExtractOptions(ICommand command, IEnumerator <string> argsEnumerator)
        {
            List <string> arguments = new List <string>();
            IDictionary <OptionAttribute, PropertyInfo> properties = _commandManager.GetCommandOptions(command);

            while (true)
            {
                string option = GetNextCommandLineItem(argsEnumerator);

                if (option == null)
                {
                    break;
                }

                if (!(option.StartsWith("/", StringComparison.OrdinalIgnoreCase) && _supportSlashAsSwitch) &&
                    !option.StartsWith("-", StringComparison.OrdinalIgnoreCase))
                {
                    arguments.Add(option);
                    continue;
                }

                string optionText = option.Substring(1);
                string value      = null;

                if (optionText.EndsWith("-", StringComparison.OrdinalIgnoreCase))
                {
                    optionText = optionText.TrimEnd('-');
                    value      = "false";
                }

                var          result   = GetPartialOptionMatch(properties, prop => prop.Value.Name, prop => prop.Key.AltName, option, optionText);
                PropertyInfo propInfo = result.Value;

                if (propInfo.PropertyType == typeof(bool))
                {
                    value = value ?? "true";
                }
                else
                {
                    value = GetNextCommandLineItem(argsEnumerator);
                }

                if (value == null)
                {
                    throw new CommandLineException(LocalizedResourceManager.GetString("MissingOptionValueError"), option);
                }

                AssignValue(command, propInfo, option, value);
            }
            CommandLineHelper.AddRange(command.Arguments, arguments);
        }
 public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CoreV2.NuGet.CredentialType credentialType, bool retrying)
 {
     // If we are retrying, the stored credentials must be invalid.
     if (!retrying && (credentialType == CoreV2.NuGet.CredentialType.RequestCredentials) && TryGetCredentials(uri, out var credentials, out var username))
     {
         _logger.LogMinimal(
             string.Format(
                 CultureInfo.CurrentCulture,
                 LocalizedResourceManager.GetString(nameof(NuGetResources.SettingsCredentials_UsingSavedCredentials)),
                 username));
         return(credentials);
     }
     return(null);
 }
Exemple #3
0
 internal static string CombinePathWithVerboseError(params string[] paths)
 {
     try
     {
         return(Path.Combine(paths));
     }
     catch (ArgumentException e)
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                   LocalizedResourceManager.GetString("Error_InvalidCharactersInPathSegment"),
                                                   string.Join("', '", paths)),
                                     e);
     }
 }
        private static MsBuildToolset GetToolsetFromUserVersion(
            string userVersion,
            IEnumerable <MsBuildToolset> installedToolsets)
        {
            // Version.TryParse only take decimal string like "14.0", "14" need to be converted.
            var versionParts = userVersion.Split('.');
            var major        = versionParts.Length > 0 ? versionParts[0] : "0";
            var minor        = versionParts.Length > 1 ? versionParts[1] : "0";

            var userVersionString = string.Join(".", major, minor);

            // First match by string comparison
            var selectedToolset = installedToolsets.FirstOrDefault(
                t => string.Equals(userVersion, t.Version, StringComparison.OrdinalIgnoreCase));

            if (selectedToolset != null)
            {
                return(selectedToolset);
            }

            // Then match by Major & Minor version numbers. And we want an actual parsing of t.ToolsVersion,
            // without the safe fallback to 0.0 built into t.ParsedToolsVersion.
            selectedToolset = installedToolsets.FirstOrDefault(t =>
            {
                Version parsedUserVersion;
                Version parsedToolsVersion;
                if (Version.TryParse(userVersionString, out parsedUserVersion) &&
                    Version.TryParse(t.Version, out parsedToolsVersion))
                {
                    return(parsedToolsVersion.Major == parsedUserVersion.Major &&
                           parsedToolsVersion.Minor == parsedUserVersion.Minor);
                }

                return(false);
            });

            if (selectedToolset == null)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString(
                        nameof(NuGetResources.Error_CannotFindMsbuild)),
                    userVersion);

                throw new CommandException(message);
            }

            return(selectedToolset);
        }
Exemple #5
0
        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 Configuration.PackageSource(Source, Name);

            if (!string.IsNullOrEmpty(UserName))
            {
                var credentials = Configuration.PackageSourceCredential.FromUserInput(Name, UserName, Password, StorePasswordInClearText);
                newPackageSource.Credentials = credentials;
            }

            sourceList.Add(newPackageSource);
            SourceProvider.SavePackageSources(sourceList);
            Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandSourceAddedSuccessfully"), Name);
        }
Exemple #6
0
 private static void LogHelperMessageForPathTooLongException(Console logger)
 {
     if (!IsWindows10(logger))
     {
         logger.WriteWarning(LocalizedResourceManager.GetString(nameof(NuGetResources.Warning_LongPath_UnsupportedOS)));
     }
     else if (!IsSupportLongPathEnabled(logger))
     {
         logger.WriteWarning(LocalizedResourceManager.GetString(nameof(NuGetResources.Warning_LongPath_DisabledPolicy)));
     }
     else if (!IsRuntimeGreaterThanNet462(logger))
     {
         logger.WriteWarning(LocalizedResourceManager.GetString(nameof(NuGetResources.Warning_LongPath_UnsupportedNetFramework)));
     }
 }
 /// <summary>
 /// Outputs the current NuGet version (by default, only when vebosity is detailed).
 /// </summary>
 private void OutputNuGetVersion()
 {
     if (ShouldOutputNuGetVersion)
     {
         var assemblyName     = Assembly.GetExecutingAssembly().GetName();
         var assemblyLocation = Assembly.GetExecutingAssembly().Location;
         var version          = System.Diagnostics.FileVersionInfo.GetVersionInfo(assemblyLocation).FileVersion;
         var message          = string.Format(
             CultureInfo.CurrentCulture,
             LocalizedResourceManager.GetString("OutputNuGetVersion"),
             assemblyName.Name,
             version);
         Console.WriteLine(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);
            }

            SettingsUtility.SetEncryptedValue(Settings, ConfigurationConstants.ApiKeys, source, apiKey);

            string sourceName = CommandLineUtility.GetSourceDisplayName(source);

            // Setup the symbol server key
            if (setSymbolServerKey)
            {
                SettingsUtility.SetEncryptedValue(Settings, ConfigurationConstants.ApiKeys, NuGetConstants.DefaultSymbolServerUrl, apiKey);
                Console.WriteLine(LocalizedResourceManager.GetString("SetApiKeyCommandDefaultApiKeysSaved"),
                                  apiKey,
                                  sourceName,
                                  CommandLineUtility.GetSourceDisplayName(NuGetConstants.DefaultSymbolServerUrl));
            }
            else
            {
                Console.WriteLine(LocalizedResourceManager.GetString("SetApiKeyCommandApiKeySaved"), apiKey, sourceName);
            }
        }
Exemple #9
0
        /// <summary>
        /// Gets the msbuild toolset that matches the given <paramref name="msbuildVersion"/>.
        /// </summary>
        /// <param name="msbuildVersion">The msbuild version. Can be null.</param>
        /// <param name="installedToolsets">List of installed toolsets,
        /// ordered by ToolsVersion, from highest to lowest.</param>
        /// <returns>The matching toolset.</returns>
        /// <remarks>This method is not intended to be called directly. It's marked public so that it
        /// can be called by unit tests.</remarks>
        public static MsbuildToolSet SelectMsbuildToolset(
            Version msbuildVersion,
            IEnumerable <MsbuildToolSet> installedToolsets)
        {
            MsbuildToolSet selectedToolset;

            if (msbuildVersion == null)
            {
                // MSBuild does not exist in PATH. In this case, the highest installed version is used
                selectedToolset = installedToolsets.FirstOrDefault();
            }
            else
            {
                // Search by major & minor version
                selectedToolset = installedToolsets.FirstOrDefault(
                    toolset =>
                {
                    var v = SafeParseVersion(toolset.ToolsVersion);
                    return(v.Major == msbuildVersion.Major && v.Minor == v.Minor);
                });

                if (selectedToolset == null)
                {
                    // no match found. Now search by major only
                    selectedToolset = installedToolsets.FirstOrDefault(
                        toolset =>
                    {
                        var v = SafeParseVersion(toolset.ToolsVersion);
                        return(v.Major == msbuildVersion.Major);
                    });
                }

                if (selectedToolset == null)
                {
                    // still no match. Use the highest installed version in this case
                    selectedToolset = installedToolsets.FirstOrDefault();
                }
            }

            if (selectedToolset == null)
            {
                throw new CommandLineException(
                          LocalizedResourceManager.GetString(
                              nameof(NuGetResources.Error_MSBuildNotInstalled)));
            }

            return(selectedToolset);
        }
Exemple #10
0
        private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs)
        {
            restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath);
            restoreInputs.NameOfSolutionFile      = Path.GetFileNameWithoutExtension(solutionFileFullPath);

            // restore packages for the solution
            string solutionLevelPackagesConfig;

            try
            {
                solutionLevelPackagesConfig = Path.Combine(
                    restoreInputs.DirectoryOfSolutionFile,
                    NuGetConstants.NuGetSolutionSettingsFolder,
                    Constants.PackageReferenceFile);
            }
            catch (ArgumentException e)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          LocalizedResourceManager.GetString("Error_InvalidSolutionDirectory"),
                                                          restoreInputs.DirectoryOfSolutionFile),
                                            e);
            }

            if (File.Exists(solutionLevelPackagesConfig))
            {
                restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig);
            }

            var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, MsBuildDirectory.Value.Path);

            foreach (var projectFile in projectFiles)
            {
                if (!File.Exists(projectFile))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"),
                                                projectFile);
                    Console.LogWarning(message);
                    continue;
                }

                var normalizedProjectFile = Path.GetFullPath(projectFile);

                // Add everything
                restoreInputs.ProjectFiles.Add(normalizedProjectFile);
            }
        }
Exemple #11
0
        private void UpdatePackageSource()
        {
            if (String.IsNullOrEmpty(Name))
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNameRequired"));
            }

            var 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 Configuration.PackageSource(Source, existingSource.Name);
            }

            ValidateCredentials();

            sourceList.RemoveAt(existingSourceIndex);

            if (!string.IsNullOrEmpty(UserName))
            {
                var credentials = Configuration.PackageSourceCredential.FromUserInput(Name, UserName, Password,
                                                                                      storePasswordInClearText: StorePasswordInClearText);
                existingSource.Credentials = credentials;
            }

            sourceList.Insert(existingSourceIndex, existingSource);
            SourceProvider.SavePackageSources(sourceList);
            Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandUpdateSuccessful"), Name);
        }
Exemple #12
0
        public override async Task ExecuteCommandAsync()
        {
            string packagePath = Arguments[0];
            string apiKeyValue = null;

            if (!string.IsNullOrEmpty(ApiKey))
            {
                apiKeyValue = ApiKey;
            }
            else if (Arguments.Count > 1 && !string.IsNullOrEmpty(Arguments[1]))
            {
                apiKeyValue = Arguments[1];
            }

            try
            {
                await PushRunner.Run(
                    Settings,
                    SourceProvider,
                    new[] { packagePath },
                    Source,
                    apiKeyValue,
                    SymbolSource,
                    SymbolApiKey,
                    Timeout,
                    DisableBuffering,
                    NoSymbols,
                    NoServiceEndpoint,
                    SkipDuplicate,
                    Console);
            }
            catch (TaskCanceledException ex)
            {
                string timeoutMessage = LocalizedResourceManager.GetString(nameof(NuGetResources.PushCommandTimeoutError));
                throw new AggregateException(ex, new Exception(timeoutMessage));
            }
            catch (Exception ex)
            {
                if (ex is HttpRequestException && ex.InnerException is WebException)
                {
                    throw ex.InnerException;
                }

                throw;
            }
        }
Exemple #13
0
        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();
            }
        }
Exemple #14
0
        private Task PerformV2Restore(string packagesConfigFilePath, string installPath)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath, ExcludeVersion);

            var installedPackageReferences = GetInstalledPackageReferences(
                packagesConfigFilePath,
                allowDuplicatePackageIds: true);

            var packageRestoreData = installedPackageReferences.Select(reference =>
                                                                       new PackageRestoreData(
                                                                           reference,
                                                                           new[] { packagesConfigFilePath },
                                                                           isMissing: true));

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: null,
                packageRestoreFailedEvent: null,
                sourceRepositories: packageSources.Select(sourceRepositoryProvider.CreateRepository),
                maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).Any();

            if (!missingPackageReferences)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    packagesConfigFilePath);

                Console.LogMinimal(message);
            }

            Task <PackageRestoreResult> packageRestoreTask = PackageRestoreManager.RestoreMissingPackagesAsync(packageRestoreContext, new ConsoleProjectContext(Console));

            return(packageRestoreTask);
        }
Exemple #15
0
        private async Task UpdateTrustedSourceAsync(PackageSource packageSource)
        {
            var sourceRepositoryProvider    = new CommandLineSourceRepositoryProvider(SourceProvider);
            var repositorySignatureResource = await sourceRepositoryProvider.CreateRepository(packageSource).GetResourceAsync <RepositorySignatureResource>() ??
                                              throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandSourceNotSupportRepoSign"), packageSource.Name);

            var trustedSource = new TrustedSource(packageSource.Name);

            foreach (var cert in repositorySignatureResource.RepositoryCertificateInfos)
            {
                foreach (var fingerprint in cert.Fingerprints)
                {
                    trustedSource.Certificates.Add(new CertificateTrustEntry(fingerprint.Value, cert.Subject, CryptoHashUtility.OidToHashAlgorithmName(fingerprint.Key)));
                }
            }

            packageSource.TrustedSource = trustedSource;
        }
Exemple #16
0
        private MSBuildProjectSystem GetMSBuildProject(string packageReferenceFilePath, INuGetProjectContext projectContext)
        {
            // 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(_msbuildDirectory, projectFiles[0], projectContext));
        }
Exemple #17
0
        private void ValidateCredentials()
        {
            var isUsernameEmpty  = string.IsNullOrEmpty(Username);
            var isPasswordEmpty  = string.IsNullOrEmpty(Password);
            var isAuthTypesEmpty = string.IsNullOrEmpty(ValidAuthenticationTypes);

            if (isUsernameEmpty ^ isPasswordEmpty)
            {
                // If only one of them is set, throw.
                throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandCredentialsRequired"));
            }

            if (isPasswordEmpty && !isAuthTypesEmpty)
            {
                // can't specify auth types without credentials
                throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandCredentialsRequiredWithAuthTypes"));
            }
        }
        public override Task ExecuteCommandAsync()
        {
            // On mono, parallel builds are broken for some reason. See https://gist.github.com/4201936 for the errors
            // That are thrown.
            DisableParallelProcessing |= RuntimeEnvironmentHelper.IsMono;

            if (DisableParallelProcessing)
            {
                HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
            }

            CalculateEffectivePackageSaveMode();
            CalculateEffectiveSettings();
            var installPath = Path.GetFullPath(ResolveInstallPath());

            var configFilePath = Path.GetFullPath(Arguments.Count == 0 ? Constants.PackageReferenceFile : Arguments[0]);
            var configFileName = Path.GetFileName(configFilePath);

            // If the first argument is a packages.xxx.config file, install everything it lists
            // Otherwise, treat the first argument as a package Id
            if (CommandLineUtility.IsValidConfigFileName(configFileName))
            {
                Prerelease = true;

                // display opt-out message if needed
                if (Console != null && RequireConsent &&
                    new PackageRestoreConsent(Settings).IsGranted)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandPackageRestoreOptOutMessage"),
                        NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                    Console.WriteLine(message);
                }

                return(PerformV2RestoreAsync(configFilePath, installPath));
            }
            else
            {
                var packageId = Arguments[0];
                var version   = Version != null ? new NuGetVersion(Version) : null;
                return(InstallPackageAsync(packageId, version, installPath));
            }
        }
Exemple #19
0
        internal void SelfUpdate(string exePath, bool prerelease, CoreV2.NuGet.SemanticVersion version)
        {
            Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCheckingForUpdates"), NuGetConstants.V2FeedUrl);

            // Get the nuget command line package from the specified repository
            CoreV2.NuGet.IPackageRepository packageRepository = _repositoryFactory.CreateRepository(NuGetConstants.V2FeedUrl);
            CoreV2.NuGet.IPackage           package           = packageRepository.GetUpdates(
                new [] { new CoreV2.NuGet.PackageName(NuGetCommandLinePackageId, version) },
                includePrerelease: prerelease,
                includeAllVersions: false,
                targetFrameworks: null,
                versionConstraints: null).FirstOrDefault();

            Console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCurrentlyRunningNuGetExe"), version); // SemanticVersion is the problem

            // 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
                CoreV2.NuGet.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"));
            }
        }
Exemple #20
0
        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);
        }
Exemple #21
0
        public override async Task ExecuteCommandAsync()
        {
            // Arguments[0] or Arguments[1] will not be null at this point.
            // Because, this command has MinArgs set to 2.
            var source      = Arguments[0];
            var destination = Arguments[1];

            OfflineFeedUtility.ThrowIfInvalidOrNotFound(
                source,
                isDirectory: true,
                resourceString: LocalizedResourceManager.GetString(nameof(NuGetResources.InitCommand_FeedIsNotFound)));

            // If the Destination Feed Folder does not exist, it will be created.
            OfflineFeedUtility.ThrowIfInvalid(destination);

            var packagePaths = GetPackageFilePaths(source, "*" + PackagingCoreConstants.NupkgExtension);

            if (packagePaths.Count > 0)
            {
                foreach (var packagePath in packagePaths)
                {
                    var offlineFeedAddContext = new OfflineFeedAddContext(
                        packagePath,
                        destination,
                        Console, // IConsole is an ILogger
                        throwIfSourcePackageIsInvalid: false,
                        throwIfPackageExistsAndInvalid: false,
                        throwIfPackageExists: false,
                        expand: Expand);

                    await OfflineFeedUtility.AddPackageToSource(offlineFeedAddContext, CancellationToken.None);
                }
            }
            else
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString(nameof(NuGetResources.InitCommand_FeedContainsNoPackages)),
                    source);

                Console.LogMinimal(message);
            }
        }
Exemple #22
0
        /// <summary>
        /// Discover all restore inputs, this checks for both v2 and v3
        /// </summary>
        private async Task <PackageRestoreInputs> DetermineRestoreInputsAsync()
        {
            var packageRestoreInputs = new PackageRestoreInputs();

            if (Arguments.Count == 0)
            {
                // If no arguments were provided use the current directory
                GetInputsFromDirectory(Directory.GetCurrentDirectory(), packageRestoreInputs);
            }
            else
            {
                // Restore takes multiple arguments, each could be a file or directory
                var argument = Arguments.Single();
                var fullPath = Path.GetFullPath(argument);

                if (Directory.Exists(fullPath))
                {
                    // Dir
                    GetInputsFromDirectory(fullPath, packageRestoreInputs);
                }
                else if (File.Exists(fullPath))
                {
                    // File
                    GetInputsFromFile(fullPath, packageRestoreInputs);
                }
                else
                {
                    // Not found
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        argument);

                    throw new InvalidOperationException(message);
                }
            }
            // Run inputs through msbuild to determine the
            // correct type and find dependencies as needed.
            await DetermineInputsFromMSBuildAsync(packageRestoreInputs);

            return(packageRestoreInputs);
        }
Exemple #23
0
        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 source = SourceProvider.GetPackageSourceByName(Name);

            if (source == null)
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNoMatchingSourcesFound"), Name);
            }

            SourceProvider.RemovePackageSource(Name);
            Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandSourceRemovedSuccessfully"), Name);
        }
            /// <summary>
            /// Constructor. It creates an empty temp file under the temp directory / NuGet, with
            /// extension <paramref name="extension"/>.
            /// </summary>
            /// <param name="extension">The extension of the temp file.</param>
            public TempFile(string extension)
            {
                if (string.IsNullOrEmpty(extension))
                {
                    throw new ArgumentNullException(nameof(extension));
                }

                var tempDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp);

                Directory.CreateDirectory(tempDirectory);

                var count = 0;

                do
                {
                    _filePath = Path.Combine(tempDirectory, Path.GetRandomFileName() + extension);

                    if (!File.Exists(_filePath))
                    {
                        try
                        {
                            // create an empty file
                            using (var filestream = File.Open(_filePath, FileMode.CreateNew))
                            {
                            }

                            // file is created successfully.
                            return;
                        }
                        catch
                        {
                            // Ignore and try again
                        }
                    }

                    count++;
                }while (count < 3);

                throw new InvalidOperationException(
                          LocalizedResourceManager.GetString(nameof(NuGetResources.Error_FailedToCreateRandomFileForP2P)));
            }
        /// <summary>
        /// Parse the Framework parameter or use Any as the default framework.
        /// </summary>
        private NuGetFramework GetTargetFramework()
        {
            var targetFramework = NuGetFramework.AnyFramework;

            if (!string.IsNullOrEmpty(Framework))
            {
                targetFramework = NuGetFramework.Parse(Framework);
            }

            if (targetFramework.IsUnsupported)
            {
                // Fail with a helpful message if the user provided an invalid framework.
                var message = string.Format(CultureInfo.CurrentCulture,
                                            LocalizedResourceManager.GetString("UnsupportedFramework"),
                                            Framework);

                throw new ArgumentException(message);
            }

            return(targetFramework);
        }
        private static MethodInfo GetAllProjectFileNamesMethod()
        {
#pragma warning disable 618
            var assembly = typeof(Microsoft.Build.BuildEngine.Engine).Assembly;
#pragma warning restore 618
            var solutionParserType = assembly.GetType("Mono.XBuild.CommandLine.SolutionParser");
            if (solutionParserType == null)
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("Error_CannotGetXBuildSolutionParser"));
            }

            var methodInfo = solutionParserType.GetMethod(
                "GetAllProjectFileNames",
                new Type[] { typeof(string) });
            if (methodInfo == null)
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("Error_CannotGetGetAllProjectFileNamesMethod"));
            }

            return(methodInfo);
        }
Exemple #27
0
        public override Task ExecuteCommandAsync()
        {
            if (DisableParallelProcessing)
            {
                HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
            }

            CalculateEffectivePackageSaveMode();
            CalculateEffectiveSettings();
            string installPath = ResolveInstallPath();

            string configFilePath = Path.GetFullPath(Arguments.Count == 0 ? Constants.PackageReferenceFile : Arguments[0]);
            string configFileName = Path.GetFileName(configFilePath);

            // If the first argument is a packages.xxx.config file, install everything it lists
            // Otherwise, treat the first argument as a package Id
            if (PackageReferenceFile.IsValidConfigFileName(configFileName))
            {
                Prerelease = true;

                // display opt-out message if needed
                if (Console != null && RequireConsent &&
                    new PackageRestoreConsent(new SettingsToLegacySettings(Settings)).IsGranted)
                {
                    string message = String.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandPackageRestoreOptOutMessage"),
                        NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                    Console.WriteLine(message);
                }

                return(PerformV2Restore(configFilePath, installPath));
            }
            else
            {
                var packageId = Arguments[0];
                var version   = Version != null ? new NuGetVersion(Version) : null;
                return(InstallPackage(packageId, version, installPath));
            }
        }
        public static object ChangeType(object value, Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (value == null)
            {
                if (TypeAllowsNull(type))
                {
                    return(null);
                }
                return(Convert.ChangeType(value, type, CultureInfo.CurrentCulture));
            }

            type = RemoveNullableFromType(type);

            if (value.GetType() == type)
            {
                return(value);
            }

            TypeConverter converter = TypeDescriptor.GetConverter(type);

            if (converter.CanConvertFrom(value.GetType()))
            {
                return(converter.ConvertFrom(value));
            }

            TypeConverter otherConverter = TypeDescriptor.GetConverter(value.GetType());

            if (otherConverter.CanConvertTo(type))
            {
                return(otherConverter.ConvertTo(value, type));
            }

            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                                                              LocalizedResourceManager.GetString("UnableToConvertTypeError"), value.GetType(), type));
        }
Exemple #29
0
        public override async Task ExecuteCommandAsync()
        {
            string packagePath    = Arguments[0];
            string sourcePath     = Source;
            string apiKeyValue    = ApiKey;
            int    timeoutSeconds = Timeout;

            if (string.IsNullOrEmpty(apiKeyValue) && Arguments.Count > 1)
            {
                apiKeyValue = Arguments[1];
            }

            try
            {
                await PushRunner.Run(
                    Settings,
                    SourceProvider,
                    packagePath,
                    Source,
                    apiKeyValue,
                    Timeout,
                    DisableBuffering,
                    NoSymbols,
                    Console);
            }
            catch (TaskCanceledException ex)
            {
                string timeoutMessage = LocalizedResourceManager.GetString(nameof(NuGetResources.PushCommandTimeoutError));
                throw new AggregateException(ex, new Exception(timeoutMessage));
            }
            catch (Exception ex)
            {
                if (ex is HttpRequestException && ex.InnerException is WebException)
                {
                    throw ex.InnerException;
                }

                throw;
            }
        }
Exemple #30
0
        internal void CalculateEffectivePackageSaveMode()
        {
            string packageSaveModeValue = PackageSaveMode;

            if (string.IsNullOrEmpty(packageSaveModeValue))
            {
                packageSaveModeValue = SettingsUtility.GetConfigValue(Settings, "PackageSaveMode");
            }

            if (!string.IsNullOrEmpty(packageSaveModeValue))
            {
                // The PackageSaveMode flag only determines if nuspec and nupkg are saved at the target location.
                // For install \ restore, we always extract files.
                EffectivePackageSaveMode = Packaging.PackageSaveMode.Files;
                foreach (var v in packageSaveModeValue.Split(';'))
                {
                    if (v.Equals(Packaging.PackageSaveMode.Nupkg.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        EffectivePackageSaveMode |= Packaging.PackageSaveMode.Nupkg;
                    }
                    else if (v.Equals(Packaging.PackageSaveMode.Nuspec.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        EffectivePackageSaveMode |= Packaging.PackageSaveMode.Nuspec;
                    }
                    else
                    {
                        string message = String.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("Warning_InvalidPackageSaveMode"),
                            v);

                        throw new InvalidOperationException(message);
                    }
                }
            }
            else
            {
                EffectivePackageSaveMode = Packaging.PackageSaveMode.None;
            }
        }