예제 #1
0
        public void ExceptionShouldBeSentToTelemetry()
        {
            Exception caughtException = null;

            try
            {
                string[] args = { "build" };
                Cli.Program.ProcessArgs(args);
                throw new ArgumentException("test exception");
            }
            catch (Exception ex)
            {
                caughtException = ex;
                TelemetryEventEntry.SendFiltered(ex);
            }

            var exception = new Exception();

            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "mainCatchException/exception" &&
                     e.Properties.ContainsKey("exceptionType") &&
                     e.Properties["exceptionType"] == "System.ArgumentException" &&
                     e.Properties.ContainsKey("detail") &&
                     e.Properties["detail"].Contains(caughtException.StackTrace));
        }
예제 #2
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            new MulticoreJitActivator().TryActivateMulticoreJit();

            if (Env.GetEnvironmentVariableAsBool("DOTNET_CLI_CAPTURE_TIMING", false))
            {
                PerfTrace.Enabled = true;
            }

            InitializeProcess();

            try
            {
                using (PerfTrace.Current.CaptureTiming())
                {
                    return(ProcessArgs(args));
                }
            }
            catch (HelpException e)
            {
                Reporter.Output.WriteLine(e.Message);
                return(0);
            }
            catch (Exception e) when(e.ShouldBeDisplayedAsError())
            {
                Reporter.Error.WriteLine(CommandContext.IsVerbose()
                    ? e.ToString().Red().Bold()
                    : e.Message.Red().Bold());

                var commandParsingException = e as CommandParsingException;

                if (commandParsingException != null)
                {
                    Reporter.Output.WriteLine(commandParsingException.HelpText);
                }

                return(1);
            }
            catch (Exception e) when(!e.ShouldBeDisplayedAsError())
            {
                // If telemetry object has not been initialized yet. It cannot be collected
                TelemetryEventEntry.SendFiltered(e);
                Reporter.Error.WriteLine(e.ToString().Red().Bold());

                return(1);
            }
            finally
            {
                if (PerfTrace.Enabled)
                {
                    Reporter.Output.WriteLine("Performance Summary:");
                    PerfTraceOutput.Print(Reporter.Output, PerfTrace.GetEvents());
                }
            }
        }
        public void TopLevelCommandNameShouldBeSentToTelemetryWithoutPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "build"
            });

            TelemetryEventEntry.SendFiltered(parseResult);
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "toplevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("BUILD") &&
                                                       e.Measurement == null);
        }
        public void TopLevelCommandNameShouldBeSentToTelemetryWithZeroPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "build"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult, new Dictionary <string, double>()
            {
                { "Startup Time", 0 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "toplevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("BUILD") &&
                                                       e.Measurement == null);
        }
        public void SubLevelCommandNameShouldBeSentToTelemetryWithoutPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "new", "console"
            });

            TelemetryEventEntry.SendFiltered(parseResult);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey("argument") &&
                     e.Properties["argument"] == Sha256Hasher.Hash("CONSOLE") &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("NEW") &&
                     e.Measurement == null);
        }
예제 #6
0
        public void WhenCalledWithMissingArgumentWorkloadSubLevelCommandNameAndArgumentShouldBeSentToTelemetry()
        {
            var parseResult =
                Parser.Instance.Parse(new List <string>()
            {
                "-d", "workload", "install"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult,
                                                          new Dictionary <string, double>()
            {
                { "Startup Time", 0 }, { "Parse Time", 23456 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "sublevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("WORKLOAD") &&
                                                       e.Properties["subcommand"] ==
                                                       Sha256Hasher.Hash("INSTALL"));
        }
        public void SubLevelCommandNameShouldBeSentToTelemetryWithPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "new", "console"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult, new Dictionary <string, double>()
            {
                { "Startup Time", 34567 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "sublevelparser/command" &&
                                                       e.Properties.ContainsKey("argument") &&
                                                       e.Properties["argument"] == Sha256Hasher.Hash("CONSOLE") &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("NEW") &&
                                                       e.Measurement.ContainsKey("Startup Time") &&
                                                       e.Measurement["Startup Time"] == 34567);
        }
예제 #8
0
        public void ToolsSubLevelCommandNameAndArgumentShouldBeSentToTelemetry()
        {
            var parseResult =
                Parser.Instance.Parse(new List <string>()
            {
                "tool", "install", "dotnet-format"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult,
                                                          new Dictionary <string, double>()
            {
                { "Startup Time", 0 }, { "Parse Time", 23456 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "sublevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("TOOL") &&
                                                       e.Properties["subcommand"] ==
                                                       Sha256Hasher.Hash("INSTALL") &&
                                                       e.Properties["argument"] ==
                                                       Sha256Hasher.Hash("DOTNET-FORMAT"));
        }
예제 #9
0
 public TelemetryCommandTests()
 {
     _fakeTelemetry = new FakeRecordEventNameTelemetry();
     TelemetryEventEntry.Subscribe(_fakeTelemetry.TrackEvent);
     TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
 }
예제 #10
0
파일: Program.cs 프로젝트: baronfel/sdk
        public static int Main(string[] args)
        {
            //setting output encoding is not available on those platforms
            if (!OperatingSystem.IsIOS() && !OperatingSystem.IsAndroid() && !OperatingSystem.IsTvOS())
            {
                //if output is redirected, force encoding to utf-8;
                //otherwise the caller may not decode it correctly
                if (Console.IsOutputRedirected)
                {
                    Console.OutputEncoding = Encoding.UTF8;
                }
            }

            DebugHelper.HandleDebugSwitch(ref args);

            // Capture the current timestamp to calculate the host overhead.
            DateTime mainTimeStamp = DateTime.Now;
            TimeSpan startupTime   = mainTimeStamp - Process.GetCurrentProcess().StartTime;

            bool perfLogEnabled = Env.GetEnvironmentVariableAsBool("DOTNET_CLI_PERF_LOG", false);

            // Avoid create temp directory with root permission and later prevent access in non sudo
            if (SudoEnvironmentDirectoryOverride.IsRunningUnderSudo())
            {
                perfLogEnabled = false;
            }

            PerformanceLogStartupInformation startupInfo = null;

            if (perfLogEnabled)
            {
                startupInfo = new PerformanceLogStartupInformation(mainTimeStamp);
                PerformanceLogManager.InitializeAndStartCleanup(FileSystemWrapper.Default);
            }

            PerformanceLogEventListener perLogEventListener = null;

            try
            {
                if (perfLogEnabled)
                {
                    perLogEventListener = PerformanceLogEventListener.Create(FileSystemWrapper.Default, PerformanceLogManager.Instance.CurrentLogDirectory);
                }

                PerformanceLogEventSource.Log.LogStartUpInformation(startupInfo);
                PerformanceLogEventSource.Log.CLIStart();

                InitializeProcess();

                try
                {
                    return(ProcessArgs(args, startupTime));
                }
                catch (HelpException e)
                {
                    Reporter.Output.WriteLine(e.Message);
                    return(0);
                }
                catch (Exception e) when(e.ShouldBeDisplayedAsError())
                {
                    Reporter.Error.WriteLine(CommandContext.IsVerbose()
                        ? e.ToString().Red().Bold()
                        : e.Message.Red().Bold());

                    var commandParsingException = e as CommandParsingException;

                    if (commandParsingException != null && commandParsingException.ParseResult != null)
                    {
                        commandParsingException.ParseResult.ShowHelp();
                    }

                    return(1);
                }
                catch (Exception e) when(!e.ShouldBeDisplayedAsError())
                {
                    // If telemetry object has not been initialized yet. It cannot be collected
                    TelemetryEventEntry.SendFiltered(e);
                    Reporter.Error.WriteLine(e.ToString().Red().Bold());

                    return(1);
                }
                finally
                {
                    PerformanceLogEventSource.Log.CLIStop();
                }
            }
            finally
            {
                if (perLogEventListener != null)
                {
                    perLogEventListener.Dispose();
                }
            }
        }
예제 #11
0
파일: Program.cs 프로젝트: baronfel/sdk
        internal static int ProcessArgs(string[] args, TimeSpan startupTime, ITelemetry telemetryClient = null)
        {
            Dictionary <string, double> performanceData = new Dictionary <string, double>();

            PerformanceLogEventSource.Log.BuiltInCommandParserStart();
            Stopwatch parseStartTime = Stopwatch.StartNew();
            var       parseResult    = Parser.Instance.Parse(args);

            // Avoid create temp directory with root permission and later prevent access in non sudo
            // This method need to be run very early before temp folder get created
            // https://github.com/dotnet/sdk/issues/20195
            SudoEnvironmentDirectoryOverride.OverrideEnvironmentVariableToTmp(parseResult);

            performanceData.Add("Parse Time", parseStartTime.Elapsed.TotalMilliseconds);
            PerformanceLogEventSource.Log.BuiltInCommandParserStop();

            using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                       new FirstTimeUseNoticeSentinel())
            {
                IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel();
                IFileSentinel toolPathSentinel = new FileSentinel(
                    new FilePath(
                        Path.Combine(
                            CliFolderPathCalculator.DotnetUserProfileFolderPath,
                            ToolPathSentinelFileName)));
                if (parseResult.GetValueForOption(Parser.DiagOption) && parseResult.IsDotnetBuiltInCommand())
                {
                    Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                    CommandContext.SetVerbose(true);
                    Reporter.Reset();
                }
                if (parseResult.HasOption(Parser.VersionOption) && parseResult.IsTopLevelDotnetCommand())
                {
                    CommandLineInfo.PrintVersion();
                    return(0);
                }
                else if (parseResult.HasOption(Parser.InfoOption) && parseResult.IsTopLevelDotnetCommand())
                {
                    CommandLineInfo.PrintInfo();
                    return(0);
                }
                else
                {
                    PerformanceLogEventSource.Log.FirstTimeConfigurationStart();

                    var environmentProvider = new EnvironmentProvider();

                    bool generateAspNetCertificate =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_GENERATE_ASPNET_CERTIFICATE", defaultValue: true);
                    bool telemetryOptout =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", defaultValue: false);
                    bool addGlobalToolsToPath =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", defaultValue: true);
                    bool nologo =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_NOLOGO", defaultValue: false);

                    ReportDotnetHomeUsage(environmentProvider);

                    var isDotnetBeingInvokedFromNativeInstaller = false;
                    if (parseResult.CommandResult.Command.Name.Equals(Parser.InstallSuccessCommand.Name))
                    {
                        aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                        firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                        toolPathSentinel           = new NoOpFileSentinel(exists: false);
                        isDotnetBeingInvokedFromNativeInstaller = true;
                    }

                    var dotnetFirstRunConfiguration = new DotnetFirstRunConfiguration(
                        generateAspNetCertificate: generateAspNetCertificate,
                        telemetryOptout: telemetryOptout,
                        addGlobalToolsToPath: addGlobalToolsToPath,
                        nologo: nologo);

                    ConfigureDotNetForFirstTimeUse(
                        firstTimeUseNoticeSentinel,
                        aspNetCertificateSentinel,
                        toolPathSentinel,
                        isDotnetBeingInvokedFromNativeInstaller,
                        dotnetFirstRunConfiguration,
                        environmentProvider,
                        performanceData);
                    PerformanceLogEventSource.Log.FirstTimeConfigurationStop();
                }

                PerformanceLogEventSource.Log.TelemetryRegistrationStart();

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                }
                TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);

                PerformanceLogEventSource.Log.TelemetryRegistrationStop();
            }

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }
            PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStart();
            performanceData.Add("Startup Time", startupTime.TotalMilliseconds);
            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult, performanceData));
            PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStop();

            int exitCode;

            if (parseResult.CanBeInvoked())
            {
                PerformanceLogEventSource.Log.BuiltInCommandStart();
                exitCode = parseResult.Invoke();
                PerformanceLogEventSource.Log.BuiltInCommandStop();
            }
            else
            {
                PerformanceLogEventSource.Log.ExtensibleCommandResolverStart();
                var resolvedCommand = CommandFactoryUsingResolver.Create(
                    "dotnet-" + parseResult.GetValueForArgument(Parser.DotnetSubCommand),
                    args.GetSubArguments(),
                    FrameworkConstants.CommonFrameworks.NetStandardApp15);
                PerformanceLogEventSource.Log.ExtensibleCommandResolverStop();

                PerformanceLogEventSource.Log.ExtensibleCommandStart();
                var result = resolvedCommand.Execute();
                PerformanceLogEventSource.Log.ExtensibleCommandStop();

                exitCode = result.ExitCode;
            }

            PerformanceLogEventSource.Log.TelemetryClientFlushStart();
            telemetryClient.Flush();
            PerformanceLogEventSource.Log.TelemetryClientFlushStop();

            return(exitCode);
        }
예제 #12
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            // Capture the current timestamp to calculate the host overhead.
            DateTime mainTimeStamp = DateTime.Now;
            TimeSpan startupTime   = mainTimeStamp - Process.GetCurrentProcess().StartTime;

            bool perfLogEnabled = Env.GetEnvironmentVariableAsBool("DOTNET_CLI_PERF_LOG", false);
            PerformanceLogStartupInformation startupInfo = null;

            if (perfLogEnabled)
            {
                startupInfo = new PerformanceLogStartupInformation(mainTimeStamp);
                PerformanceLogManager.InitializeAndStartCleanup(FileSystemWrapper.Default);
            }

            PerformanceLogEventListener perLogEventListener = null;

            try
            {
                if (perfLogEnabled)
                {
                    perLogEventListener = PerformanceLogEventListener.Create(FileSystemWrapper.Default, PerformanceLogManager.Instance.CurrentLogDirectory);
                }

                PerformanceLogEventSource.Log.LogStartUpInformation(startupInfo);
                PerformanceLogEventSource.Log.CLIStart();

                InitializeProcess();

                try
                {
                    return(ProcessArgs(args, startupTime));
                }
                catch (HelpException e)
                {
                    Reporter.Output.WriteLine(e.Message);
                    return(0);
                }
                catch (Exception e) when(e.ShouldBeDisplayedAsError())
                {
                    Reporter.Error.WriteLine(CommandContext.IsVerbose()
                        ? e.ToString().Red().Bold()
                        : e.Message.Red().Bold());

                    var commandParsingException = e as CommandParsingException;

                    if (commandParsingException != null)
                    {
                        Reporter.Output.WriteLine(commandParsingException.HelpText);
                    }

                    return(1);
                }
                catch (Exception e) when(!e.ShouldBeDisplayedAsError())
                {
                    // If telemetry object has not been initialized yet. It cannot be collected
                    TelemetryEventEntry.SendFiltered(e);
                    Reporter.Error.WriteLine(e.ToString().Red().Bold());

                    return(1);
                }
                finally
                {
                    PerformanceLogEventSource.Log.CLIStop();
                }
            }
            finally
            {
                if (perLogEventListener != null)
                {
                    perLogEventListener.Dispose();
                }
            }
        }
 public TelemetryCommandTests()
 {
     _fakeTelemetry = new FakeRecordEventNameTelemetry();
     TelemetryEventEntry.Subscribe(_fakeTelemetry.TrackEvent);
     TelemetryEventEntry.TelemetryFilter = new TelemetryFilter();
 }
 public TelemetryFilterTests(ITestOutputHelper log) : base(log)
 {
     _fakeTelemetry = new FakeRecordEventNameTelemetry();
     TelemetryEventEntry.Subscribe(_fakeTelemetry.TrackEvent);
     TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
 }
예제 #15
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            var success = true;
            var command = string.Empty;
            var lastArg = 0;
            TopLevelCommandParserResult topLevelCommandParserResult = TopLevelCommandParserResult.Empty;

            using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                       new FirstTimeUseNoticeSentinel())
            {
                IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel();
                IFileSentinel toolPathSentinel = new FileSentinel(
                    new FilePath(
                        Path.Combine(
                            CliFolderPathCalculator.DotnetUserProfileFolderPath,
                            ToolPathSentinelFileName)));

                for (; lastArg < args.Length; lastArg++)
                {
                    if (IsArg(args[lastArg], "d", "diagnostics"))
                    {
                        Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                        CommandContext.SetVerbose(true);
                    }
                    else if (IsArg(args[lastArg], "version"))
                    {
                        PrintVersion();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "info"))
                    {
                        PrintInfo();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "h", "help") ||
                             args[lastArg] == "-?" ||
                             args[lastArg] == "/?")
                    {
                        HelpCommand.PrintHelp();
                        return(0);
                    }
                    else if (args[lastArg].StartsWith("-", StringComparison.OrdinalIgnoreCase))
                    {
                        Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                        success = false;
                    }
                    else
                    {
                        // It's the command, and we're done!
                        command = args[lastArg];
                        if (string.IsNullOrEmpty(command))
                        {
                            command = "help";
                        }

                        var environmentProvider = new EnvironmentProvider();

                        bool generateAspNetCertificate =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_GENERATE_ASPNET_CERTIFICATE", true);
                        bool skipFirstRunExperience =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", false);
                        bool telemetryOptout =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", false);

                        ReportDotnetHomeUsage(environmentProvider);

                        topLevelCommandParserResult = new TopLevelCommandParserResult(command);
                        var hasSuperUserAccess = false;
                        if (IsDotnetBeingInvokedFromNativeInstaller(topLevelCommandParserResult))
                        {
                            aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                            firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                            toolPathSentinel           = new NoOpFileSentinel(exists: false);
                            hasSuperUserAccess         = true;

                            // When running through a native installer, we want the cache expansion to happen, so
                            // we need to override this.
                            skipFirstRunExperience = false;
                        }

                        var dotnetFirstRunConfiguration = new DotnetFirstRunConfiguration(
                            generateAspNetCertificate: generateAspNetCertificate,
                            skipFirstRunExperience: skipFirstRunExperience,
                            telemetryOptout: telemetryOptout);

                        ConfigureDotNetForFirstTimeUse(
                            firstTimeUseNoticeSentinel,
                            aspNetCertificateSentinel,
                            toolPathSentinel,
                            hasSuperUserAccess,
                            dotnetFirstRunConfiguration,
                            environmentProvider);

                        break;
                    }
                }
                if (!success)
                {
                    HelpCommand.PrintHelp();
                    return(1);
                }

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                }
                TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
            }

            IEnumerable <string> appArgs =
                (lastArg + 1) >= args.Length
                ? Enumerable.Empty <string>()
                : args.Skip(lastArg + 1).ToArray();

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            TelemetryEventEntry.SendFiltered(topLevelCommandParserResult);

            int exitCode;

            if (BuiltInCommandsCatalog.Commands.TryGetValue(topLevelCommandParserResult.Command, out var builtIn))
            {
                var parseResult = Parser.Instance.ParseFrom($"dotnet {topLevelCommandParserResult.Command}", appArgs.ToArray());
                if (!parseResult.Errors.Any())
                {
                    TelemetryEventEntry.SendFiltered(parseResult);
                }

                exitCode = builtIn.Command(appArgs.ToArray());
            }
            else
            {
                CommandResult result = CommandFactoryUsingResolver.Create(
                    "dotnet-" + topLevelCommandParserResult.Command,
                    appArgs,
                    FrameworkConstants.CommonFrameworks.NetStandardApp15)
                                       .Execute();
                exitCode = result.ExitCode;
            }
            return(exitCode);
        }
예제 #16
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            var success = true;
            var command = string.Empty;
            var lastArg = 0;
            var cliFallbackFolderPathCalculator = new CliFallbackFolderPathCalculator();

            using (INuGetCacheSentinel nugetCacheSentinel = new NuGetCacheSentinel(cliFallbackFolderPathCalculator))
                using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                           new FirstTimeUseNoticeSentinel(cliFallbackFolderPathCalculator))
                {
                    IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                    for (; lastArg < args.Length; lastArg++)
                    {
                        if (IsArg(args[lastArg], "d", "diagnostics"))
                        {
                            Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                            CommandContext.SetVerbose(true);
                        }
                        else if (IsArg(args[lastArg], "version"))
                        {
                            PrintVersion();
                            return(0);
                        }
                        else if (IsArg(args[lastArg], "info"))
                        {
                            PrintInfo();
                            return(0);
                        }
                        else if (IsArg(args[lastArg], "h", "help") ||
                                 args[lastArg] == "-?" ||
                                 args[lastArg] == "/?")
                        {
                            HelpCommand.PrintHelp();
                            return(0);
                        }
                        else if (args[lastArg].StartsWith("-"))
                        {
                            Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                            success = false;
                        }
                        else
                        {
                            // It's the command, and we're done!
                            command = args[lastArg];

                            if (IsDotnetBeingInvokedFromNativeInstaller(command))
                            {
                                firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                            }

                            ConfigureDotNetForFirstTimeUse(
                                nugetCacheSentinel,
                                firstTimeUseNoticeSentinel,
                                cliFallbackFolderPathCalculator);

                            break;
                        }
                    }
                    if (!success)
                    {
                        HelpCommand.PrintHelp();
                        return(1);
                    }

                    if (telemetryClient == null)
                    {
                        telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                    }
                    TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                    TelemetryEventEntry.TelemetryFilter = new TelemetryFilter();
                }

            IEnumerable <string> appArgs =
                (lastArg + 1) >= args.Length
                ? Enumerable.Empty <string>()
                : args.Skip(lastArg + 1).ToArray();

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            if (string.IsNullOrEmpty(command))
            {
                command = "help";
            }

            TelemetryEventEntry.TrackEvent(command, null, null);

            int exitCode;

            if (BuiltInCommandsCatalog.Commands.TryGetValue(command, out var builtIn))
            {
                TelemetryEventEntry.SendFiltered(Parser.Instance.ParseFrom($"dotnet {command}", appArgs.ToArray()));
                exitCode = builtIn.Command(appArgs.ToArray());
            }
            else
            {
                CommandResult result = Command.Create(
                    "dotnet-" + command,
                    appArgs,
                    FrameworkConstants.CommonFrameworks.NetStandardApp15)
                                       .Execute();
                exitCode = result.ExitCode;
            }
            return(exitCode);
        }
예제 #17
0
        internal static int ProcessArgs(string[] args, TimeSpan startupTime, ITelemetry telemetryClient = null)
        {
            Dictionary <string, double> performanceData = new Dictionary <string, double>();

            PerformanceLogEventSource.Log.BuiltInCommandParserStart();
            Stopwatch parseStartTime = Stopwatch.StartNew();
            var       parseResult    = Parser.Instance.Parse(args);

            performanceData.Add("Parse Time", parseStartTime.Elapsed.TotalMilliseconds);
            PerformanceLogEventSource.Log.BuiltInCommandParserStop();

            using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                       new FirstTimeUseNoticeSentinel())
            {
                IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel();
                IFileSentinel toolPathSentinel = new FileSentinel(
                    new FilePath(
                        Path.Combine(
                            CliFolderPathCalculator.DotnetUserProfileFolderPath,
                            ToolPathSentinelFileName)));
                if (parseResult.ValueForOption <bool>(Parser.DiagOption) && parseResult.IsDotnetBuiltInCommand())
                {
                    Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                    CommandContext.SetVerbose(true);
                    Reporter.Reset();
                }
                if (parseResult.HasOption(Parser.VersionOption) && parseResult.IsTopLevelDotnetCommand())
                {
                    CommandLineInfo.PrintVersion();
                    return(0);
                }
                else if (parseResult.HasOption(Parser.InfoOption) && parseResult.IsTopLevelDotnetCommand())
                {
                    CommandLineInfo.PrintInfo();
                    return(0);
                }
                else if (parseResult.HasOption("-h") && parseResult.IsTopLevelDotnetCommand())
                {
                    HelpCommand.PrintHelp();
                    return(0);
                }
                else if (parseResult.Directives.Count() > 0)
                {
                    return(parseResult.Invoke());
                }
                else
                {
                    PerformanceLogEventSource.Log.FirstTimeConfigurationStart();

                    var environmentProvider = new EnvironmentProvider();

                    bool generateAspNetCertificate =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_GENERATE_ASPNET_CERTIFICATE", defaultValue: true);
                    bool telemetryOptout =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", defaultValue: false);
                    bool addGlobalToolsToPath =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", defaultValue: true);
                    bool nologo =
                        environmentProvider.GetEnvironmentVariableAsBool("DOTNET_NOLOGO", defaultValue: false);

                    ReportDotnetHomeUsage(environmentProvider);

                    var isDotnetBeingInvokedFromNativeInstaller = false;
                    if (parseResult.CommandResult.Command.Name.Equals(Parser.InstallSuccessCommand.Name))
                    {
                        aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                        firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                        toolPathSentinel           = new NoOpFileSentinel(exists: false);
                        isDotnetBeingInvokedFromNativeInstaller = true;
                    }

                    var dotnetFirstRunConfiguration = new DotnetFirstRunConfiguration(
                        generateAspNetCertificate: generateAspNetCertificate,
                        telemetryOptout: telemetryOptout,
                        addGlobalToolsToPath: addGlobalToolsToPath,
                        nologo: nologo);

                    ConfigureDotNetForFirstTimeUse(
                        firstTimeUseNoticeSentinel,
                        aspNetCertificateSentinel,
                        toolPathSentinel,
                        isDotnetBeingInvokedFromNativeInstaller,
                        dotnetFirstRunConfiguration,
                        environmentProvider,
                        performanceData);
                    PerformanceLogEventSource.Log.FirstTimeConfigurationStop();
                }

                PerformanceLogEventSource.Log.TelemetryRegistrationStart();

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                }
                TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);

                PerformanceLogEventSource.Log.TelemetryRegistrationStop();
            }

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }
            PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStart();
            performanceData.Add("Startup Time", startupTime.TotalMilliseconds);
            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult, performanceData));
            PerformanceLogEventSource.Log.TelemetrySaveIfEnabledStop();

            var topLevelCommands = new string[] { "dotnet", parseResult.RootSubCommandResult() }.Concat(Parser.DiagOption.Aliases);
            int exitCode;

            if (parseResult.CommandResult.Command.Name.Equals("dotnet") && string.IsNullOrEmpty(parseResult.ValueForArgument <string>(Parser.DotnetSubCommand)))
            {
                exitCode = 0;
            }
            else if (BuiltInCommandsCatalog.Commands.TryGetValue(parseResult.RootSubCommandResult(), out var builtIn))
            {
                PerformanceLogEventSource.Log.BuiltInCommandStart();
                exitCode = builtIn.Command(args.Where(t => !topLevelCommands.Contains(t)).ToArray());
                PerformanceLogEventSource.Log.BuiltInCommandStop();
            }
            else
            {
                PerformanceLogEventSource.Log.ExtensibleCommandResolverStart();
                var resolvedCommand = CommandFactoryUsingResolver.Create(
                    "dotnet-" + parseResult.ValueForArgument <string>(Parser.DotnetSubCommand),
                    args.Where(t => !topLevelCommands.Contains(t)).ToArray(),
                    FrameworkConstants.CommonFrameworks.NetStandardApp15);
                PerformanceLogEventSource.Log.ExtensibleCommandResolverStop();

                PerformanceLogEventSource.Log.ExtensibleCommandStart();
                var result = resolvedCommand.Execute();
                PerformanceLogEventSource.Log.ExtensibleCommandStop();

                exitCode = result.ExitCode;
            }

            PerformanceLogEventSource.Log.TelemetryClientFlushStart();
            telemetryClient.Flush();
            PerformanceLogEventSource.Log.TelemetryClientFlushStop();

            return(exitCode);
        }