Beispiel #1
0
        /// <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);
        }
Beispiel #2
0
        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("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);
                });
            });
        }