internal static void Register(CommandLineApplication app, Func <ILogger> getLogger, Action <LogLevel> setLogLevel, Func <IVerifyCommandRunner> getCommandRunner) { app.Command("verify", verifyCmd => { CommandArgument packagePaths = verifyCmd.Argument( "<package-paths>", Strings.VerifyCommandPackagePathDescription, multipleValues: true); CommandOption all = verifyCmd.Option( "--all", Strings.VerifyCommandAllDescription, CommandOptionType.NoValue); CommandOption fingerPrint = verifyCmd.Option( "--certificate-fingerprint", Strings.VerifyCommandCertificateFingerprintDescription, CommandOptionType.MultipleValue); CommandOption verbosity = verifyCmd.Option( "-v|--verbosity", Strings.Verbosity_Description, CommandOptionType.SingleValue); verifyCmd.HelpOption(XPlatUtility.HelpOption); verifyCmd.Description = Strings.VerifyCommandDescription; verifyCmd.OnExecute(async() => { ValidatePackagePaths(packagePaths); VerifyArgs args = new VerifyArgs(); args.PackagePaths = packagePaths.Values; args.Verifications = all.HasValue() ? new List <Verification>() { Verification.All } : new List <Verification>() { Verification.Signatures }; args.CertificateFingerprint = fingerPrint.Values; args.Logger = getLogger(); setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value())); var runner = getCommandRunner(); var verifyTask = runner.ExecuteCommandAsync(args); await verifyTask; return(verifyTask.Result); }); }); }
/// <summary> /// Attempts to parse the desired log verbosity from the arguments. Returns true if the /// arguments contains a valid verbosity option. If no valid verbosity option was /// specified, the log level is set to a default log level and false is returned. /// </summary> private static bool TryParseVerbosity(string[] args, CommandOption verbosity, out LogLevel logLevel) { bool found = false; for (var index = 0; index < args.Length; index++) { var arg = args[index]; string[] option; if (arg.StartsWith("--")) { option = arg.Substring(2).Split(new[] { ':', '=' }, 2); if (!string.Equals(option[0], verbosity.LongName, StringComparison.Ordinal)) { continue; } } else if (arg.StartsWith("-")) { option = arg.Substring(1).Split(new[] { ':', '=' }, 2); if (!string.Equals(option[0], verbosity.ShortName, StringComparison.Ordinal)) { continue; } } else { continue; } if (option.Length == 2) { found = verbosity.TryParse(option[1]); } else if (index < args.Length - 1) { found = verbosity.TryParse(args[index + 1]); } break; } logLevel = XPlatUtility.GetLogLevel(verbosity); // Reset the parsed value since the application execution expects the option to not be // populated yet, as this is a single-valued option. verbosity.Values.Clear(); return(found); }
private static ISettings ProcessConfigFile(string configFile) { if (string.IsNullOrEmpty(configFile)) { return(XPlatUtility.CreateDefaultSettings()); } var configFileFullPath = Path.GetFullPath(configFile); var directory = Path.GetDirectoryName(configFileFullPath); var configFileName = Path.GetFileName(configFileFullPath); return(Settings.LoadDefaultSettings( directory, configFileName, machineWideSettings: new XPlatMachineWideSetting())); }
private static async Task <RestoreResultPair> PreviewAddPackageReference(PackageReferenceArgs packageReferenceArgs, DependencyGraphSpec dgSpec, PackageSpec originalPackageSpec) { // Set user agent and connection settings. XPlatUtility.ConfigureProtocol(); var providerCache = new RestoreCommandProvidersCache(); using (var cacheContext = new SourceCacheContext()) { cacheContext.NoCache = false; cacheContext.IgnoreFailedSources = false; // Pre-loaded request provider containing the graph file var providers = new List <IPreLoadedRestoreRequestProvider>(); // Create a copy to avoid modifying the original spec which may be shared. var updatedPackageSpec = originalPackageSpec.Clone(); PackageSpecOperations.AddOrUpdateDependency(updatedPackageSpec, packageReferenceArgs.PackageDependency); providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgSpec)); var restoreContext = new RestoreArgs() { CacheContext = cacheContext, LockFileVersion = LockFileFormat.Version, Log = packageReferenceArgs.Logger, MachineWideSettings = new XPlatMachineWideSetting(), GlobalPackagesFolder = packageReferenceArgs.PackageDirectory, PreLoadedRequestProviders = providers, Sources = packageReferenceArgs.Sources?.ToList() }; // Generate Restore Requests. There will always be 1 request here since we are restoring for 1 project. var restoreRequests = await RestoreRunner.GetRequests(restoreContext); // Run restore without commit. This will always return 1 Result pair since we are restoring for 1 request. var restoreResult = await RestoreRunner.RunWithoutCommit(restoreRequests, restoreContext); return(restoreResult.Single()); } }
private static async Task <RestoreResultPair> PreviewAddPackageReferenceAsync(PackageReferenceArgs packageReferenceArgs, DependencyGraphSpec dgSpec) { // Set user agent and connection settings. XPlatUtility.ConfigureProtocol(); var providerCache = new RestoreCommandProvidersCache(); using (var cacheContext = new SourceCacheContext()) { cacheContext.NoCache = false; cacheContext.IgnoreFailedSources = false; // Pre-loaded request provider containing the graph file var providers = new List <IPreLoadedRestoreRequestProvider> { new DependencyGraphSpecRequestProvider(providerCache, dgSpec) }; var restoreContext = new RestoreArgs() { CacheContext = cacheContext, LockFileVersion = LockFileFormat.Version, Log = packageReferenceArgs.Logger, MachineWideSettings = new XPlatMachineWideSetting(), GlobalPackagesFolder = packageReferenceArgs.PackageDirectory, PreLoadedRequestProviders = providers, Sources = packageReferenceArgs.Sources?.ToList() }; // Generate Restore Requests. There will always be 1 request here since we are restoring for 1 project. var restoreRequests = await RestoreRunner.GetRequests(restoreContext); //Setup the Credential Service DefaultCredentialServiceUtility.SetupDefaultCredentialService(restoreContext.Log, !packageReferenceArgs.Interactive); // Run restore without commit. This will always return 1 Result pair since we are restoring for 1 request. var restoreResult = await RestoreRunner.RunWithoutCommit(restoreRequests, restoreContext); return(restoreResult.Single()); } }
public static void Register(CommandLineApplication app, Func <ILogger> getLogger) { app.Command("push", push => { push.Description = Strings.Push_Description; push.HelpOption(XPlatUtility.HelpOption); push.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var source = push.Option( "-s|--source <source>", Strings.Source_Description, CommandOptionType.SingleValue); var symbolSource = push.Option( "-ss|--symbol-source <source>", Strings.SymbolSource_Description, CommandOptionType.SingleValue); var timeout = push.Option( "-t|--timeout <timeout>", Strings.Push_Timeout_Description, CommandOptionType.SingleValue); var apikey = push.Option( "-k|--api-key <apiKey>", Strings.ApiKey_Description, CommandOptionType.SingleValue); var symbolApiKey = push.Option( "-sk|--symbol-api-key <apiKey>", Strings.SymbolApiKey_Description, CommandOptionType.SingleValue); var disableBuffering = push.Option( "-d|--disable-buffering", Strings.DisableBuffering_Description, CommandOptionType.SingleValue); var noSymbols = push.Option( "-n|--no-symbols", Strings.NoSymbols_Description, CommandOptionType.SingleValue); var arguments = push.Argument( "[root]", Strings.Push_Package_ApiKey_Description, multipleValues: true); var noServiceEndpointDescription = push.Option( "--no-service-endpoint", Strings.NoServiceEndpoint_Description, CommandOptionType.NoValue); var interactive = push.Option( "--interactive", Strings.NuGetXplatCommand_Interactive, CommandOptionType.NoValue); push.OnExecute(async() => { if (arguments.Values.Count < 1) { throw new ArgumentException(Strings.Push_MissingArguments); } string packagePath = arguments.Values[0]; string sourcePath = source.Value(); string apiKeyValue = apikey.Value(); string symbolSourcePath = symbolSource.Value(); string symbolApiKeyValue = symbolApiKey.Value(); bool disableBufferingValue = disableBuffering.HasValue(); bool noSymbolsValue = noSymbols.HasValue(); bool noServiceEndpoint = noServiceEndpointDescription.HasValue(); int timeoutSeconds = 0; if (timeout.HasValue() && !int.TryParse(timeout.Value(), out timeoutSeconds)) { throw new ArgumentException(Strings.Push_InvalidTimeout); } var sourceProvider = new PackageSourceProvider(XPlatUtility.CreateDefaultSettings()); try { DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue()); await PushRunner.Run( sourceProvider.Settings, sourceProvider, packagePath, sourcePath, apiKeyValue, symbolSourcePath, symbolApiKeyValue, timeoutSeconds, disableBufferingValue, noSymbolsValue, noServiceEndpoint, getLogger()); } catch (TaskCanceledException ex) { throw new AggregateException(ex, new Exception(Strings.Push_Timeout_Error)); } return(0); }); }); }
public static void Register(CommandLineApplication app, Func <ILogger> getLogger) { app.Command("delete", delete => { delete.Description = Strings.Delete_Description; delete.HelpOption(XPlatUtility.HelpOption); delete.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var source = delete.Option( "-s|--source <source>", Strings.Source_Description, CommandOptionType.SingleValue); var nonInteractive = delete.Option( "--non-interactive", Strings.NonInteractive_Description, CommandOptionType.NoValue); var apikey = delete.Option( "-k|--api-key <apiKey>", Strings.ApiKey_Description, CommandOptionType.SingleValue); var arguments = delete.Argument( "[root]", Strings.Delete_PackageIdAndVersion_Description, multipleValues: true); var noServiceEndpointDescription = delete.Option( "--no-service-endpoint", Strings.NoServiceEndpoint_Description, CommandOptionType.NoValue); delete.OnExecute(async() => { if (arguments.Values.Count < 2) { throw new ArgumentException(Strings.Delete_MissingArguments); } string packageId = arguments.Values[0]; string packageVersion = arguments.Values[1]; string sourcePath = source.Value(); string apiKeyValue = apikey.Value(); bool nonInteractiveValue = nonInteractive.HasValue(); bool noServiceEndpoint = noServiceEndpointDescription.HasValue(); PackageSourceProvider sourceProvider = new PackageSourceProvider(XPlatUtility.CreateDefaultSettings()); await DeleteRunner.Run( sourceProvider.Settings, sourceProvider, packageId, packageVersion, sourcePath, apiKeyValue, nonInteractiveValue, noServiceEndpoint, Confirm, getLogger()); return(0); }); }); }
/// <summary> /// Internal Main. This is used for testing. /// </summary> public static int MainInternal(string[] args, CommandOutputLogger log) { #if DEBUG var debugNuGetXPlat = Environment.GetEnvironmentVariable("DEBUG_NUGET_XPLAT"); if (args.Contains(DebugOption) || string.Equals(bool.TrueString, debugNuGetXPlat, StringComparison.OrdinalIgnoreCase)) { args = args.Where(arg => !StringComparer.OrdinalIgnoreCase.Equals(arg, DebugOption)).ToArray(); Console.WriteLine("Waiting for debugger to attach."); Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}"); while (!Debugger.IsAttached) { System.Threading.Thread.Sleep(100); } Debugger.Break(); } #endif // Optionally disable localization. if (args.Any(arg => string.Equals(arg, CommandConstants.ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase))) { CultureUtility.DisableLocalization(); } var app = InitializeApp(args); args = args .Where(e => e != "package") .ToArray(); var verbosity = app.Option(XPlatUtility.VerbosityOption, Strings.Switch_Verbosity, CommandOptionType.SingleValue); // Options aren't parsed until we call app.Execute(), so look directly for the verbosity option ourselves LogLevel logLevel; TryParseVerbosity(args, verbosity, out logLevel); log.LogLevel = logLevel; NetworkProtocolUtility.SetConnectionLimit(); XPlatUtility.SetUserAgent(); // This method has no effect on .NET Core. NetworkProtocolUtility.ConfigureSupportedSslProtocols(); // Register commands RegisterCommands(app, log); app.OnExecute(() => { app.ShowHelp(); return(0); }); log.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.OutputNuGetVersion, app.FullName, app.LongVersionGetter())); int exitCode = 0; try { exitCode = app.Execute(args); } catch (Exception e) { // Log the error if (ExceptionLogger.Instance.ShowStack) { log.LogError(e.ToString()); } else { log.LogError(ExceptionUtilities.DisplayMessage(e)); } // Log the stack trace as verbose output. log.LogVerbose(e.ToString()); exitCode = 1; } // Limit the exit code range to 0-255 to support POSIX if (exitCode < 0 || exitCode > 255) { exitCode = 1; } return(exitCode); }
public static void Register(CommandLineApplication app, Func <ILogger> getLogger) { app.Command("pack", pack => { pack.Description = Strings.PackCommand_Description; pack.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var basePath = pack.Option( "-b|--base-path <basePath>", Strings.BasePath_Description, CommandOptionType.SingleValue); var build = pack.Option( "--build", Strings.Build_Description, CommandOptionType.NoValue); var exclude = pack.Option( "--exclude", Strings.Exclude_Description, CommandOptionType.MultipleValue); var excludeEmpty = pack.Option( "-e|--exclude-empty-directories", Strings.ExcludeEmptyDirectories_Description, CommandOptionType.NoValue); var minClientVersion = pack.Option( "--min-client-version <version>", Strings.MinClientVersion_Description, CommandOptionType.SingleValue); var noDefaultExcludes = pack.Option( "--no-default-excludes", Strings.NoDefaultExcludes_Description, CommandOptionType.NoValue); var noPackageAnalysis = pack.Option( "--no-package-analysis", Strings.NoPackageAnalysis_Description, CommandOptionType.NoValue); var outputDirectory = pack.Option( "-o|--output-directory <outputDirectory>", Strings.OutputDirectory_Description, CommandOptionType.SingleValue); var properties = pack.Option( "-p|--properties <properties>", Strings.OutputDirectory_Description, CommandOptionType.SingleValue); var suffix = pack.Option( "--suffix <suffix>", Strings.Suffix_Description, CommandOptionType.SingleValue); var symbols = pack.Option( "-s|--symbols", Strings.Symbols_Description, CommandOptionType.NoValue); var verbosity = pack.Option( "--verbosity <level>", Strings.Switch_Verbosity, CommandOptionType.SingleValue); var versionOption = pack.Option( "-v|--version <version>", Strings.Version_Description, CommandOptionType.SingleValue); var arguments = pack.Argument( "nuspec or project.json file", Strings.InputFile_Description, multipleValues: true); pack.OnExecute(() => { var logger = getLogger(); var packArgs = new PackArgs(); packArgs.Logger = logger; packArgs.Arguments = arguments.Values; packArgs.Path = PackCommandRunner.GetInputFile(packArgs); // Set the current directory if the files being packed are in a different directory PackCommandRunner.SetupCurrentDirectory(packArgs); logger.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.PackageCommandAttemptingToBuildPackage, Path.GetFileName(packArgs.Path))); // If the BasePath is not specified, use the directory of the input file (nuspec / proj) file packArgs.BasePath = !basePath.HasValue() ? Path.GetDirectoryName(Path.GetFullPath(packArgs.Path)) : basePath.Value(); packArgs.BasePath = packArgs.BasePath.TrimEnd(Path.DirectorySeparatorChar); packArgs.Build = build.HasValue(); packArgs.Exclude = exclude.Values; packArgs.ExcludeEmptyDirectories = excludeEmpty.HasValue(); packArgs.LogLevel = XPlatUtility.GetLogLevel(verbosity); if (minClientVersion.HasValue()) { Version version; if (!Version.TryParse(minClientVersion.Value(), out version)) { throw new ArgumentException(Strings.PackageCommandInvalidMinClientVersion); } packArgs.MinClientVersion = version; } packArgs.MachineWideSettings = new CommandLineXPlatMachineWideSetting(); packArgs.MsBuildDirectory = new Lazy <string>(() => string.Empty); packArgs.NoDefaultExcludes = noDefaultExcludes.HasValue(); packArgs.NoPackageAnalysis = noPackageAnalysis.HasValue(); packArgs.OutputDirectory = outputDirectory.Value(); if (properties.HasValue()) { foreach (var property in properties.Value().Split(';')) { int index = property.IndexOf('='); if (index > 0 && index < property.Length - 1) { packArgs.Properties.Add(property.Substring(0, index), property.Substring(index + 1)); } } } packArgs.Suffix = suffix.Value(); packArgs.Symbols = symbols.HasValue(); if (versionOption.HasValue()) { NuGetVersion version; if (!NuGetVersion.TryParse(versionOption.Value(), out version)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.PackageVersionInvalid, versionOption.Value())); } packArgs.Version = version.ToNormalizedString(); } PackCommandRunner packCommandRunner = new PackCommandRunner(packArgs, null); packCommandRunner.BuildPackage(); return(0); }); }); }
internal static void Register(CommandLineApplication app, Func <ILogger> getLogger, Action <LogLevel> setLogLevel, Func <ISignCommandRunner> getCommandRunner) { app.Command(CommandName, signCmd => { CommandArgument packagePaths = signCmd.Argument( "<package-paths>", Strings.SignCommandPackagePathDescription, multipleValues: true); CommandOption outputDirectory = signCmd.Option( "-o|--output", Strings.SignCommandOutputDirectoryDescription, CommandOptionType.SingleValue); CommandOption path = signCmd.Option( "--certificate-path", Strings.SignCommandCertificatePathDescription, CommandOptionType.SingleValue); CommandOption store = signCmd.Option( "--certificate-store-name", Strings.SignCommandCertificateStoreNameDescription, CommandOptionType.SingleValue); CommandOption location = signCmd.Option( "--certificate-store-location", Strings.SignCommandCertificateStoreLocationDescription, CommandOptionType.SingleValue); CommandOption subject = signCmd.Option( "--certificate-subject-name", Strings.SignCommandCertificateSubjectNameDescription, CommandOptionType.SingleValue); CommandOption fingerprint = signCmd.Option( "--certificate-fingerprint", Strings.SignCommandCertificateFingerprintDescription, CommandOptionType.SingleValue); CommandOption password = signCmd.Option( "--certificate-password", Strings.SignCommandCertificatePasswordDescription, CommandOptionType.SingleValue); CommandOption algorithm = signCmd.Option( "--hash-algorithm", Strings.SignCommandHashAlgorithmDescription, CommandOptionType.SingleValue); CommandOption timestamper = signCmd.Option( "--timestamper", Strings.SignCommandTimestamperDescription, CommandOptionType.SingleValue); CommandOption timestamperAlgorithm = signCmd.Option( "--timestamp-hash-algorithm", Strings.SignCommandTimestampHashAlgorithmDescription, CommandOptionType.SingleValue); CommandOption overwrite = signCmd.Option( "--overwrite", Strings.SignCommandOverwriteDescription, CommandOptionType.NoValue); CommandOption verbosity = signCmd.Option( "-v|--verbosity", Strings.Verbosity_Description, CommandOptionType.SingleValue); signCmd.HelpOption(XPlatUtility.HelpOption); signCmd.Description = Strings.SignCommandDescription; signCmd.OnExecute(async() => { ILogger logger = getLogger(); ValidatePackagePaths(packagePaths); WarnIfNoTimestamper(logger, timestamper); ValidateCertificateInputs(path, fingerprint, subject, store, location); ValidateAndCreateOutputDirectory(outputDirectory); SigningSpecificationsV1 signingSpec = SigningSpecifications.V1; StoreLocation storeLocation = ValidateAndParseStoreLocation(location); StoreName storeName = ValidateAndParseStoreName(store); HashAlgorithmName hashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(algorithm.Value(), algorithm.LongName, signingSpec); HashAlgorithmName timestampHashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(timestamperAlgorithm.Value(), timestamperAlgorithm.LongName, signingSpec); var args = new SignArgs() { PackagePaths = packagePaths.Values, OutputDirectory = outputDirectory.Value(), CertificatePath = path.Value(), CertificateStoreName = storeName, CertificateStoreLocation = storeLocation, CertificateSubjectName = subject.Value(), CertificateFingerprint = fingerprint.Value(), CertificatePassword = password.Value(), SignatureHashAlgorithm = hashAlgorithm, Logger = logger, Overwrite = overwrite.HasValue(), //The interactive option is not enabled at first, so the NonInteractive is always set to true. This is tracked by https://github.com/NuGet/Home/issues/10620 NonInteractive = true, Timestamper = timestamper.Value(), TimestampHashAlgorithm = timestampHashAlgorithm }; setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value())); ISignCommandRunner runner = getCommandRunner(); int result = await runner.ExecuteCommandAsync(args); return(result); }); }); }
public static void Register(CommandLineApplication app, Func <ILogger> getLogger) { app.Command("delete", delete => { delete.Description = Strings.Delete_Description; delete.HelpOption(XPlatUtility.HelpOption); delete.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var source = delete.Option( "-s|--source <source>", Strings.Source_Description, CommandOptionType.SingleValue); var nonInteractive = delete.Option( "--non-interactive", Strings.NonInteractive_Description, CommandOptionType.NoValue); var apikey = delete.Option( "-k|--api-key <apiKey>", Strings.ApiKey_Description, CommandOptionType.SingleValue); var arguments = delete.Argument( "[root]", Strings.Delete_PackageIdAndVersion_Description, multipleValues: true); var noServiceEndpointDescription = delete.Option( "--no-service-endpoint", Strings.NoServiceEndpoint_Description, CommandOptionType.NoValue); var interactive = delete.Option( "--interactive", Strings.NuGetXplatCommand_Interactive, CommandOptionType.NoValue); delete.OnExecute(async() => { if (arguments.Values.Count < 2) { throw new ArgumentException(Strings.Delete_MissingArguments); } string packageId = arguments.Values[0]; string packageVersion = arguments.Values[1]; string sourcePath = source.Value(); string apiKeyValue = apikey.Value(); bool nonInteractiveValue = nonInteractive.HasValue(); bool noServiceEndpoint = noServiceEndpointDescription.HasValue(); DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue()); #pragma warning disable CS0618 // Type or member is obsolete PackageSourceProvider sourceProvider = new PackageSourceProvider(XPlatUtility.GetSettingsForCurrentWorkingDirectory(), enablePackageSourcesChangedEvent: false); #pragma warning restore CS0618 // Type or member is obsolete await DeleteRunner.Run( sourceProvider.Settings, sourceProvider, packageId, packageVersion, sourcePath, apiKeyValue, nonInteractiveValue, noServiceEndpoint, Confirm, getLogger()); return(0); }); }); }
private static async Task <int> ExecuteCommand(TrustCommand action, CommandOption algorithm, bool allowUntrustedRootOption, CommandOption owners, CommandOption verbosity, CommandOption configFile, Func <ILogger> getLogger, Action <LogLevel> setLogLevel, string name = null, string sourceUrl = null, string packagePath = null, string fingerprint = null) { ILogger logger = getLogger(); try { ISettings settings = XPlatUtility.ProcessConfigFile(configFile.Value()); var trustedSignersArgs = new TrustedSignersArgs() { Action = MapTrustEnumAction(action), PackagePath = packagePath, Name = name, ServiceIndex = sourceUrl, CertificateFingerprint = fingerprint, FingerprintAlgorithm = algorithm?.Value(), AllowUntrustedRoot = allowUntrustedRootOption, Author = action == TrustCommand.Author, Repository = action == TrustCommand.Repository, Owners = CommandLineUtility.SplitAndJoinAcrossMultipleValues(owners?.Values), Logger = logger }; setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value())); // Add is the only action which does certificate chain building. if (trustedSignersArgs.Action == TrustedSignersAction.Add) { X509TrustStore.InitializeForDotNetSdk(logger); } #pragma warning disable CS0618 // Type or member is obsolete var sourceProvider = new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false); #pragma warning restore CS0618 // Type or member is obsolete var trustedSignersProvider = new TrustedSignersProvider(settings); var runner = new TrustedSignersCommandRunner(trustedSignersProvider, sourceProvider); Task <int> trustedSignTask = runner.ExecuteCommandAsync(trustedSignersArgs); return(await trustedSignTask); } catch (InvalidOperationException e) { // nuget trust command handled exceptions. if (!string.IsNullOrWhiteSpace(name)) { var error_TrustedSignerAlreadyExistsMessage = string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustedSignerAlreadyExists, name); if (e.Message == error_TrustedSignerAlreadyExistsMessage) { logger.LogError(error_TrustedSignerAlreadyExistsMessage); return(1); } } if (!string.IsNullOrWhiteSpace(sourceUrl)) { var error_TrustedRepoAlreadyExists = string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustedRepoAlreadyExists, sourceUrl); if (e.Message == error_TrustedRepoAlreadyExists) { logger.LogError(error_TrustedRepoAlreadyExists); return(1); } } throw; } catch (ArgumentException e) { if (e.Data is System.Collections.IDictionary) { logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustFingerPrintAlreadyExist)); return(1); } throw; } }
internal static void Register(CommandLineApplication app, Func <ILogger> getLogger, Action <LogLevel> setLogLevel) { app.Command("trust", trustedSignersCmd => { CommandArgument command = trustedSignersCmd.Argument( "<command>", Strings.TrustCommandActionDescription, multipleValues: true); CommandOption algorithm = trustedSignersCmd.Option( "--algorithm", Strings.TrustCommandAlgorithm, CommandOptionType.SingleValue); CommandOption allowUntrustedRootOption = trustedSignersCmd.Option( "--allow-untrusted-root", Strings.TrustCommandAllowUntrustedRoot, CommandOptionType.NoValue); CommandOption owners = trustedSignersCmd.Option( "--owners", Strings.TrustCommandOwners, CommandOptionType.MultipleValue); CommandOption verbosity = trustedSignersCmd.Option( "-v|--verbosity", Strings.Verbosity_Description, CommandOptionType.SingleValue); CommandOption configFile = trustedSignersCmd.Option( "--configfile", Strings.Option_ConfigFile, CommandOptionType.SingleValue); trustedSignersCmd.HelpOption(XPlatUtility.HelpOption); trustedSignersCmd.Description = Strings.TrustCommandDescription; trustedSignersCmd.OnExecute(async() => { TrustCommand action; if (!command.Values.Any() || string.IsNullOrEmpty(command.Values[0])) { action = TrustCommand.List; } else if (!Enum.TryParse(command.Values[0], ignoreCase: true, result: out action)) { throw new CommandLineArgumentCombinationException(string.Format(CultureInfo.CurrentCulture, Strings.Error_UnknownAction, command.Values[0])); } string name = null; if (command.Values.Count > 1) { name = command.Values[1]; } string packagePath = null; string sourceUrl = null; string fingerprint = null; if (command.Values.Count() > 2) { if (action == TrustCommand.Author || action == TrustCommand.Repository) { packagePath = command.Values[2]; } else if (action == TrustCommand.Source) { sourceUrl = command.Values[2]; } else if (action == TrustCommand.Certificate) { fingerprint = command.Values[2]; } } ISettings settings = ProcessConfigFile(configFile.Value()); var trustedSignersArgs = new TrustedSignersArgs() { Action = MapTrustEnumAction(action), PackagePath = packagePath, Name = name, ServiceIndex = sourceUrl, CertificateFingerprint = fingerprint, FingerprintAlgorithm = algorithm.Value(), AllowUntrustedRoot = allowUntrustedRootOption.HasValue(), Author = action == TrustCommand.Author, Repository = action == TrustCommand.Repository, Owners = CommandLineUtility.SplitAndJoinAcrossMultipleValues(owners.Values), Logger = getLogger() }; setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value())); #pragma warning disable CS0618 // Type or member is obsolete var sourceProvider = new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false); #pragma warning restore CS0618 // Type or member is obsolete var trustedSignersProvider = new TrustedSignersProvider(settings); var runner = new TrustedSignersCommandRunner(trustedSignersProvider, sourceProvider); Task <int> trustedSignTask = runner.ExecuteCommandAsync(trustedSignersArgs); return(await trustedSignTask); }); }); }
public static void Register( CommandLineApplication cmdApp, Func <CommandOutputLogger> getLogger) { cmdApp.Command("restore", (Action <CommandLineApplication>)(restore => { restore.Description = Strings.Restore_Description; restore.HelpOption(XPlatUtility.HelpOption); restore.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var sources = restore.Option( "-s|--source <source>", Strings.Restore_Switch_Source_Description, CommandOptionType.MultipleValue); var packagesDirectory = restore.Option( "--packages <packagesDirectory>", Strings.Restore_Switch_Packages_Description, CommandOptionType.SingleValue); var disableParallel = restore.Option( "--disable-parallel", Strings.Restore_Switch_DisableParallel_Description, CommandOptionType.NoValue); var fallBack = restore.Option( "-f|--fallbacksource <FEED>", Strings.Restore_Switch_Fallback_Description, CommandOptionType.MultipleValue); var configFile = restore.Option( "--configfile <file>", Strings.Restore_Switch_ConfigFile_Description, CommandOptionType.SingleValue); var noCache = restore.Option( "--no-cache", Strings.Restore_Switch_NoCache_Description, CommandOptionType.NoValue); var inferRuntimes = restore.Option( "--infer-runtimes", "Temporary option to allow NuGet to infer RIDs for legacy repositories", CommandOptionType.NoValue); var verbosity = restore.Option( XPlatUtility.VerbosityOption, Strings.Switch_Verbosity, CommandOptionType.SingleValue); var argRoot = restore.Argument( "[root]", Strings.Restore_Arg_ProjectName_Description, multipleValues: true); var ignoreFailedSources = restore.Option( "--ignore-failed-sources", Strings.Restore_Switch_IgnoreFailedSource_Description, CommandOptionType.NoValue); restore.OnExecute(async() => { var log = getLogger(); if (verbosity.HasValue()) { log.LogLevel = XPlatUtility.GetLogLevel(verbosity); } using (var cacheContext = new SourceCacheContext()) { cacheContext.NoCache = noCache.HasValue(); cacheContext.IgnoreFailedSources = ignoreFailedSources.HasValue(); var providerCache = new RestoreCommandProvidersCache(); // Ordered request providers var providers = new List <IRestoreRequestProvider>(); providers.Add(new MSBuildP2PRestoreRequestProvider(providerCache)); providers.Add(new ProjectJsonRestoreRequestProvider(providerCache)); ISettings defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null); CachingSourceProvider sourceProvider = new CachingSourceProvider(new PackageSourceProvider(defaultSettings)); var restoreContext = new RestoreArgs() { CacheContext = cacheContext, LockFileVersion = LockFileFormat.Version, ConfigFile = configFile.HasValue() ? configFile.Value() : null, DisableParallel = disableParallel.HasValue(), GlobalPackagesFolder = packagesDirectory.HasValue() ? packagesDirectory.Value() : null, Inputs = new List <string>(argRoot.Values), Log = log, MachineWideSettings = new XPlatMachineWideSetting(), RequestProviders = providers, Sources = sources.Values, FallbackSources = fallBack.Values, CachingSourceProvider = sourceProvider }; if (inferRuntimes.HasValue()) { var runtimeOSname = PlatformApis.GetRuntimeOsName(); var os = PlatformApis.GetOSName(); var defaultRuntimes = RequestRuntimeUtility.GetDefaultRestoreRuntimes(os, runtimeOSname); restoreContext.FallbackRuntimes.UnionWith(defaultRuntimes); } if (restoreContext.DisableParallel) { HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore(); } var restoreSummaries = await RestoreRunner.Run(restoreContext); // Summary RestoreSummary.Log(log, restoreSummaries); return(restoreSummaries.All(x => x.Success) ? 0 : 1); } }); })); }
public static void Register(CommandLineApplication app, Func <ILogger> getLogger) { app.Command("locals", locals => { locals.Description = Strings.LocalsCommand_Description; locals.HelpOption(XPlatUtility.HelpOption); locals.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var clear = locals.Option( "-c|--clear", Strings.LocalsCommand_ClearDescription, CommandOptionType.NoValue); var list = locals.Option( "-l|--list", Strings.LocalsCommand_ListDescription, CommandOptionType.NoValue); var arguments = locals.Argument( "Cache Location(s)", Strings.LocalsCommand_ArgumentDescription, multipleValues: false); locals.OnExecute(() => { var logger = getLogger(); var setting = XPlatUtility.GetSettingsForCurrentWorkingDirectory(); // Using both -clear and -list command options, or neither one of them, is not supported. // We use MinArgs = 0 even though the first argument is required, // to avoid throwing a command argument validation exception and // immediately show usage help for this command instead. if ((arguments.Values.Count < 1) || string.IsNullOrWhiteSpace(arguments.Values[0])) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_NoArguments)); } else if (clear.HasValue() && list.HasValue()) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_MultipleOperations)); } else if (!clear.HasValue() && !list.HasValue()) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_NoOperation)); } else { var localsArgs = new LocalsArgs(arguments.Values, setting, logger.LogInformation, logger.LogError, clear.HasValue(), list.HasValue()); var localsCommandRunner = new LocalsCommandRunner(); localsCommandRunner.ExecuteCommand(localsArgs); } return(0); }); }); }
/// <summary> /// Internal Main. This is used for testing. /// </summary> public static int MainInternal(string[] args, CommandOutputLogger log) { #if DEBUG try { // .NET JIT compiles one method at a time. If this method calls `MSBuildLocator` directly, the // try block is never entered if Microsoft.Build.Locator.dll can't be found. So, run it in a // lambda function to ensure we're in the try block. C# IIFE! ((Action)(() => MSBuildLocator.RegisterDefaults()))(); } catch { // MSBuildLocator is used only to enable Visual Studio debugging. // It's not needed when using a patched dotnet sdk, so it doesn't matter if it fails. } var debugNuGetXPlat = Environment.GetEnvironmentVariable("DEBUG_NUGET_XPLAT"); if (args.Contains(DebugOption) || string.Equals(bool.TrueString, debugNuGetXPlat, StringComparison.OrdinalIgnoreCase)) { args = args.Where(arg => !StringComparer.OrdinalIgnoreCase.Equals(arg, DebugOption)).ToArray(); Debugger.Launch(); } #endif // Optionally disable localization. if (args.Any(arg => string.Equals(arg, CommandConstants.ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase))) { CultureUtility.DisableLocalization(); } var app = InitializeApp(args, log); // Remove the correct item in array for "package" commands. Only do this when "add package", "remove package", etc... are being run. if (app.Name == DotnetPackageAppName) { // package add ... args[0] = null; args = args .Where(e => e != null) .ToArray(); } NetworkProtocolUtility.SetConnectionLimit(); XPlatUtility.SetUserAgent(); app.OnExecute(() => { app.ShowHelp(); return(0); }); log.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.OutputNuGetVersion, app.FullName, app.LongVersionGetter())); int exitCode = 0; try { exitCode = app.Execute(args); } catch (Exception e) { bool handled = false; string verb = null; if (args.Length > 1) { // Redirect users nicely if they do 'dotnet nuget sources add' or 'dotnet nuget add sources' if (StringComparer.OrdinalIgnoreCase.Compare(args[0], "sources") == 0) { verb = args[1]; } else if (StringComparer.OrdinalIgnoreCase.Compare(args[1], "sources") == 0) { verb = args[0]; } if (verb != null) { switch (verb.ToLowerInvariant()) { case "add": case "remove": case "update": case "enable": case "disable": case "list": log.LogMinimal(string.Format(CultureInfo.CurrentCulture, Strings.Sources_Redirect, $"dotnet nuget {verb} source")); handled = true; break; default: break; } } } if (!handled) { // Log the error if (ExceptionLogger.Instance.ShowStack) { log.LogError(e.ToString()); } else { log.LogError(ExceptionUtilities.DisplayMessage(e)); } // Log the stack trace as verbose output. log.LogVerbose(e.ToString()); exitCode = 1; ShowBestHelp(app, args); } } // Limit the exit code range to 0-255 to support POSIX if (exitCode < 0 || exitCode > 255) { exitCode = 1; } return(exitCode); }
public static void Register( CommandLineApplication app, Func <ILogger> getLogger, Action <LogLevel> setLogLevel, Func <IListPackageCommandRunner> getCommandRunner) { app.Command("list", listpkg => { listpkg.Description = Strings.ListPkg_Description; listpkg.HelpOption(XPlatUtility.HelpOption); listpkg.Option( CommandConstants.ForceEnglishOutputOption, Strings.ForceEnglishOutput_Description, CommandOptionType.NoValue); var path = listpkg.Argument( "<PROJECT | SOLUTION>", Strings.ListPkg_PathDescription, multipleValues: false); var framework = listpkg.Option( "--framework", Strings.ListPkg_FrameworkDescription, CommandOptionType.MultipleValue); var deprecatedReport = listpkg.Option( "--deprecated", Strings.ListPkg_DeprecatedDescription, CommandOptionType.NoValue); var outdatedReport = listpkg.Option( "--outdated", Strings.ListPkg_OutdatedDescription, CommandOptionType.NoValue); var vulnerableReport = listpkg.Option( "--vulnerable", Strings.ListPkg_VulnerableDescription, CommandOptionType.NoValue); var includeTransitive = listpkg.Option( "--include-transitive", Strings.ListPkg_TransitiveDescription, CommandOptionType.NoValue); var prerelease = listpkg.Option( "--include-prerelease", Strings.ListPkg_PrereleaseDescription, CommandOptionType.NoValue); var highestPatch = listpkg.Option( "--highest-patch", Strings.ListPkg_HighestPatchDescription, CommandOptionType.NoValue); var highestMinor = listpkg.Option( "--highest-minor", Strings.ListPkg_HighestMinorDescription, CommandOptionType.NoValue); var source = listpkg.Option( "--source", Strings.ListPkg_SourceDescription, CommandOptionType.MultipleValue); var config = listpkg.Option( "--config", Strings.ListPkg_ConfigDescription, CommandOptionType.SingleValue); var interactive = listpkg.Option( "--interactive", Strings.NuGetXplatCommand_Interactive, CommandOptionType.NoValue); var verbosity = listpkg.Option( "-v|--verbosity", Strings.Verbosity_Description, CommandOptionType.SingleValue); listpkg.OnExecute(async() => { var logger = getLogger(); setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value())); var settings = ProcessConfigFile(config.Value(), path.Value); var sources = source.Values; var packageSources = GetPackageSources(settings, sources, config); VerifyValidFrameworks(framework); var reportType = GetReportType( isOutdated: outdatedReport.HasValue(), isDeprecated: deprecatedReport.HasValue(), isVulnerable: vulnerableReport.HasValue()); var packageRefArgs = new ListPackageArgs( path.Value, packageSources, framework.Values, reportType, includeTransitive.HasValue(), prerelease.HasValue(), highestPatch.HasValue(), highestMinor.HasValue(), logger, CancellationToken.None); DisplayMessages(packageRefArgs); DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue()); var listPackageCommandRunner = getCommandRunner(); await listPackageCommandRunner.ExecuteCommandAsync(packageRefArgs); return(0); }); }); }