Ejemplo n.º 1
0
 internal override bool CanHandle()
 {
     return(_sampleOption.HasValue());
 }
Ejemplo n.º 2
0
        private static int EnsureHttpsCertificate(CommandOption exportPath, CommandOption password, CommandOption trust, IReporter reporter)
        {
            var now     = DateTimeOffset.Now;
            var manager = new CertificateManager();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && trust?.HasValue() == true)
            {
                reporter.Warn("Trusting the HTTPS development certificate was requested. If the certificate is not " +
                              "already trusted we will run the following command:" + Environment.NewLine +
                              "'sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain <<certificate>>'" +
                              Environment.NewLine + "This command might prompt you for your password to install the certificate " +
                              "on the system keychain.");
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && trust?.HasValue() == true)
            {
                reporter.Warn("Trusting the HTTPS development certificate was requested. A confirmation prompt will be displayed " +
                              "if the certificate was not previously trusted. Click yes on the prompt to trust the certificate.");
            }

            var result = manager.EnsureAspNetCoreHttpsDevelopmentCertificate(
                now,
                now.Add(HttpsCertificateValidity),
                exportPath.Value(),
                trust == null ? false : trust.HasValue(),
                password.HasValue(),
                password.Value());

            reporter.Verbose(string.Join(Environment.NewLine, result.Diagnostics.Messages));

            switch (result.ResultCode)
            {
            case EnsureCertificateResult.Succeeded:
                reporter.Output("The HTTPS developer certificate was generated successfully.");
                if (exportPath.Value() != null)
                {
                    reporter.Verbose($"The certificate was exported to {Path.GetFullPath(exportPath.Value())}");
                }
                return(Success);

            case EnsureCertificateResult.ValidCertificatePresent:
                reporter.Output("A valid HTTPS certificate is already present.");
                if (exportPath.Value() != null)
                {
                    reporter.Verbose($"The certificate was exported to {Path.GetFullPath(exportPath.Value())}");
                }
                return(Success);

            case EnsureCertificateResult.ErrorCreatingTheCertificate:
                reporter.Error("There was an error creating the HTTPS developer certificate.");
                return(ErrorCreatingTheCertificate);

            case EnsureCertificateResult.ErrorSavingTheCertificateIntoTheCurrentUserPersonalStore:
                reporter.Error("There was an error saving the HTTPS developer certificate to the current user personal certificate store.");
                return(ErrorSavingTheCertificate);

            case EnsureCertificateResult.ErrorExportingTheCertificate:
                reporter.Warn("There was an error exporting HTTPS developer certificate to a file.");
                return(ErrorExportingTheCertificate);

            case EnsureCertificateResult.FailedToTrustTheCertificate:
                reporter.Warn("There was an error trusting HTTPS developer certificate.");
                return(ErrorTrustingTheCertificate);

            case EnsureCertificateResult.UserCancelledTrustStep:
                reporter.Warn("The user cancelled the trust step.");
                return(ErrorUserCancelledTrustPrompt);

            default:
                reporter.Error("Something went wrong. The HTTPS developer certificate could not be created.");
                return(CriticalError);
            }
        }
Ejemplo n.º 3
0
        private static int EnsureHttpsCertificate(CommandOption exportPath, CommandOption password, CommandOption noPassword, CommandOption trust, CommandOption exportFormat, IReporter reporter)
        {
            var now     = DateTimeOffset.Now;
            var manager = CertificateManager.Instance;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                var certificates = manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true, exportPath.HasValue());
                foreach (var certificate in certificates)
                {
                    var status = manager.CheckCertificateState(certificate, interactive: true);
                    if (!status.Success)
                    {
                        reporter.Warn("One or more certificates might be in an invalid state. We will try to access the certificate key " +
                                      "for each certificate and as a result you might be prompted one or more times to enter " +
                                      "your password to access the user keychain. " +
                                      "When that happens, select 'Always Allow' to grant 'dotnet' access to the certificate key in the future.");
                    }

                    break;
                }
            }

            if (trust?.HasValue() == true)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    reporter.Warn("Trusting the HTTPS development certificate was requested. If the certificate is not " +
                                  "already trusted we will run the following command:" + Environment.NewLine +
                                  "'sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain <<certificate>>'" +
                                  Environment.NewLine + "This command might prompt you for your password to install the certificate " +
                                  "on the system keychain.");
                }

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    reporter.Warn("Trusting the HTTPS development certificate was requested. A confirmation prompt will be displayed " +
                                  "if the certificate was not previously trusted. Click yes on the prompt to trust the certificate.");
                }

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    reporter.Warn("Trusting the HTTPS development certificate was requested. Trusting the certificate on Linux distributions automatically is not supported. " +
                                  "For instructions on how to manually trust the certificate on your Linux distribution, go to https://aka.ms/dev-certs-trust");
                }
            }

            var format = CertificateKeyExportFormat.Pfx;

            if (exportFormat.HasValue() && !Enum.TryParse(exportFormat.Value(), ignoreCase: true, out format))
            {
                reporter.Error($"Unknown key format '{exportFormat.Value()}'.");
                return(InvalidKeyExportFormat);
            }

            var result = manager.EnsureAspNetCoreHttpsDevelopmentCertificate(
                now,
                now.Add(HttpsCertificateValidity),
                exportPath.Value(),
                trust == null ? false : trust.HasValue() && !RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
                password.HasValue() || (noPassword.HasValue() && format == CertificateKeyExportFormat.Pem),
                password.Value(),
                exportFormat.HasValue() ? format : CertificateKeyExportFormat.Pfx);

            switch (result)
            {
            case EnsureCertificateResult.Succeeded:
                reporter.Output("The HTTPS developer certificate was generated successfully.");
                if (exportPath.Value() != null)
                {
                    reporter.Verbose($"The certificate was exported to {Path.GetFullPath(exportPath.Value())}");
                }
                return(Success);

            case EnsureCertificateResult.ValidCertificatePresent:
                reporter.Output("A valid HTTPS certificate is already present.");
                if (exportPath.Value() != null)
                {
                    reporter.Verbose($"The certificate was exported to {Path.GetFullPath(exportPath.Value())}");
                }
                return(Success);

            case EnsureCertificateResult.ErrorCreatingTheCertificate:
                reporter.Error("There was an error creating the HTTPS developer certificate.");
                return(ErrorCreatingTheCertificate);

            case EnsureCertificateResult.ErrorSavingTheCertificateIntoTheCurrentUserPersonalStore:
                reporter.Error("There was an error saving the HTTPS developer certificate to the current user personal certificate store.");
                return(ErrorSavingTheCertificate);

            case EnsureCertificateResult.ErrorExportingTheCertificate:
                reporter.Warn("There was an error exporting HTTPS developer certificate to a file.");
                return(ErrorExportingTheCertificate);

            case EnsureCertificateResult.FailedToTrustTheCertificate:
                reporter.Warn("There was an error trusting HTTPS developer certificate.");
                return(ErrorTrustingTheCertificate);

            case EnsureCertificateResult.UserCancelledTrustStep:
                reporter.Warn("The user cancelled the trust step.");
                return(ErrorUserCancelledTrustPrompt);

            default:
                reporter.Error("Something went wrong. The HTTPS developer certificate could not be created.");
                return(CriticalError);
            }
        }
Ejemplo n.º 4
0
 public static Option <string> Some(this CommandOption opt) => !opt.HasValue() ? null : opt.Value();
Ejemplo n.º 5
0
        static void OtherMain(string[] args)
        {
            CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false);
            CommandArgument        directory  = commandLineApplication.Argument("directory", "The directory to search for assemblies");
            CommandOption          dgmlExport = commandLineApplication.Option("-dg|--dgml <filename>", "Export to a dgml file", CommandOptionType.SingleValue);
            CommandOption          nonsystem  = commandLineApplication.Option("-n|--nonsystem", "List system assemblies", CommandOptionType.NoValue);
            CommandOption          all        = commandLineApplication.Option("-a|--all", "List all assemblies and references.", CommandOptionType.NoValue);
            CommandOption          noconsole  = commandLineApplication.Option("-nc|--noconsole", "Do not show references on console.", CommandOptionType.NoValue);
            CommandOption          silent     = commandLineApplication.Option("-s|--silent", "Do not show any message, only warnings and errors will be shown.", CommandOptionType.NoValue);

            commandLineApplication.HelpOption("-? | -h | --help");
            commandLineApplication.OnExecute(() =>
            {
                ConsoleLogger consoleLogger = new ConsoleLogger(!silent.HasValue());

                string directoryPath = directory.Value;
                if (!Directory.Exists(directoryPath))
                {
                    consoleLogger.LogMessage(string.Format("Directory: '{0}' does not exist.", directoryPath));
                    return(-1);
                }

                bool onlyConflicts = !all.HasValue();
                bool skipSystem    = nonsystem.HasValue();

                IDependencyAnalyzer analyzer = new DependencyAnalyzer()
                {
                    DirectoryInfo = new DirectoryInfo(directoryPath)
                };

                consoleLogger.LogMessage(string.Format("Check assemblies in: {0}", analyzer.DirectoryInfo));

                DependencyAnalyzerResult result = analyzer.Analyze(consoleLogger);

                if (!noconsole.HasValue())
                {
                    IDependencyVisualizer visualizer = new ConsoleVisualizer(result)
                    {
                        SkipSystem = skipSystem, OnlyConflicts = onlyConflicts
                    };
                    visualizer.Visualize();
                }

                if (dgmlExport.HasValue())
                {
                    IDependencyVisualizer export = new DgmlExport(result, string.IsNullOrWhiteSpace(dgmlExport.Value()) ? Path.Combine(analyzer.DirectoryInfo.FullName, "references.dgml") : dgmlExport.Value(), consoleLogger);
                    export.Visualize();
                }

                return(0);
            });
            try
            {
                commandLineApplication.Execute(args);
            }
            catch (CommandParsingException cpe)
            {
                Console.WriteLine(cpe.Message);
                commandLineApplication.ShowHelp();
            }
        }
Ejemplo n.º 6
0
        internal static void Register(CommandLineApplication app,
                                      Func <ILogger> getLogger)
        {
            app.Command("update", UpdateCmd =>
            {
                UpdateCmd.Command("source", SourceCmd =>
                {
                    CommandArgument name = SourceCmd.Argument(
                        "name", Strings.SourcesCommandNameDescription);
                    CommandOption source = SourceCmd.Option(
                        "-s|--source",
                        Strings.SourcesCommandSourceDescription,
                        CommandOptionType.SingleValue);
                    CommandOption username = SourceCmd.Option(
                        "-u|--username",
                        Strings.SourcesCommandUsernameDescription,
                        CommandOptionType.SingleValue);
                    CommandOption password = SourceCmd.Option(
                        "-p|--password",
                        Strings.SourcesCommandPasswordDescription,
                        CommandOptionType.SingleValue);
                    CommandOption storePasswordInClearText = SourceCmd.Option(
                        "--store-password-in-clear-text",
                        Strings.SourcesCommandStorePasswordInClearTextDescription,
                        CommandOptionType.NoValue);
                    CommandOption validAuthenticationTypes = SourceCmd.Option(
                        "--valid-authentication-types",
                        Strings.SourcesCommandValidAuthenticationTypesDescription,
                        CommandOptionType.SingleValue);
                    CommandOption configfile = SourceCmd.Option(
                        "--configfile",
                        Strings.Option_ConfigFile,
                        CommandOptionType.SingleValue);
                    SourceCmd.HelpOption("-h|--help");
                    SourceCmd.Description = Strings.UpdateSourceCommandDescription;
                    SourceCmd.OnExecute(() =>
                    {
                        var args = new UpdateSourceArgs()
                        {
                            Name     = name.Value,
                            Source   = source.Value(),
                            Username = username.Value(),
                            Password = password.Value(),
                            StorePasswordInClearText = storePasswordInClearText.HasValue(),
                            ValidAuthenticationTypes = validAuthenticationTypes.Value(),
                            Configfile = configfile.Value(),
                        };

                        UpdateSourceRunner.Run(args, getLogger);
                        return(0);
                    });
                });
                UpdateCmd.HelpOption("-h|--help");
                UpdateCmd.Description = Strings.Update_Description;
                UpdateCmd.OnExecute(() =>
                {
                    app.ShowHelp("update");
                    return(0);
                });
            });
        }
Ejemplo n.º 7
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name                      = "dotnet add p2p",
                FullName                  = ".NET Add Project to Project (p2p) reference Command",
                Description               = "Command to add project to project (p2p) reference",
                AllowArgumentSeparator    = true,
                ArgumentSeparatorHelpText = "Project to project references to add"
            };

            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument(
                "<PROJECT>",
                "The project file to modify. If a project file is not specified," +
                " it searches the current working directory for an MSBuild file that has" +
                " a file extension that ends in `proj` and uses that file.");

            CommandOption frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                "Add reference only when targetting a specific framework",
                CommandOptionType.SingleValue);

            CommandOption forceOption = app.Option(
                "--force",
                "Add reference even if it does not exist, do not convert paths to relative",
                CommandOptionType.NoValue);

            app.OnExecute(() => {
                if (string.IsNullOrEmpty(projectArgument.Value))
                {
                    throw new GracefulException(LocalizableStrings.RequiredArgumentNotPassed, "<Project>");
                }

                var msbuildProj = MsbuildProject.FromFileOrDirectory(projectArgument.Value);

                if (app.RemainingArguments.Count == 0)
                {
                    throw new GracefulException(LocalizableStrings.SpecifyAtLeastOneReferenceToAdd);
                }

                List <string> references = app.RemainingArguments;
                if (!forceOption.HasValue())
                {
                    MsbuildProject.EnsureAllReferencesExist(references);
                    msbuildProj.ConvertPathsToRelative(ref references);
                }

                int numberOfAddedReferences = msbuildProj.AddProjectToProjectReferences(
                    frameworkOption.Value(),
                    references);

                if (numberOfAddedReferences != 0)
                {
                    msbuildProj.Project.Save();
                }

                return(0);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (GracefulException e)
            {
                Reporter.Error.WriteLine(e.Message.Red());
                app.ShowHelp();
                return(1);
            }
        }
Ejemplo n.º 8
0
        public static int Main(string[] args)
        {
            CommandLineApplication commandLineApplication =
                new CommandLineApplication(throwOnUnexpectedArg: false);

            commandLineApplication.Name = "iMobileDevice.Generator";
            commandLineApplication.HelpOption("-?|-h|--help");

            commandLineApplication.Command(
                "generate",
                (runCommand) =>
            {
                runCommand.Description = "Generates the Interop source for imobiledevice-net based on the libimobiledevice headers";

                CommandOption outputArgument = runCommand.Option(
                    "-o|--output <dir>",
                    "The output directory. The C# code will be generated in this directory.",
                    CommandOptionType.SingleValue);

                CommandOption includeArgument = runCommand.Option(
                    "-i|--include <dir>",
                    "Include directory to use. Defaults to the include directory in VCPKG_ROOT.",
                    CommandOptionType.SingleValue);

                runCommand.HelpOption("-? | -h | --help");

                runCommand.OnExecute(() =>
                {
                    string targetDirectory = @"..\..\..\..\..\iMobileDevice-net";
                    if (outputArgument.HasValue())
                    {
                        targetDirectory = outputArgument.Value();
                    }

                    targetDirectory = Path.GetFullPath(targetDirectory);

                    RestoreClang();

                    ModuleGenerator generator = new ModuleGenerator();
                    generator.IncludeDirectories.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft Visual Studio 14.0\VC\include"));
                    generator.IncludeDirectories.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft Visual Studio\Shared\14.0\VC\include"));
                    generator.IncludeDirectories.Add(GetWindowsKitUcrtFolder());
                    generator.IncludeDirectories.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Windows Kits", "8.1", "include", "shared"));

                    string sourceDir = null;

                    if (includeArgument.HasValue())
                    {
                        sourceDir = includeArgument.Value();
                    }
                    else
                    {
                        var vcpkgPath = Environment.GetEnvironmentVariable("VCPKG_ROOT");

                        if (vcpkgPath == null)
                        {
                            Console.Error.WriteLine("Please set the VCPKG_ROOT environment variable to the folder where you've installed VCPKG.");
                            return(-1);
                        }

                        vcpkgPath = Path.Combine(vcpkgPath, "installed", "x86-windows", "include");
                        Console.WriteLine($"Reading include files from {vcpkgPath}");
                        sourceDir = vcpkgPath;
                    }

                    generator.IncludeDirectories.Add(sourceDir);

                    Console.WriteLine($"Writing the C# files to: {targetDirectory}");

                    Collection <string> names = new Collection <string>();

                    var files = new List <string>();
                    files.Add(Path.Combine(sourceDir, "usbmuxd.h"));
                    files.Add(Path.Combine(sourceDir, "plist/plist.h"));
                    files.Add(Path.Combine(sourceDir, "libideviceactivation.h"));
                    files.Add(Path.Combine(sourceDir, "libirecovery.h"));
                    var iMobileDeviceDirectory = Path.Combine(sourceDir, "libimobiledevice");
                    files.Add(Path.Combine(iMobileDeviceDirectory, "libimobiledevice.h"));
                    files.Add(Path.Combine(iMobileDeviceDirectory, "lockdown.h"));
                    files.Add(Path.Combine(iMobileDeviceDirectory, "afc.h"));

                    var iMobileDeviceFileNames = Directory.GetFiles(iMobileDeviceDirectory, "*.h")
                                                 .Where(f => !files.Contains(f, StringComparer.OrdinalIgnoreCase));

                    files.AddRange(iMobileDeviceFileNames);

                    foreach (var file in files)
                    {
                        Console.WriteLine($"Processing {Path.GetFileName(file)}");
                        generator.InputFile = file;

                        if (string.Equals(Path.GetFileName(file), "libideviceactivation.h", StringComparison.OrdinalIgnoreCase))
                        {
                            generator.Generate(targetDirectory, "ideviceactivation");
                        }
                        else if (string.Equals(Path.GetFileName(file), "plist.h", StringComparison.OrdinalIgnoreCase))
                        {
                            generator.Generate(targetDirectory, "plist");
                        }
                        else if (string.Equals(Path.GetFileName(file), "usbmuxd.h", StringComparison.OrdinalIgnoreCase))
                        {
                            generator.Generate(targetDirectory, "usbmuxd");
                        }
                        else if (string.Equals(Path.GetFileName(file), "libirecovery.h", StringComparison.OrdinalIgnoreCase))
                        {
                            generator.Generate(targetDirectory, "irecovery");
                        }
                        else
                        {
                            generator.Generate(targetDirectory);
                        }

                        generator.Types.Clear();

                        names.Add(generator.Name);
                    }

                    ApiGenerator apiGenerator = new ApiGenerator();
                    apiGenerator.Generate(names, targetDirectory);

                    return(0);
                });
            });

            return(commandLineApplication.Execute(args));
        }
Ejemplo n.º 9
0
        private protected void AddOption(ConventionContext context, CommandOption option, PropertyInfo prop)
        {
            foreach (var attr in prop.GetCustomAttributes().OfType <ValidationAttribute>())
            {
                option.Validators.Add(new AttributeValidator(attr));
            }

            if (option.OptionType == CommandOptionType.NoValue && prop.PropertyType != typeof(bool))
            {
                throw new InvalidOperationException(Strings.NoValueTypesMustBeBoolean);
            }

            if (!string.IsNullOrEmpty(option.ShortName))
            {
                if (context.Application._shortOptions.TryGetValue(option.ShortName, out var otherProp))
                {
                    throw new InvalidOperationException(
                              Strings.OptionNameIsAmbiguous(option.ShortName, prop, otherProp));
                }
                context.Application._shortOptions.Add(option.ShortName, prop);
            }

            if (!string.IsNullOrEmpty(option.LongName))
            {
                if (context.Application._longOptions.TryGetValue(option.LongName, out var otherProp))
                {
                    throw new InvalidOperationException(
                              Strings.OptionNameIsAmbiguous(option.LongName, prop, otherProp));
                }
                context.Application._longOptions.Add(option.LongName, prop);
            }

            var setter = ReflectionHelper.GetPropertySetter(prop);

            switch (option.OptionType)
            {
            case CommandOptionType.MultipleValue:
                var collectionParser = CollectionParserProvider.Default.GetParser(prop.PropertyType);
                if (collectionParser == null)
                {
                    throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                }
                context.Application.OnParsingComplete(_ =>
                                                      setter.Invoke(context.ModelAccessor.GetModel(), collectionParser.Parse(option.LongName, option.Values)));
                break;

            case CommandOptionType.SingleOrNoValue:
                var valueTupleParser = ValueTupleParserProvider.Default.GetParser(prop.PropertyType);
                if (valueTupleParser == null)
                {
                    throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                }
                context.Application.OnParsingComplete(_ =>
                                                      setter.Invoke(context.ModelAccessor.GetModel(), valueTupleParser.Parse(option.HasValue(), option.LongName, option.Value())));
                break;

            case CommandOptionType.SingleValue:
                var parser = ValueParserProvider.Default.GetParser(prop.PropertyType);
                if (parser == null)
                {
                    throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                }
                context.Application.OnParsingComplete(_ =>
                {
                    var value = option.Value();
                    if (value == null)
                    {
                        return;
                    }
                    setter.Invoke(context.ModelAccessor.GetModel(), parser.Parse(option.LongName, value));
                });
                break;

            case CommandOptionType.NoValue:
                context.Application.OnParsingComplete(_ => setter.Invoke(context.ModelAccessor.GetModel(), option.HasValue()));
                break;

            default:
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 10
0
        public static void Main(string[] args)
        {
            try
            {
                AppDomain.CurrentDomain.UnhandledException += OnAppDomainUnhandledException;
#if DEBUG
                PreloadNativeLibs();
#endif
                //TouchNativeLibs();
                if (!HandleCommandLineOptions(args, out var configFile))
                {
                    return;
                }

                Logo();
                clusterConfig = ReadConfig(configFile);

                if (dumpConfigOption.HasValue())
                {
                    DumpParsedConfig(clusterConfig);
                    return;
                }

                ValidateConfig();
                Bootstrap();
                LogRuntimeInfo();

                if (!shareRecoveryOption.HasValue())
                {
                    Console.CancelKeyPress += OnCancelKeyPress;
                    Start().Wait(cts.Token);
                }

                else
                {
                    RecoverShares(shareRecoveryOption.Value());
                }
            }

            catch (PoolStartupAbortException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine("\nCluster cannot start. Good Bye!");
            }

            catch (JsonException)
            {
                // ignored
            }

            catch (IOException)
            {
                // ignored
            }

            catch (AggregateException ex)
            {
                if (!(ex.InnerExceptions.First() is PoolStartupAbortException))
                {
                    Console.WriteLine(ex);
                }

                Console.WriteLine("Cluster cannot start. Good Bye!");
            }

            catch (OperationCanceledException)
            {
                // Ctrl+C
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex);

                Console.WriteLine("Cluster cannot start. Good Bye!");
            }
        }
Ejemplo n.º 11
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication();

            app.Name                = "dotnet compile-fsc";
            app.FullName            = ".NET F# Compiler";
            app.Description         = "F# Compiler for the .NET Platform";
            app.HandleResponseFiles = true;
            app.HelpOption("-h|--help");

            CommonCompilerOptionsCommandLine commonCompilerCommandLine = CommonCompilerOptionsCommandLine.AddOptions(app);
            AssemblyInfoOptionsCommandLine   assemblyInfoCommandLine   = AssemblyInfoOptionsCommandLine.AddOptions(app);

            CommandOption   tempOutputOption = app.Option("--temp-output <arg>", "Compilation temporary directory", CommandOptionType.SingleValue);
            CommandOption   outputNameOption = app.Option("--out <arg>", "Name of the output assembly", CommandOptionType.SingleValue);
            CommandOption   referencesOption = app.Option("--reference <arg>...", "Path to a compiler metadata reference", CommandOptionType.MultipleValue);
            CommandOption   resourcesOption  = app.Option("--resource <arg>...", "Resources to embed", CommandOptionType.MultipleValue);
            CommandArgument sourcesArgument  = app.Argument("<source-files>...", "Compilation sources", multipleValues: true);

            app.OnExecute(() =>
            {
                if (!tempOutputOption.HasValue())
                {
                    Reporter.Error.WriteLine("Option '--temp-output' is required");
                    return(ExitFailed);
                }

                CommonCompilerOptions commonOptions = commonCompilerCommandLine.GetOptionValues();

                AssemblyInfoOptions assemblyInfoOptions = assemblyInfoCommandLine.GetOptionValues();

                // TODO less hacky
                bool targetNetCore =
                    commonOptions.Defines.Contains("DNXCORE50") ||
                    commonOptions.Defines.Where(d => d.StartsWith("NETSTANDARDAPP1_")).Any() ||
                    commonOptions.Defines.Where(d => d.StartsWith("NETCOREAPP1_")).Any() ||
                    commonOptions.Defines.Where(d => d.StartsWith("NETSTANDARD1_")).Any();

                // Get FSC Path upfront to use it for win32manifest path
                string tempOutDir  = tempOutputOption.Value();
                var fscCommandSpec = ResolveFsc(null, tempOutDir);
                var fscExeFile     = fscCommandSpec.FscExeFile;
                var fscExeDir      = fscCommandSpec.FscExeDir;

                // FSC arguments
                var allArgs = new List <string>();

                //HACK fsc raise error FS0208 if target exe doesnt have extension .exe
                bool hackFS0208 = targetNetCore && commonOptions.EmitEntryPoint == true;

                string outputName      = outputNameOption.Value();
                var originalOutputName = outputName;

                if (outputName != null)
                {
                    if (hackFS0208)
                    {
                        outputName = Path.ChangeExtension(outputName, ".exe");
                    }

                    allArgs.Add($"--out:{outputName}");
                }

                //let's pass debugging type only if options.DebugType is specified, until
                //portablepdb are confirmed to work.
                //so it's possibile to test portable pdb without breaking existing build
                if (string.IsNullOrEmpty(commonOptions.DebugType))
                {
                    //debug info (only windows pdb supported, not portablepdb)
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        allArgs.Add("--debug");
                        //TODO check if full or pdbonly
                        allArgs.Add("--debug:pdbonly");
                    }
                    else
                    {
                        allArgs.Add("--debug-");
                    }
                }
                else
                {
                    allArgs.Add("--debug");
                    allArgs.Add($"--debug:{commonOptions.DebugType}");
                }

                // Default options
                allArgs.Add("--noframework");
                allArgs.Add("--nologo");
                allArgs.Add("--simpleresolution");
                allArgs.Add("--nocopyfsharpcore");

                // project.json compilationOptions
                if (commonOptions.Defines != null)
                {
                    allArgs.AddRange(commonOptions.Defines.Select(def => $"--define:{def}"));
                }

                if (commonOptions.GenerateXmlDocumentation == true)
                {
                    allArgs.Add($"--doc:{Path.ChangeExtension(outputName, "xml")}");
                }

                if (commonOptions.KeyFile != null)
                {
                    allArgs.Add($"--keyfile:{commonOptions.KeyFile}");
                }

                if (commonOptions.Optimize == true)
                {
                    allArgs.Add("--optimize+");
                }

                //--resource doesnt expect "
                //bad: --resource:"path/to/file",name
                //ok:  --resource:path/to/file,name
                allArgs.AddRange(resourcesOption.Values.Select(resource => $"--resource:{resource.Replace("\"", "")}"));

                allArgs.AddRange(referencesOption.Values.Select(r => $"-r:{r}"));

                if (commonOptions.EmitEntryPoint != true)
                {
                    allArgs.Add("--target:library");
                }
                else
                {
                    allArgs.Add("--target:exe");

                    //HACK we need default.win32manifest for exe
                    var win32manifestPath = Path.Combine(fscExeDir, "..", "..", "runtimes", "any", "native", "default.win32manifest");
                    allArgs.Add($"--win32manifest:{win32manifestPath}");
                }

                if (commonOptions.SuppressWarnings != null && commonOptions.SuppressWarnings.Any())
                {
                    allArgs.Add("--nowarn:" + string.Join(",", commonOptions.SuppressWarnings.ToArray()));
                }

                if (commonOptions.LanguageVersion != null)
                {
                    // Not used in fsc
                }

                if (commonOptions.Platform != null)
                {
                    allArgs.Add($"--platform:{commonOptions.Platform}");
                }

                if (commonOptions.AllowUnsafe == true)
                {
                }

                if (commonOptions.WarningsAsErrors == true)
                {
                    allArgs.Add("--warnaserror");
                }

                //set target framework
                if (targetNetCore)
                {
                    allArgs.Add("--targetprofile:netcore");
                }

                if (commonOptions.DelaySign == true)
                {
                    allArgs.Add("--delaysign+");
                }

                if (commonOptions.PublicSign == true)
                {
                }

                if (commonOptions.AdditionalArguments != null)
                {
                    // Additional arguments are added verbatim
                    allArgs.AddRange(commonOptions.AdditionalArguments);
                }

                // Generate assembly info
                var assemblyInfo = Path.Combine(tempOutDir, $"dotnet-compile.assemblyinfo.fs");
                File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateFSharp(assemblyInfoOptions));

                //source files + assemblyInfo
                allArgs.AddRange(GetSourceFiles(sourcesArgument.Values, assemblyInfo).ToArray());

                //TODO check the switch enabled in fsproj in RELEASE and DEBUG configuration

                var rsp = Path.Combine(tempOutDir, "dotnet-compile-fsc.rsp");
                File.WriteAllLines(rsp, allArgs, Encoding.UTF8);

                // Execute FSC!
                var result = RunFsc(new List <string> {
                    $"@{rsp}"
                }, tempOutDir)
                             .ForwardStdErr()
                             .ForwardStdOut()
                             .Execute();

                bool successFsc = result.ExitCode == 0;

                if (hackFS0208 && File.Exists(outputName))
                {
                    if (File.Exists(originalOutputName))
                    {
                        File.Delete(originalOutputName);
                    }
                    File.Move(outputName, originalOutputName);
                }

                //HACK dotnet build require a pdb (crash without), fsc atm cant generate a portable pdb, so an empty pdb is created
                string pdbPath = Path.ChangeExtension(outputName, ".pdb");
                if (successFsc && !File.Exists(pdbPath))
                {
                    File.WriteAllBytes(pdbPath, Array.Empty <byte>());
                }

                return(result.ExitCode);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Reporter.Error.WriteLine(ex.ToString());
#else
                Reporter.Error.WriteLine(ex.Message);
#endif
                return(ExitFailed);
            }
        }
Ejemplo n.º 12
0
        protected override int Execute()
        {
            var commands = _args.TakeWhile(a => a[0] != '-').ToList();

            if (_help.HasValue() || ShouldHelp(commands))
            {
                return(ShowHelp(_help.HasValue(), commands));
            }

            var(projectFile, startupProjectFile) = ResolveProjects(
                _project.Value(),
                _startupProject.Value());

            Reporter.WriteVerbose(Resources.UsingProject(projectFile));
            Reporter.WriteVerbose(Resources.UsingStartupProject(startupProjectFile));

            var project        = Project.FromFile(projectFile, _msbuildprojectextensionspath.Value());
            var startupProject = Project.FromFile(
                startupProjectFile,
                _msbuildprojectextensionspath.Value(),
                _framework.Value(),
                _configuration.Value(),
                _runtime.Value());

            if (!_noBuild.HasValue())
            {
                startupProject.Build();
            }

            string executable;
            var    args = new List <string>();

            var toolsPath = Path.Combine(
                Path.GetDirectoryName(typeof(Program).GetTypeInfo().Assembly.Location),
                "tools");

            var targetDir         = Path.GetFullPath(Path.Combine(startupProject.ProjectDir, startupProject.OutputPath));
            var targetPath        = Path.Combine(targetDir, project.TargetFileName);
            var startupTargetPath = Path.Combine(targetDir, startupProject.TargetFileName);
            var depsFile          = Path.Combine(
                targetDir,
                startupProject.AssemblyName + ".deps.json");
            var runtimeConfig = Path.Combine(
                targetDir,
                startupProject.AssemblyName + ".runtimeconfig.json");
            var projectAssetsFile = startupProject.ProjectAssetsFile;

            var targetFramework = new FrameworkName(startupProject.TargetFrameworkMoniker);

            if (targetFramework.Identifier == ".NETFramework")
            {
                executable = Path.Combine(
                    toolsPath,
                    "net461",
                    startupProject.PlatformTarget == "x86"
                        ? "win-x86"
                        : "any",
                    "ef.exe");
            }
            else if (targetFramework.Identifier == ".NETCoreApp")
            {
                if (targetFramework.Version < new Version(2, 0))
                {
                    throw new CommandException(
                              Resources.NETCoreApp1StartupProject(startupProject.ProjectName, targetFramework.Version));
                }

                executable = "dotnet";
                args.Add("exec");
                args.Add("--depsfile");
                args.Add(depsFile);

                if (!string.IsNullOrEmpty(projectAssetsFile))
                {
                    using (var reader = JsonDocument.Parse(File.OpenRead(projectAssetsFile)))
                    {
                        var projectAssets  = reader.RootElement;
                        var packageFolders = projectAssets.GetProperty("packageFolders").EnumerateObject().Select(p => p.Name);

                        foreach (var packageFolder in packageFolders)
                        {
                            args.Add("--additionalprobingpath");
                            args.Add(packageFolder.TrimEnd(Path.DirectorySeparatorChar));
                        }
                    }
                }

                if (File.Exists(runtimeConfig))
                {
                    args.Add("--runtimeconfig");
                    args.Add(runtimeConfig);
                }
                else if (startupProject.RuntimeFrameworkVersion.Length != 0)
                {
                    args.Add("--fx-version");
                    args.Add(startupProject.RuntimeFrameworkVersion);
                }

                args.Add(Path.Combine(toolsPath, "netcoreapp2.0", "any", "ef.dll"));
            }
            else if (targetFramework.Identifier == ".NETStandard")
            {
                throw new CommandException(Resources.NETStandardStartupProject(startupProject.ProjectName));
            }
            else
            {
                throw new CommandException(
                          Resources.UnsupportedFramework(startupProject.ProjectName, targetFramework.Identifier));
            }

            args.AddRange(_args);
            args.Add("--assembly");
            args.Add(targetPath);
            args.Add("--startup-assembly");
            args.Add(startupTargetPath);
            args.Add("--project-dir");
            args.Add(project.ProjectDir);
            args.Add("--language");
            args.Add(project.Language);
            args.Add("--working-dir");
            args.Add(Directory.GetCurrentDirectory());

            if (Reporter.IsVerbose)
            {
                args.Add("--verbose");
            }

            if (Reporter.NoColor)
            {
                args.Add("--no-color");
            }

            if (Reporter.PrefixOutput)
            {
                args.Add("--prefix-output");
            }

            if (project.RootNamespace.Length != 0)
            {
                args.Add("--root-namespace");
                args.Add(project.RootNamespace);
            }

            return(Exe.Run(executable, args, startupProject.ProjectDir));
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            CommandLineApplication cla = new CommandLineApplication(throwOnUnexpectedArg: false);

            cla.Name     = "dbrel";
            cla.FullName = "dbrel: Database Release Utility";
            cla.HelpOption("-? | -h | --help");
            cla.VersionOption("-v | --version", "0.0.7");
            CommandOption init = cla.Option("-i | --init <dir>"
                                            , "Initialise an empty folder structure."
                                            , CommandOptionType.SingleValue);
            CommandOption target = cla.Option("-t | --target <target>"
                                              , "Target database code referenced in .dbrel"
                                              , CommandOptionType.SingleValue);
            CommandOption config = cla.Option("-c | --config"
                                              , "Apply configuration script."
                                              , CommandOptionType.NoValue);
            CommandOption schema_action = cla.Option("-s | --schema_action <action>"
                                                     , "Database schema action"
                                                     , CommandOptionType.SingleValue);
            CommandArgument file = cla.Argument("file"
                                                , "The file to run in against the target database."
                                                , false);

            cla.OnExecute(() => {
                string pathGiven = Path.GetFullPath(".");
                if (File.Exists(file.Value))
                {
                    pathGiven = Path.GetFullPath(file.Value);
                }
                string root = DBRelLib.FindRoot(pathGiven);
                if (root == null)
                {
                    Console.WriteLine(string.Format("Unable to locate .dbrel from {0}", pathGiven));
                }
                else
                {
                    Dictionary <string, Dictionary <string, string> > cfg = DBRelLib.Cfg(root);
                    List <string> keys = new List <string>(cfg.Keys);
                    string tgt         = keys[0];
                    if (target.HasValue())
                    {
                        tgt = target.Value();
                    }
                    if (keys.Contains(tgt))
                    {
                        List <string> tgtKeys = new List <string>(cfg[tgt].Keys);
                        // If there is a block_hosts key, interpret it...
                        bool block_host = false;
                        if (tgtKeys.Contains("block_hosts"))
                        {
                            List <string> block_hosts = new List <string>(cfg[tgt]["block_hosts"].Split(","));
                            block_host = block_hosts.Contains(System.Net.Dns.GetHostName());
                        }
                        // If there is an ignore_patterns key, interpret it...
                        bool ignore_file = false;
                        if (tgtKeys.Contains("ignore_patterns"))
                        {
                            List <string> ignore_patterns = new List <string>(cfg[tgt]["ignore_patterns"].Split(","));
                            foreach (string ignore_pattern in ignore_patterns)
                            {
                                Regex re = new Regex(ignore_pattern);
                                if (file.Value != null && re.Match(file.Value).Success)
                                {
                                    ignore_file = true;
                                }
                            }
                        }
                        if (block_host)
                        {
                            Console.WriteLine(string.Format("{0} has been explicitly blocked for the target '{1}'", System.Net.Dns.GetHostName(), tgt));
                        }
                        else if (ignore_file)
                        {
                            Console.WriteLine(string.Format("Ignoring {0}. Check your .dbrel file is this is a mistake.", file.Value));
                        }
                        else
                        {
                            string cs = cfg[tgt]["connectionString"];
                            if (Environment.GetEnvironmentVariable("DEBUG") != null)
                            {
                                Console.WriteLine(cs);
                            }
                            string driver = "mssql";
                            if (cfg[tgt].ContainsKey("driver"))
                            {
                                driver = cfg[tgt]["driver"];
                            }
                            if (init.HasValue())
                            {
                                DBRelLib.Init(init.Value());
                            }
                            else if (config.HasValue())
                            {
                                DBRelLib.Config(root, tgt, cs, driver);
                            }
                            else if (schema_action.HasValue())
                            {
                                DBRelLib.SchemaInit(cs, driver);
                                Dictionary <int, Dictionary <string, string> > queue = DBRelLib.SchemaQueue(root);
                                dbconn db = new dbconn(cs, driver);
                                List <Dictionary <string, object> > rows = db.rows("select id from _dbrel");
                                foreach (KeyValuePair <int, Dictionary <string, string> > entry in queue)
                                {
                                    string applied = "0";
                                    foreach (Dictionary <string, object> row in rows)
                                    {
                                        if ((int)row["id"] == entry.Key)
                                        {
                                            applied = "1";
                                        }
                                    }
                                    queue[entry.Key]["applied"] = applied;
                                }
                                if (schema_action.Value() == "queue")
                                {
                                    foreach (KeyValuePair <int, Dictionary <string, string> > entry in queue)
                                    {
                                        if (entry.Value["applied"] == "0")
                                        {
                                            Console.WriteLine(string.Format("{0}\t{1}", entry.Key, entry.Value["filepath"]));
                                        }
                                    }
                                }
                                else if (schema_action.Value() == "rollback")
                                {
                                    rows   = db.rows("select isnull(max(id), 1) id from _dbrel");
                                    int id = (int)rows[0]["id"];
                                    Console.WriteLine(string.Format("Rolling back schema patch {0}.\n  I hope you know what you're doing!", id));
                                    db.exec(string.Format("delete _dbrel where id = {0}", id));
                                }
                                else if (schema_action.Value() == "apply" ||
                                         schema_action.Value() == "manual")
                                {
                                    bool applied = false;
                                    int i        = 1;
                                    while (!applied && i <= queue.Count)
                                    {
                                        if (queue[i]["applied"] == "0")
                                        {
                                            string filepath = queue[i]["filepath"];
                                            using (StreamReader fin = File.OpenText(filepath)) {
                                                string sql  = fin.ReadToEnd();
                                                bool result = true;
                                                if (schema_action.Value() == "apply")
                                                {
                                                    Console.Write(string.Format("Applying schema patch {0}...", filepath));
                                                    result = db.exec(sql);
                                                    Console.WriteLine(string.Format(" {0}", (result ? "Success" : "Fail")));
                                                }
                                                else
                                                {
                                                    Console.Write(string.Format("Manually marking schema patch {0} as applied.\n  I hope you know what you're doing!", i));
                                                }
                                                if (result)
                                                {
                                                    db.exec(string.Format("insert into _dbrel (id) values ({0});", i));
                                                }
                                            }
                                            applied = true;
                                        }
                                        i++;
                                    }
                                    if (!applied)
                                    {
                                        Console.WriteLine(string.Format("No schema patches to apply to {0}", tgt));
                                    }
                                }
                                else
                                {
                                    Console.WriteLine(string.Format("I don't know how to perform schema action '{0}'", schema_action.Value()));
                                }
                            }
                            else if (file.Value != null)
                            {
                                if (File.Exists(file.Value))
                                {
                                    dbconn db   = new dbconn(cs, driver);
                                    string sql1 = DBRelLib.DropStatement(file.Value, driver);
                                    // Console.WriteLine(sql1);
                                    db.exec(sql1);
                                    using (StreamReader sr = new StreamReader(file.Value)) {
                                        string sql2 = sr.ReadToEnd();
                                        bool result = db.exec(sql2);
                                        Console.WriteLine(string.Format("Applying {0}... {1}", pathGiven, (result ? "Success" : "Fail")));
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Specified file does not exist...\n  {0}", file.Value);
                                }
                            }
                            else
                            {
                                cla.ShowHelp();
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Invalid target specified: {0}", tgt));
                    }
                }
                return(0);
            });
            cla.Execute(args);
        }
Ejemplo n.º 14
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication cmd = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name        = "pack",
                FullName    = LocalizableStrings.AppFullName,
                Description = LocalizableStrings.AppDescription,
                HandleRemainingArguments  = true,
                ArgumentSeparatorHelpText = HelpMessageStrings.MSBuildAdditionalArgsHelpText
            };

            cmd.HelpOption("-h|--help");

            var output = cmd.Option(
                $"-o|--output <{LocalizableStrings.CmdOutputDir}>",
                LocalizableStrings.CmdOutputDirDescription,
                CommandOptionType.SingleValue);
            var noBuild = cmd.Option(
                "--no-build",
                LocalizableStrings.CmdNoBuildOptionDescription,
                CommandOptionType.NoValue);
            var includeSymbols = cmd.Option(
                "--include-symbols",
                LocalizableStrings.CmdIncludeSymbolsDescription,
                CommandOptionType.NoValue);
            var includeSource = cmd.Option(
                "--include-source",
                LocalizableStrings.CmdIncludeSourceDescription,
                CommandOptionType.NoValue);
            var configuration = cmd.Option(
                $"-c|--configuration <{LocalizableStrings.CmdConfig}>",
                LocalizableStrings.CmdConfigDescription,
                CommandOptionType.SingleValue);
            var versionSuffix = cmd.Option(
                $"--version-suffix <{LocalizableStrings.CmdVersionSuffix}>",
                LocalizableStrings.CmdVersionSuffixDescription,
                CommandOptionType.SingleValue);
            var serviceable = cmd.Option(
                "-s|--serviceable",
                LocalizableStrings.CmdServiceableDescription,
                CommandOptionType.NoValue);
            var argRoot = cmd.Argument(
                $"<{LocalizableStrings.CmdArgumentProject}>",
                LocalizableStrings.CmdArgumentDescription,
                multipleValues: true);
            CommandOption verbosityOption = MSBuildForwardingApp.AddVerbosityOption(cmd);

            cmd.OnExecute(() =>
            {
                var msbuildArgs = new List <string>()
                {
                    "/t:pack"
                };

                if (noBuild.HasValue())
                {
                    msbuildArgs.Add($"/p:NoBuild=true");
                }

                if (includeSymbols.HasValue())
                {
                    msbuildArgs.Add($"/p:IncludeSymbols=true");
                }

                if (includeSource.HasValue())
                {
                    msbuildArgs.Add($"/p:IncludeSource=true");
                }

                if (output.HasValue())
                {
                    msbuildArgs.Add($"/p:PackageOutputPath={output.Value()}");
                }

                if (configuration.HasValue())
                {
                    msbuildArgs.Add($"/p:Configuration={configuration.Value()}");
                }

                if (versionSuffix.HasValue())
                {
                    msbuildArgs.Add($"/p:VersionSuffix={versionSuffix.Value()}");
                }

                if (serviceable.HasValue())
                {
                    msbuildArgs.Add($"/p:Serviceable=true");
                }

                if (verbosityOption.HasValue())
                {
                    msbuildArgs.Add($"/verbosity:{verbosityOption.Value()}");
                }

                msbuildArgs.AddRange(argRoot.Values);

                msbuildArgs.AddRange(cmd.RemainingArguments);
                return(new MSBuildForwardingApp(msbuildArgs).Execute());
            });

            return(cmd.Execute(args));
        }
Ejemplo n.º 15
0
        public static int Main(string[] args)
        {
            //Console.ReadLine();
            Broker = new Broker();

            CommandLineApplication app = new CommandLineApplication(false)
            {
                Name     = "dotnet new3",
                FullName = "Template Instantiation Commands for .NET Core CLI."
            };

            CommandArgument template        = app.Argument("template", "The template to instantiate.");
            CommandOption   listOnly        = app.Option("-l|--list", "Lists templates with containing the specified name.", CommandOptionType.NoValue);
            CommandOption   name            = app.Option("-n|--name", "The name for the output. If no name is specified, the name of the current directory is used.", CommandOptionType.SingleValue);
            CommandOption   dir             = app.Option("-d|--dir", "Indicates whether to display create a directory for the generated content.", CommandOptionType.NoValue);
            CommandOption   alias           = app.Option("-a|--alias", "Creates an alias for the specified template", CommandOptionType.SingleValue);
            CommandOption   parametersFiles = app.Option("-x|--extra-args", "Adds a parameters file.", CommandOptionType.MultipleValue);
            CommandOption   install         = app.Option("-i|--install", "Installs a source or a template pack.", CommandOptionType.MultipleValue);
            CommandOption   uninstall       = app.Option("-u|--uninstall", "Uninstalls a source", CommandOptionType.MultipleValue);
            CommandOption   source          = app.Option("-s|--source", "The specific template source to get the template from.", CommandOptionType.SingleValue);
            CommandOption   currentConfig   = app.Option("-c|--current-config", "Lists the currently installed components and sources.", CommandOptionType.NoValue);
            CommandOption   help            = app.Option("-h|--help", "Indicates whether to display the help for the template's parameters instead of creating it.", CommandOptionType.NoValue);

            CommandOption installComponent = app.Option("--install-component", "Installs a component.", CommandOptionType.MultipleValue);
            CommandOption resetConfig      = app.Option("--reset", "Resets the component cache and installed template sources.", CommandOptionType.NoValue);
            CommandOption rescan           = app.Option("--rescan", "Rebuilds the component cache.", CommandOptionType.NoValue);
            CommandOption global           = app.Option("--global", "Performs the --install or --install-component operation for all users.", CommandOptionType.NoValue);
            CommandOption reinit           = app.Option("--reinitialize", "Sets dotnet new3 back to its pre-first run state.", CommandOptionType.NoValue);
            CommandOption quiet            = app.Option("--quiet", "Doesn't output any status information.", CommandOptionType.NoValue);
            CommandOption skipUpdateCheck  = app.Option("--skip-update-check", "Don't check for updates.", CommandOptionType.NoValue);
            CommandOption update           = app.Option("--update", "Update matching templates.", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                if (reinit.HasValue())
                {
                    Paths.FirstRunCookie.Delete();
                    return(Task.FromResult(0));
                }

                if (!Paths.UserDir.Exists() || !Paths.FirstRunCookie.Exists())
                {
                    if (!quiet.HasValue())
                    {
                        Reporter.Output.WriteLine("Getting things ready for first use...");
                    }

                    if (!Paths.FirstRunCookie.Exists())
                    {
                        PerformReset(true, true);
                        Paths.FirstRunCookie.WriteAllText("");
                    }

                    ConfigureEnvironment();
                    PerformReset(false, true);
                }

                if (rescan.HasValue())
                {
                    Broker.ComponentRegistry.ForceReinitialize();
                    ShowConfig();
                    return(Task.FromResult(0));
                }

                if (resetConfig.HasValue())
                {
                    PerformReset(global.HasValue());
                    return(Task.FromResult(0));
                }

                if (currentConfig.HasValue())
                {
                    ShowConfig();
                    return(Task.FromResult(0));
                }

                if (install.HasValue())
                {
                    InstallPackage(install.Values, true, global.HasValue(), quiet.HasValue());
                    return(Task.FromResult(0));
                }

                if (installComponent.HasValue())
                {
                    InstallPackage(installComponent.Values, false, global.HasValue(), quiet.HasValue());
                    return(Task.FromResult(0));
                }

                if (update.HasValue())
                {
                    return(PerformUpdateAsync(template.Value, quiet.HasValue(), source));
                }

                if (uninstall.HasValue())
                {
                    foreach (string value in uninstall.Values)
                    {
                        if (value == "*")
                        {
                            Paths.TemplateSourcesFile.Delete();
                            Paths.AliasesFile.Delete();

                            if (global.HasValue())
                            {
                                Paths.GlobalTemplateCacheDir.Delete();
                            }
                            else
                            {
                                Paths.TemplateCacheDir.Delete();
                            }

                            return(Task.FromResult(0));
                        }

                        if (!TryRemoveSource(value))
                        {
                            string cacheDir = global.HasValue() ? Paths.GlobalTemplateCacheDir : Paths.TemplateCacheDir;
                            bool anyRemoved = false;

                            if (!value.Exists())
                            {
                                foreach (string file in cacheDir.EnumerateFiles($"{value}.*.nupkg"))
                                {
                                    int verStart = file.IndexOf(value, StringComparison.OrdinalIgnoreCase) + value.Length + 1;
                                    string ver   = file.Substring(verStart);
                                    ver          = ver.Substring(0, ver.Length - ".nupkg".Length);
                                    Version version;

                                    if (Version.TryParse(ver, out version))
                                    {
                                        if (!quiet.HasValue())
                                        {
                                            Reporter.Output.WriteLine($"Removing {value} version {version}...");
                                        }

                                        anyRemoved = true;
                                        file.Delete();
                                    }
                                }
                            }

                            if (!anyRemoved && !quiet.HasValue())
                            {
                                Reporter.Error.WriteLine($"Couldn't remove {value} as a template source.".Red().Bold());
                            }
                        }
                    }

                    return(Task.FromResult(0));
                }

                if (listOnly.HasValue())
                {
                    ListTemplates(template, source);
                    return(Task.FromResult(0));
                }

                IReadOnlyDictionary <string, string> parameters;

                try
                {
                    parameters = app.ParseExtraArgs(parametersFiles);
                }
                catch (Exception ex)
                {
                    Reporter.Error.WriteLine(ex.Message.Red().Bold());
                    app.ShowHelp();
                    return(Task.FromResult(-1));
                }

                return(TemplateCreator.Instantiate(app, template.Value ?? "", name, dir, source, help, alias, parameters, quiet.HasValue(), skipUpdateCheck.HasValue()));
            });

            int result;

            try
            {
                result = app.Execute(args);
            }
            catch (Exception ex)
            {
                AggregateException ax = ex as AggregateException;

                while (ax != null && ax.InnerExceptions.Count == 1)
                {
                    ex = ax.InnerException;
                    ax = ex as AggregateException;
                }

                Reporter.Error.WriteLine(ex.Message.Bold().Red());

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    ax = ex as AggregateException;

                    while (ax != null && ax.InnerExceptions.Count == 1)
                    {
                        ex = ax.InnerException;
                        ax = ex as AggregateException;
                    }

                    Reporter.Error.WriteLine(ex.Message.Bold().Red());
                }

                Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
                result = 1;
            }

            return(result);
        }
Ejemplo n.º 16
0
        static int Main(string[] args)
        {
            var logger = new ConsoleLogger();
            var app    = new CommandLineApplication();

            app.Name     = "coverlet";
            app.FullName = "Cross platform .NET Core code coverage tool";
            app.HelpOption("-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandArgument module              = app.Argument("<ASSEMBLY>", "Path to the test assembly.");
            CommandOption   target              = app.Option("-t|--target", "Path to the test runner application.", CommandOptionType.SingleValue);
            CommandOption   targs               = app.Option("-a|--targetargs", "Arguments to be passed to the test runner.", CommandOptionType.SingleValue);
            CommandOption   output              = app.Option("-o|--output", "Output of the generated coverage report", CommandOptionType.SingleValue);
            CommandOption   formats             = app.Option("-f|--format", "Format of the generated coverage report.", CommandOptionType.MultipleValue);
            CommandOption   threshold           = app.Option("--threshold", "Exits with error if the coverage % is below value.", CommandOptionType.SingleValue);
            CommandOption   thresholdTypes      = app.Option("--threshold-type", "Coverage type to apply the threshold to.", CommandOptionType.MultipleValue);
            CommandOption   excludeFilters      = app.Option("--exclude", "Filter expressions to exclude specific modules and types.", CommandOptionType.MultipleValue);
            CommandOption   includeFilters      = app.Option("--include", "Filter expressions to include only specific modules and types.", CommandOptionType.MultipleValue);
            CommandOption   excludedSourceFiles = app.Option("--exclude-by-file", "Glob patterns specifying source files to exclude.", CommandOptionType.MultipleValue);
            CommandOption   mergeWith           = app.Option("--merge-with", "Path to existing coverage result to merge.", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                if (string.IsNullOrEmpty(module.Value) || string.IsNullOrWhiteSpace(module.Value))
                {
                    throw new CommandParsingException(app, "No test assembly specified.");
                }

                if (!target.HasValue())
                {
                    throw new CommandParsingException(app, "Target must be specified.");
                }

                Coverage coverage = new Coverage(module.Value, excludeFilters.Values.ToArray(), includeFilters.Values.ToArray(), excludedSourceFiles.Values.ToArray(), mergeWith.Value());
                coverage.PrepareModules();

                Process process                          = new Process();
                process.StartInfo.FileName               = target.Value();
                process.StartInfo.Arguments              = targs.HasValue() ? targs.Value() : string.Empty;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.Start();
                logger.LogInformation(process.StandardOutput.ReadToEnd());
                process.WaitForExit();

                var dOutput         = output.HasValue() ? output.Value() : Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar.ToString();
                var dThreshold      = threshold.HasValue() ? int.Parse(threshold.Value()) : 0;
                var dThresholdTypes = thresholdTypes.HasValue() ? thresholdTypes.Values : new List <string>(new string[] { "line", "branch", "method" });

                logger.LogInformation("\nCalculating coverage result...");

                var result    = coverage.GetCoverageResult();
                var directory = Path.GetDirectoryName(dOutput);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                foreach (var format in (formats.HasValue() ? formats.Values : new List <string>(new string[] { "json" })))
                {
                    var reporter = new ReporterFactory(format).CreateReporter();
                    if (reporter == null)
                    {
                        throw new Exception($"Specified output format '{format}' is not supported");
                    }

                    var filename = Path.GetFileName(dOutput);
                    filename     = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename;
                    filename     = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}";

                    var report = Path.Combine(directory, filename);
                    logger.LogInformation($"  Generating report '{report}'");
                    File.WriteAllText(report, reporter.Report(result));
                }

                var summary               = new CoverageSummary();
                var exceptionBuilder      = new StringBuilder();
                var coverageTable         = new ConsoleTable("Module", "Line", "Branch", "Method");
                var thresholdFailed       = false;
                var overallLineCoverage   = summary.CalculateLineCoverage(result.Modules).Percent * 100;
                var overallBranchCoverage = summary.CalculateBranchCoverage(result.Modules).Percent * 100;
                var overallMethodCoverage = summary.CalculateMethodCoverage(result.Modules).Percent * 100;

                foreach (var _module in result.Modules)
                {
                    var linePercent   = summary.CalculateLineCoverage(_module.Value).Percent * 100;
                    var branchPercent = summary.CalculateBranchCoverage(_module.Value).Percent * 100;
                    var methodPercent = summary.CalculateMethodCoverage(_module.Value).Percent * 100;

                    coverageTable.AddRow(Path.GetFileNameWithoutExtension(_module.Key), $"{linePercent}%", $"{branchPercent}%", $"{methodPercent}%");

                    if (dThreshold > 0)
                    {
                        if (linePercent < dThreshold && dThresholdTypes.Contains("line"))
                        {
                            exceptionBuilder.AppendLine($"'{Path.GetFileNameWithoutExtension(_module.Key)}' has a line coverage '{linePercent}%' below specified threshold '{dThreshold}%'");
                            thresholdFailed = true;
                        }

                        if (branchPercent < dThreshold && dThresholdTypes.Contains("branch"))
                        {
                            exceptionBuilder.AppendLine($"'{Path.GetFileNameWithoutExtension(_module.Key)}' has a branch coverage '{branchPercent}%' below specified threshold '{dThreshold}%'");
                            thresholdFailed = true;
                        }

                        if (methodPercent < dThreshold && dThresholdTypes.Contains("method"))
                        {
                            exceptionBuilder.AppendLine($"'{Path.GetFileNameWithoutExtension(_module.Key)}' has a method coverage '{methodPercent}%' below specified threshold '{dThreshold}%'");
                            thresholdFailed = true;
                        }
                    }
                }

                logger.LogInformation(string.Empty);
                logger.LogInformation(coverageTable.ToStringAlternative());
                logger.LogInformation(string.Empty);
                logger.LogInformation($"Total Line {overallLineCoverage}%");
                logger.LogInformation($"Total Branch {overallBranchCoverage}%");
                logger.LogInformation($"Total Method {overallMethodCoverage}%");

                if (thresholdFailed)
                {
                    throw new Exception(exceptionBuilder.ToString().TrimEnd(Environment.NewLine.ToCharArray()));
                }

                return(process.ExitCode == 0 ? 0 : process.ExitCode);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException ex)
            {
                logger.LogError(ex.Message);
                app.ShowHelp();
                return(1);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(1);
            }
        }
Ejemplo n.º 17
0
        public StrykerOptions Build(
            string basePath,
            CommandOption reporter,
            CommandOption dashboardApiKey,
            CommandOption dashboardUrl,
            CommandOption reportersProjectName,
            CommandOption reportersModuleName,
            CommandOption reportersProjectVersion,
            CommandOption fallbackVersion,
            CommandOption projectUnderTestNameFilter,
            CommandOption additionalTimeoutMS,
            CommandOption excludedMutations,
            CommandOption ignoreMethods,
            CommandOption logLevel,
            CommandOption logToFile,
            CommandOption devMode,
            CommandOption coverageAnalysis,
            CommandOption abortTestOnFail,
            CommandOption configFilePath,
            CommandOption disableSimultaneousTesting,
            CommandOption maxConcurrentTestRunners,
            CommandOption thresholdHigh,
            CommandOption thresholdLow,
            CommandOption thresholdBreak,
            CommandOption filesToExclude,
            CommandOption filePatterns,
            CommandOption testRunner,
            CommandOption solutionPath,
            CommandOption languageVersion,
            CommandOption diff,
            CommandOption diffCompareToDashboard,
            CommandOption gitDiffTarget,
            CommandOption testProjects,
            CommandOption baselineStorageLocation,
            CommandOption azureSAS,
            CommandOption azureFileStorageUrl,
            CommandOption mutationLevel,
            CommandOption dashboardCompareFileExcludePatterns)
        {
            var fileLocation = Path.Combine(basePath, GetOption(configFilePath.Value(), CLIOptions.ConfigFilePath));

            if (File.Exists(fileLocation))
            {
                try
                {
                    _config = new ConfigurationBuilder()
                              .SetBasePath(basePath)
                              .AddJsonFile(fileLocation)
                              .Build()
                              .GetSection("stryker-config");
                }
                catch (FormatException formatException)
                {
                    throw new StrykerInputException("The stryker config file was in an incorrect format.", formatException.InnerException.Message);
                }
            }

            return(new StrykerOptions(
                       logger: _logger,
                       basePath: basePath,
                       reporters: GetOption(reporter.Value(), CLIOptions.Reporters),
                       dashboardApiKey: GetOption(dashboardApiKey.Value(), CLIOptions.DashboardApiKeyOption),
                       dashboardUrl: GetOption(dashboardUrl.Value(), CLIOptions.DashboardUrlOption),
                       diffIgnoreFiles: GetOption(dashboardCompareFileExcludePatterns.Value(), CLIOptions.DiffIgnoreFiles),
                       projectName: GetOption(reportersProjectName.Value(), CLIOptions.DashboardProjectNameOption),
                       moduleName: GetOption(reportersModuleName.Value(), CLIOptions.DashboardModuleNameOption),
                       projectVersion: GetOption(reportersProjectVersion.Value(), CLIOptions.DashboardProjectVersionOption),
                       fallbackVersion: GetOption(fallbackVersion.Value(), CLIOptions.DashboardFallbackVersionOption),
                       projectUnderTestNameFilter: GetOption(projectUnderTestNameFilter.Value(), CLIOptions.ProjectFileName),
                       additionalTimeoutMS: GetOption(additionalTimeoutMS.Value(), CLIOptions.AdditionalTimeoutMS),
                       excludedMutations: GetOption(excludedMutations.Value(), CLIOptions.ExcludedMutations),
                       ignoredMethods: GetOption(ignoreMethods.Value(), CLIOptions.IgnoreMethods),
                       logLevel: GetOption(logLevel.Value(), CLIOptions.LogLevel),
                       logToFile: GetOption(logToFile.HasValue(), CLIOptions.LogToFile),
                       devMode: GetOption(devMode.HasValue(), CLIOptions.DevMode),
                       maxConcurrentTestRunners: GetOption(maxConcurrentTestRunners.Value(), CLIOptions.MaxConcurrentTestRunners),
                       coverageAnalysis: GetOption(coverageAnalysis.Value(), CLIOptions.CoverageAnalysis),
                       abortTestOnFail: GetOption(abortTestOnFail.HasValue(), CLIOptions.AbortTestOnFail),
                       disableSimultaneousTesting: GetOption(disableSimultaneousTesting.HasValue(), CLIOptions.DisableTestingMix),
                       thresholdHigh: GetOption(thresholdHigh.Value(), CLIOptions.ThresholdHigh),
                       thresholdLow: GetOption(thresholdLow.Value(), CLIOptions.ThresholdLow),
                       thresholdBreak: GetOption(thresholdBreak.Value(), CLIOptions.ThresholdBreak),
                       filesToExclude: GetOption(filesToExclude.Value(), CLIOptions.FilesToExclude),
                       mutate: GetOption(filePatterns.Value(), CLIOptions.Mutate),
                       testRunner: GetOption(testRunner.Value(), CLIOptions.TestRunner),
                       solutionPath: GetOption(solutionPath.Value(), CLIOptions.SolutionPath),
                       languageVersion: GetOption(languageVersion.Value(), CLIOptions.LanguageVersionOption),
                       diff: (GetOption(diff.HasValue(), CLIOptions.Diff)) || GetOption(diffCompareToDashboard.HasValue(), CLIOptions.DashboardCompare),
                       compareToDashboard: GetOption(diffCompareToDashboard.HasValue(), CLIOptions.DashboardCompare),
                       gitDiffTarget: GetOption(gitDiffTarget.Value(), CLIOptions.GitDiffTarget),
                       baselineStorageLocation: GetOption(baselineStorageLocation.Value(), CLIOptions.BaselineStorageLocation),
                       azureSAS: GetOption(azureSAS.Value(), CLIOptions.AzureSAS),
                       azureFileStorageUrl: GetOption(azureFileStorageUrl.Value(), CLIOptions.AzureFileStorageUrl),
                       mutationLevel: GetOption(mutationLevel.Value(), CLIOptions.MutationLevel),
                       testProjects: GetOption(testProjects.Value(), CLIOptions.TestProjects)));
        }
Ejemplo n.º 18
0
        public static async Task Main(string[] args)
        {
            // Set Up App Info
            var app = new CommandLineApplication();

            app.Name        = "Social Media Randomizer - CSV";
            app.Description = "This tool will pick a random entry from a csv file.";
            app.HelpOption("-?|-h|--help");

            // Set up Options/Parameters
            CommandOption entriesOption = app.Option <string>("-e|--entries <filePath>", "This is the path where the CSV file with the entries are located.",
                                                              CommandOptionType.SingleValue);

            CommandOption configOption = app.Option <string>("-c|--config <filePath>", "This is the path where the CSV file with the configuration for entry types & weights are located.",
                                                             CommandOptionType.SingleValue);

            CommandOption shuffleCountOption = app.Option <int>("-s|--shuffle <count>", "This is number of times the list will be shuffled before an entry is chosen. Default is 10.",
                                                                CommandOptionType.SingleValue);

            // Set up what happens when the App Runs
            app.OnExecuteAsync(async cancellationToken =>
            {
                // Check for Options/Parameters
                if (!entriesOption.HasValue() || !File.Exists(entriesOption.Value()))
                {
                    Utilities.Log("❌ Please provide a valid file for the list of entries.", ConsoleColor.Red);
                    return(400);
                }

                if (!configOption.HasValue() || !File.Exists(configOption.Value()))
                {
                    Utilities.Log("❌ Please provide a valid file for your configuration.", ConsoleColor.Red);
                    return(400);
                }

                int shuffleCount = shuffleCountOption.HasValue() ? Convert.ToInt32(shuffleCountOption.Value()) : 10;

                // Get Config & Data from CSV Files
                List <EntryWeight> config  = CsvParser.GetWeights(configOption.Value());
                List <EntryRecord> entries = CsvParser.GetEntries(entriesOption.Value());

                // Apply Weight to Entries
                var weightedEntries = new List <EntryRecord>();

                foreach (EntryRecord entry in entries)
                {
                    int?multiplier = config.FirstOrDefault(c => c.Id == entry.EntryTypeId)?.NumberOfEntries;

                    if (multiplier == null)
                    {
                        Utilities.Log($"❌ No Config Entry Found for Id: {entry.EntryTypeId}", ConsoleColor.Red);
                        Utilities.LogWithKeyInput("Enter any key to exit ...", ConsoleColor.Gray);
                        return(400);
                    }

                    weightedEntries.AddRange(Enumerable.Range(0, multiplier.Value).Select(e => entry).ToList());
                }

                // Shuffle Entries
                Utilities.Log($"Shuffling {weightedEntries.Count} Entries\n", ConsoleColor.DarkGreen);

                for (int i = 0; i < shuffleCount; i++)
                {
                    weightedEntries = weightedEntries.Shuffle().ToList();
                }

                // Pick Random Entry
                EntryRecord winner       = weightedEntries.PickRandom(1).Single();
                EntryWeight winnerSource = config.First(c => c.Id == winner.EntryTypeId);

                Utilities.Log("--------------------------------------------------", ConsoleColor.DarkCyan);
                Utilities.Log(">>                 Winner Found                 <<", ConsoleColor.DarkCyan);
                Utilities.Log($">>{" ",46}<<", ConsoleColor.DarkCyan);
                Utilities.Log($">>  Winner       : {winner.Participant,-28} <<", ConsoleColor.DarkCyan);
                Utilities.Log($">>  Entry Source : {winnerSource.Source,-28} <<", ConsoleColor.DarkCyan);
                Utilities.Log($">>  Entry Method : {winnerSource.TypeOfEntry,-28} <<", ConsoleColor.DarkCyan);
                Utilities.Log($">>{" ",46}<<", ConsoleColor.DarkCyan);
                Utilities.Log("--------------------------------------------------\n", ConsoleColor.DarkCyan);

                return(200);
            });

            // Run the App
            try
            {
                Utilities.Log(">> Initiating the Randomizer\n", ConsoleColor.DarkGreen);
                await app.ExecuteAsync(args);

                Utilities.LogWithKeyInput("Enter any key to exit ...", ConsoleColor.Gray);
            }
            catch (CommandParsingException ex)
            {
                Utilities.Log($"❌ An error has occurred with your command line arguments: {ex.Message}", ConsoleColor.Red);
                Utilities.LogWithKeyInput("Enter any key to exit ...", ConsoleColor.Gray);
            }
            catch (Exception ex)
            {
                Utilities.Log($"❌ An exception was thrown: {ex.Message}", ConsoleColor.Red);
                Utilities.LogWithKeyInput("Enter any key to exit ...", ConsoleColor.Gray);
            }
        }
Ejemplo n.º 19
0
        private static int ClusterDataset(string filename, CommandArgument clusterNumArgs, CommandOption sizeOption)
        {
            // make sure the user entered an argument to this program
            if (string.IsNullOrWhiteSpace(filename))
            {
                Console.WriteLine("The --cluster option requires you to give one XML file on the command line.");
                return(ExitFailure);
            }

            var clusterValue = clusterNumArgs.Value ?? "2";
            var sizeValue    = sizeOption.HasValue() ? sizeOption.Value() : "8000";

            if (!uint.TryParse(clusterValue, out var numClusters))
            {
                return(ExitFailure);
            }

            if (!uint.TryParse(sizeValue, out var chipSize))
            {
                return(ExitFailure);
            }

            using (var data = Dlib.ImageDatasetMetadata.LoadImageDatasetMetadata(filename))
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(filename);


                double aspectRatio = MeanAspectRatio(data);

                var images = new Array <Array2D <RgbPixel> >();
                var feats  = new List <Matrix <double> >();

                var dataImages = data.Images;
                //console_progress_indicator pbar(dataImages.Length);
                // extract all the object chips and HOG features.
                Console.WriteLine("Loading image data...");

                for (int i = 0, count = dataImages.Count; i < count; ++i)
                {
                    //pbar.print_status(i);
                    if (!HasNonIgnoredBoxes(dataImages[i]))
                    {
                        continue;
                    }

                    using (var img = Dlib.LoadImage <RgbPixel>(dataImages[i].FileName))
                    {
                        var boxes = dataImages[i].Boxes;
                        for (var j = 0; j < boxes.Count; ++j)
                        {
                            if (boxes[j].Ignore || boxes[j].Rect.Area < 10)
                            {
                                continue;
                            }

                            var rect = new DRectangle(boxes[j].Rect);
                            rect = DRectangle.SetAspectRatio(rect, aspectRatio);
                            using (var chipDetail = new ChipDetails(rect, chipSize))
                            {
                                var chip = Dlib.ExtractImageChip <RgbPixel>(img, chipDetail);
                                Dlib.ExtractFHogFeatures <RgbPixel>(chip, out var feature);
                                feats.Add(feature);
                                images.PushBack(chip);
                            }
                        }
                    }
                }

                if (!feats.Any())
                {
                    Console.WriteLine("No non-ignored object boxes found in the XML dataset.  You can't cluster an empty dataset.");
                    return(ExitFailure);
                }

                Console.WriteLine("\nClustering objects...");
                var assignments = AngularCluster(feats, numClusters).ToList();


                // Now output each cluster to disk as an XML file.
                for (uint c = 0; c < numClusters; ++c)
                {
                    // We are going to accumulate all the image metadata for cluster c.  We put it
                    // into idata so we can sort the images such that images with central chips
                    // come before less central chips.  The idea being to get the good chips to
                    // show up first in the listing, making it easy to manually remove bad ones if
                    // that is desired.
                    var idata = new List <Pair <double, Image> >(dataImages.Count);
                    var idx   = 0;
                    for (int i = 0, count = dataImages.Count; i < count; ++i)
                    {
                        idata.Add(new Pair <double, Image> {
                            Second = new Image()
                        });

                        idata[i].First           = double.PositiveInfinity;
                        idata[i].Second.FileName = dataImages[i].FileName;

                        if (!HasNonIgnoredBoxes(dataImages[i]))
                        {
                            continue;
                        }

                        var idataBoxes = new List <Box>();
                        var boxes      = dataImages[i].Boxes;
                        for (var j = 0; j < boxes.Count; ++j)
                        {
                            if (boxes[j].Ignore || boxes[j].Rect.Area < 10)
                            {
                                continue;
                            }

                            // If this box goes into cluster c then update the score for the whole
                            // image based on this boxes' score.  Otherwise, mark the box as
                            // ignored.
                            if (assignments[idx].C == c)
                            {
                                idata[i].First = Math.Min(idata[i].First, assignments[idx].Distance);
                            }
                            else
                            {
                                idataBoxes.Last().Ignore = true;
                            }

                            ++idx;
                        }
                    }

                    // now save idata to an xml file.
                    idata.Sort((a, b) =>
                    {
                        var diff = a.First - b.First;
                        return(diff > 0 ? 1 : diff < 0 ? -1 : 0);
                    });

                    using (var cdata = new Dataset())
                    {
                        cdata.Comment = $"{data.Comment}\n\n This file contains objects which were clustered into group {c + 1} of {numClusters} groups with a chip size of {chipSize} by imglab.";
                        cdata.Name    = data.Name;

                        var cdataImages = cdata.Images;
                        for (var i = 0; i < idata.Count; ++i)
                        {
                            // if this image has non-ignored boxes in it then include it in the output.
                            if (!double.IsPositiveInfinity(idata[i].First))
                            {
                                cdataImages.Add(idata[i].Second);
                            }
                        }

                        var outfile = $"cluster_{c + 1:D3}.xml";
                        Console.WriteLine($"Saving {outfile}");
                        Dlib.ImageDatasetMetadata.SaveImageDatasetMetadata(cdata, outfile);
                    }
                }

                // Now output each cluster to disk as a big tiled jpeg file.  Sort everything so, just
                // like in the xml file above, the best objects come first in the tiling.
                assignments.Sort();
                for (uint c = 0; c < numClusters; ++c)
                {
                    var temp = new Array <Array2D <RgbPixel> >();
                    for (var i = 0; i < assignments.Count(); ++i)
                    {
                        if (assignments[i].C == c)
                        {
                            temp.PushBack(images[(int)assignments[i].Index]);
                        }
                    }

                    var outfile = $"cluster_{c + 1:D3}.jpg";
                    Console.WriteLine($"Saving {outfile}");
                    using (var tile = Dlib.TileImages(temp))
                        Dlib.SaveJpeg(tile, outfile);
                }
            }

            return(ExitSuccess);
        }
Ejemplo n.º 20
0
        public static void Main(string[] args)
        {
            var cmd = new CommandLineApplication
            {
                Name        = "QRConsole",
                FullName    = "QRConsole",
                Description = "Tool that encodes input value into a QR code and prints it in the console"
            };

            cmd.HelpOption("-h|--help|--herp");

            CommandOption contentTextOption = cmd.Option("-t|--text", "Text to encode into a QR code", CommandOptionType.SingleValue);
            CommandOption contentFileOption = cmd.Option("-f|--file", "File containing text to encode into a QR code", CommandOptionType.SingleValue);
            CommandOption clearOption       = cmd.Option("-c|--clear", "Clears the console before printing the QR code", CommandOptionType.NoValue);
            CommandOption noWaitOption      = cmd.Option("-w|--no-wait", "Does not pause before printing the QR code", CommandOptionType.NoValue);
            CommandOption base64Option      = cmd.Option("-b|--base64", "Encodes the file content to base 64 before encoding it to QR code (useful for binary files)", CommandOptionType.NoValue);
            CommandOption encodingOption    = cmd.Option("-e|--encoding", "Encoding of the file content", CommandOptionType.SingleValue);

            if (args.Length == 0)
            {
                cmd.ShowHelp();
                return;
            }

            try
            {
                cmd.Execute(args);
            }
            catch (CommandParsingException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (contentTextOption.HasValue() == false && contentFileOption.HasValue() == false)
            {
                cmd.ShowHelp();
                return;
            }
            else if (contentTextOption.HasValue() && contentFileOption.HasValue())
            {
                Console.WriteLine("Text and file are mutually exclusive");
                return;
            }

            string content = null;

            if (contentTextOption.HasValue())
            {
                content = contentTextOption.Value();
            }
            else if (contentFileOption.HasValue())
            {
                string filename = Path.GetFullPath(contentFileOption.Value());

                if (File.Exists(filename) == false)
                {
                    Console.WriteLine($"Impossible to find file '{filename}'");
                    return;
                }

                Encoding encoding = Encoding.UTF8;

                if (encodingOption.HasValue())
                {
                    encoding = RetrieveEncoding(encodingOption.Value());
                }

                if (base64Option.HasValue())
                {
                    content = Convert.ToBase64String(File.ReadAllBytes(filename));
                }
                else
                {
                    content = File.ReadAllText(filename, encoding);
                }
            }

            Run(content, noWaitOption.HasValue(), clearOption.HasValue());
        }
        protected override int ExecuteCommand()
        {
            if (!_sourceOption.HasValue())
            {
                Out.WriteLine("The source corpus was not specified.");
                return(1);
            }

            if (!_targetOption.HasValue())
            {
                Out.WriteLine("The target corpus was not specified.");
                return(1);
            }

            if (!ValidateTextCorpusOption(_sourceOption.Value(), out string sourceType, out string sourcePath))
            {
                Out.WriteLine("The specified source corpus is invalid.");
                return(1);
            }

            if (!ValidateTextCorpusOption(_targetOption.Value(), out string targetType, out string targetPath))
            {
                Out.WriteLine("The specified target corpus is invalid.");
                return(1);
            }

            string alignmentsType = null, alignmentsPath = null;

            if (_alignmentsOption != null && !ValidateAlignmentsOption(_alignmentsOption.Value(), out alignmentsType,
                                                                       out alignmentsPath))
            {
                Out.WriteLine("The specified partial alignments corpus is invalid.");
                return(1);
            }

            if (!ValidateWordTokenizerOption(_sourceWordTokenizerOption.Value()))
            {
                Out.WriteLine("The specified source word tokenizer type is invalid.");
                return(1);
            }

            if (!ValidateWordTokenizerOption(_targetWordTokenizerOption.Value()))
            {
                Out.WriteLine("The specified target word tokenizer type is invalid.");
                return(1);
            }

            if (_maxCorpusSizeOption.HasValue())
            {
                if (!int.TryParse(_maxCorpusSizeOption.Value(), out int maxCorpusSize) || maxCorpusSize <= 0)
                {
                    Out.WriteLine("The specified maximum corpus size is invalid.");
                    return(1);
                }
                MaxParallelCorpusCount = maxCorpusSize;
            }

            StringTokenizer sourceWordTokenizer = CreateWordTokenizer(_sourceWordTokenizerOption.Value());
            StringTokenizer targetWordTokenizer = CreateWordTokenizer(_targetWordTokenizerOption.Value());

            SourceCorpus     = CreateTextCorpus(sourceWordTokenizer, sourceType, sourcePath);
            TargetCorpus     = CreateTextCorpus(targetWordTokenizer, targetType, targetPath);
            AlignmentsCorpus = null;
            if (_alignmentsOption != null && _alignmentsOption.HasValue())
            {
                AlignmentsCorpus = CreateAlignmentsCorpus(alignmentsType, alignmentsPath);
            }

            ISet <string> includeTexts          = null;

            if (_includeOption.HasValue())
            {
                includeTexts = GetTexts(_includeOption.Values);
            }

            ISet <string> excludeTexts = null;

            if (_excludeOption.HasValue())
            {
                excludeTexts = GetTexts(_excludeOption.Values);
            }

            if (includeTexts != null || excludeTexts != null)
            {
                bool Filter(string id)
                {
                    if (excludeTexts != null && excludeTexts.Contains(id))
                    {
                        return(false);
                    }

                    if (includeTexts != null && includeTexts.Contains(id))
                    {
                        return(true);
                    }

                    return(includeTexts == null);
                }

                SourceCorpus = new FilteredTextCorpus(SourceCorpus, text => Filter(text.Id));
                TargetCorpus = new FilteredTextCorpus(TargetCorpus, text => Filter(text.Id));
                if (_alignmentsOption != null && _alignmentsOption.HasValue())
                {
                    AlignmentsCorpus = new FilteredTextAlignmentCorpus(AlignmentsCorpus,
                                                                       alignments => Filter(alignments.Id));
                }
            }

            ParallelCorpus = new ParallelTextCorpus(SourceCorpus, TargetCorpus, AlignmentsCorpus);

            return(0);
        }
Ejemplo n.º 22
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()));

                    X509TrustStore.InitializeForDotNetSdk(args.Logger);

                    ISignCommandRunner runner = getCommandRunner();
                    int result = await runner.ExecuteCommandAsync(args);
                    return(result);
                });
            });
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <remarks>
        /// Possible Arguments
        /// 1) If you want to dump the certs from local machine only and make it work for one environment config.
        ///     --ConfigureCerts "Certs" --ApplicationInsightsKey "AIKeyHere" --CertsToConfigure "ClusterCert;MyLocalMachine;ClusterCertThumbprint,SSLCert;MyLocalMachine;SSLCertThumbprint"
        /// 2) If you want to dump the certs from local machine and KeyVault and make it work for one environment config.
        ///     --ConfigureCerts "Certs" --ApplicationInsightsKey "AIKeyHere" --CertsToConfigure "ClusterCert;MyLocalMachine;ClusterCertThumbprint,SSLCert;KeyVault;SSLSecretName" --KeyVaultUri "https://dummyvault.vault.azure.net/" --KeyVaultClientId "1dc8b8b3-be3e-482a-b56b-9092c91aa4b2" -KeyVaultClientSecret "keyvaultappsecret"
        /// 3) If you want to dump the certs from local machine and make it work for different environments having different configs.
        ///     a) Set the arguments to --UseEnvironmentVariables (or -UseEnv)
        ///     b) And set the Environment variables
        ///         i) ConfigureCerts to Certs
        ///         ii) ApplicationInsightsKey to AiKeyHere
        ///         iii) CertsToConfigure to ClusterCert;MyLocalMachine;ClusterCertThumbprint,SSLCert;MyLocalMachine;SSLCertThumbprint
        ///        Similarily other options can be set in environment variables to enable rest of the options like KeyVault.
        /// </remarks>
        private static void Main(string[] args)
        {
            CommandLineApplication commandLineApplication        = new CommandLineApplication(false);
            CommandOption          useEnvironmentVariablesOption = commandLineApplication.Option(
                "-UseEnv | --UseEnvironmentVariables",
#pragma warning disable SA1118 // Parameter should not span multiple lines
                "Instead of using specified options, use Environment varibles with the same name (except the -- at start). This is to enable different integrations for different environments." +
                " If you use this, command line values are ignored.",
#pragma warning restore SA1118 // Parameter should not span multiple lines
                CommandOptionType.NoValue);
            CommandOption configureCertsOption = commandLineApplication.Option(
                "--ConfigureCerts <DirectoryRelativePath>",
                "Configures certs for Traefik by dropping them into the specifiec directory (relative to executing assembly). Certs are dropped in .key and .crt format.",
                CommandOptionType.SingleValue);
            CommandOption certsToConfigureOption = commandLineApplication.Option(
                "--CertsToConfigure <FormattedCertsToConfigure>",
#pragma warning disable SA1118 // Parameter should not span multiple lines
                "The value looks something like SSLCert;MyLocalMachine;7ce597cba5ae055fa37f222aaffc1007c3d61277,ClusterCert;KeyVault;ClusterCertSecretName. The format is" +
                "NameOfTheCert1;Source1;<Cert identifier1>,NameOfCert2;Source2;<Cert identifier2>." +
                "Possible Source values are 'MyLocalMachine' which fetches certs from Personal under LocalMachine Store and " +
                "'KeyVault' which fetches the cert from KeyVault. If KeyVault is specified, Specify ClientId and secret using --KeyVaultUri, --KeyVaultClientId, --KeyVaultClientSecret or --KeyVaultClientCert",
#pragma warning restore SA1118 // Parameter should not span multiple lines
                CommandOptionType.SingleValue);
            CommandOption keyVaultUriOption = commandLineApplication.Option(
                "--KeyVaultUri <KeyVaultUri>",
                "Uri to use for KeyVault connection. Use --KeyVaultClientId to specify ClientId of the app to use to access Key Vault.",
                CommandOptionType.SingleValue);
            CommandOption keyVaultClientIdOption = commandLineApplication.Option(
                "--KeyVaultClientId <ClientId>",
                "Client Id to use for KeyVault connection. Specify the secret by using --KeyVaultClientSecret or --KeyVaultClientCert.",
                CommandOptionType.SingleValue);
            CommandOption keyVaultClientSecretOption = commandLineApplication.Option(
                "--KeyVaultClientSecret <ClientSecret>",
                "Client secret to use for KeyVault connection. Specify the ClientId using --KeyVaultClientId.",
                CommandOptionType.SingleValue);
            CommandOption keyVaultClientCertThumbprintOption = commandLineApplication.Option(
                "--KeyVaultClientCert <ClientCertThumbprint>",
                "Cert thumbprint to be used to contact key vault. The cert needs to be present on the machine. Specify the ClientId using --KeyVaultClientId.",
                CommandOptionType.SingleValue);
            CommandOption applicationInsightsInstrumentationKeyOption = commandLineApplication.Option(
                "--ApplicationInsightsKey <InstrumentationKey>",
                "Instrumentation key to push traces for PreConfiguration into Application Insights.",
                CommandOptionType.SingleValue);

            commandLineApplication.HelpOption("-h|--help|-?");
            commandLineApplication.OnExecute(async() =>
            {
                try
                {
                    bool useEnvironmentVariables = useEnvironmentVariablesOption.HasValue();
                    if (applicationInsightsInstrumentationKeyOption.HasValueEx(useEnvironmentVariables))
                    {
                        Logger.ConfigureLogger(applicationInsightsInstrumentationKeyOption.GetValueEx(useEnvironmentVariables));
                    }

                    if (configureCertsOption.HasValueEx(useEnvironmentVariables))
                    {
                        ExitCode certHandlerExitCode = await CertificateHandler.ProcessAsync(
                            configureCertsOption.GetValueEx(useEnvironmentVariables),
                            certsToConfigureOption.GetValueEx(useEnvironmentVariables),
                            keyVaultUriOption.GetValueEx(useEnvironmentVariables),
                            keyVaultClientIdOption.GetValueEx(useEnvironmentVariables),
                            keyVaultClientSecretOption.GetValueEx(useEnvironmentVariables),
                            keyVaultClientCertThumbprintOption.GetValueEx(useEnvironmentVariables)).ConfigureAwait(false);

                        if (certHandlerExitCode != ExitCode.Success)
                        {
                            return((int)certHandlerExitCode);
                        }
                    }

                    return((int)ExitCode.Success);
                }
                catch (AggregateException aggrEx)
                {
                    foreach (Exception innerException in aggrEx.InnerExceptions)
                    {
                        Logger.LogError(CallInfo.Site(), innerException);
                    }

                    return((int)ExitCode.UnknownFailure);
                }
                catch (Exception ex)
                {
                    Logger.LogError(CallInfo.Site(), ex);

                    return((int)ExitCode.UnknownFailure);
                }
            });

            commandLineApplication.Execute(args);
        }
Ejemplo n.º 24
0
        private async static Task <int> Run()
        {
            string   hubUrl = _optionUrl.HasValue() ? _optionUrl.Value() : DefaultUrl;
            int      totalNumberOfClients = _optionClients.HasValue() ? int.Parse(_optionClients.Value()) : DefaultClients;
            int      bunchSize            = _optionBunchSize.HasValue() ? int.Parse(_optionBunchSize.Value()) : DefaultBunchSize;
            TimeSpan relaxation           = TimeSpan.FromSeconds(_optionRelaxation.HasValue() ? int.Parse(_optionRelaxation.Value()) : DefaultRelaxation);
            TimeSpan monitoring           = TimeSpan.FromMilliseconds(_optionMonitoring.HasValue() ? int.Parse(_optionMonitoring.Value()) : DefaultMonitoring);
            int      connects             = _optionConnects.HasValue() ? int.Parse(_optionConnects.Value()) : DefaultConnects;

            Console.WriteLine($"HUB_URL: {hubUrl}");
            Console.WriteLine($"CLIENTS_NUMBER: {totalNumberOfClients}");
            Console.WriteLine($"BUNCH_SIZE: {bunchSize}");
            Console.WriteLine($"RELAX_TIME: {relaxation}");
            Console.WriteLine($"MONITORING_TIME: {monitoring}");
            Console.WriteLine($"CONNECTION_ATTEMPTS: {connects}");
            Console.WriteLine();

            if (totalNumberOfClients < 1)
            {
                throw new ArgumentOutOfRangeException($"totalNumberOfClients ({totalNumberOfClients}) must be greater 0");
            }
            if (bunchSize < 1)
            {
                throw new ArgumentOutOfRangeException($"bunchSize ({bunchSize}) must be greater 0");
            }
            if (bunchSize > totalNumberOfClients)
            {
                throw new ArgumentOutOfRangeException($"bunchSize ({bunchSize}) may not be greater than totalNumberOfClients ({totalNumberOfClients}).");
            }

            var clients = Enumerable.Range(0, totalNumberOfClients).Select(i => new HubClient(hubUrl, connects)).ToArray();
            var monitor = new Monitor(clients)
            {
                CheckPeriod = monitoring
            };

            _ = monitor.Run().ConfigureAwait(false); // Just run and forget

            Console.WriteLine($"*** Start connections by {bunchSize} *** ");
            var startTime = DateTime.Now;

            for (int idx = 0; idx < totalNumberOfClients; idx += bunchSize)
            {
                var connectTasks = clients.Skip(idx).Take(bunchSize).Select(c => c.Connect());
                await Task.WhenAll(connectTasks).ConfigureAwait(false);

                await Task.Delay(relaxation).ConfigureAwait(false);
            }
            Console.WriteLine($"*** Connections established in {DateTime.Now - startTime}***");

            var connectException = clients.FirstOrDefault(c => c.ConnectExeption != null)?.ConnectExeption;
            var closeException   = clients.FirstOrDefault(c => c.CloseExeption != null)?.CloseExeption;

            if (connectException != null)
            {
                Console.WriteLine($"\n*** One of connect exceptions:\n{connectException}");
            }

            if (closeException != null)
            {
                Console.WriteLine($"\n*** One of close exceptions:\n{closeException}");
            }

            await Task.Delay(-1);

            return(0);
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            CommandLineApplication commandLine = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name        = "TD4",
                Description = "(c) 2019 JL Computer Inc. TD4++ CPU Developer Kit.\nOptimizing assembler"
            };

            string outputFile;
            string links;
            bool   optimize;

            var           argument     = commandLine.Argument("filename", "Source .s file", false);
            CommandOption output       = commandLine.Option("-o | --Output <output>", "Ouput file name", CommandOptionType.SingleValue);
            CommandOption target       = commandLine.Option("-t | --Target <target>", "Output target. \n\t\t\'td4e\' produces binary output for TD4+ processor. Classic TD4 programs should be assembled using this option. TD4+ is set by default. \n\t\t\'td4e8\' produces code for TD4++ which have 8bit Im. \n\t\t\'asm\' produces assembler code. \n\t\t\'asm8\' produces 8bit assembler code", CommandOptionType.SingleValue);
            CommandOption libraries    = commandLine.Option("-l | --Link <location>", "Libraries location (if not default)", CommandOptionType.SingleValue);
            CommandOption verbose      = commandLine.Option("-v | --Verbose", "Verbose mode", CommandOptionType.NoValue);
            CommandOption useTracerKey = commandLine.Option("-T | --Tracer", "Use code tracer", CommandOptionType.NoValue);
            CommandOption optimization = commandLine.Option("-O | --Optimize", "Optimize assembly (experimental)", CommandOptionType.NoValue);
            CommandOption configFile   = commandLine.Option("-c | --Configuration <file.conf>", "Machine configuration file", CommandOptionType.SingleValue);

            commandLine.HelpOption("-? | -h | --Help");
            commandLine.OnExecute(() =>
            {
                if (output.HasValue())
                {
                    outputFile = output.Value();
                    if (outputFile == null)
                    {
                        outputFile = "a.out";
                    }
                    Program.outputFile = outputFile;
                    verboseMode        = verbose.HasValue();
                    useTracer          = useTracerKey.HasValue();
                    if (target.HasValue())
                    {
                        if (target.Value() == "td4e")
                        {
                            makeBinary = true;
                            eightBit   = false;
                        }
                        else if (target.Value() == "td4e8")
                        {
                            makeBinary = true;
                            eightBit   = true;
                        }
                        else if (target.Value() == "asm")
                        {
                            makeBinary = false;
                            eightBit   = false;
                        }
                        else if (target.Value() == "asm8")
                        {
                            makeBinary = false;
                            eightBit   = true;
                        }
                        else
                        {
                            Console.WriteLine("Unknown target: \"{0}\". Aborting.", target.Value());
                            Environment.Exit(1);
                        }
                    }
                    if (configFile.HasValue())
                    {
                        configExists = true;
                        config       = CodeIO.LoadConfig(configFile.Value());
                    }
                    optimize = optimization.HasValue();
                    links    = libraries.Value();
                    if (links == null)
                    {
                        links = Directory.GetCurrentDirectory();
                    }
                    if (verboseMode)
                    {
                        Console.WriteLine("TD4++ Assembler v3.0");
                        Console.WriteLine("-=-=Session info=-=-");
                        Console.WriteLine("Source file: " + argument.Value);
                        Console.WriteLine("Output file: " + outputFile);
                        Console.WriteLine("Libraries location: " + links);
                        Console.WriteLine("Use optimizer: " + optimize.ToString());
                        Console.WriteLine("Use tracer: " + useTracer.ToString());
                        Console.WriteLine("Target: {0}", target.Value());
                        Console.WriteLine("---Verbose mode---");
                    }
                    Assembly assembly = new Assembly(argument.Value);
                    Utilities.Utilities.VerbouseOut("Parsing finished");
                    if (optimize)
                    {
                        Optimizer.Optimizer opt = new Optimizer.Optimizer(assembly);
                        Utilities.Utilities.VerbouseOut("Optimiztion finished");
                    }
                    //Output
                    Utilities.Utilities.VerbouseOut("-=-=Writing=-=-");
                    if (makeBinary)
                    {
                        CodeIO.WriteAssembly(assembly.Linker());
                    }
                    else
                    {
                        CodeIO.WriteSource(assembly.Linker());
                    }
                    Utilities.Utilities.VerbouseOut("DONE");
                }
                else
                {
                    commandLine.ShowHint();
                }
                return(0);
            });
            commandLine.Execute(args);
        }
Ejemplo n.º 26
0
        public static int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name                 = "ApiCompat",
                FullName             = "A command line tool to verify that two sets of APIs are compatible.",
                ResponseFileHandling = ResponseFileHandling.ParseArgsAsSpaceSeparated
            };

            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandArgument contracts = app.Argument("contracts", "Comma delimited list of assemblies or directories of assemblies for all the contract assemblies.");

            contracts.IsRequired();
            CommandOption implDirs = app.Option("-i|--impl-dirs", "Comma delimited list of directories to find the implementation assemblies for each contract assembly.", CommandOptionType.SingleValue);

            implDirs.IsRequired(allowEmptyStrings: true);
            CommandOption baseline                     = app.Option("-b|--baseline", "Comma delimited list of files to skip known diffs.", CommandOptionType.SingleValue);
            CommandOption validateBaseline             = app.Option("--validate-baseline", "Validates that baseline files don't have invalid/unused diffs.", CommandOptionType.NoValue);
            CommandOption mdil                         = app.Option("-m|--mdil", "Enforce MDIL servicing rules in addition to IL rules.", CommandOptionType.NoValue);
            CommandOption outFilePath                  = app.Option("-o|--out", "Output file path. Default is the console.", CommandOptionType.SingleValue);
            CommandOption leftOperand                  = app.Option("-l|--left-operand", "Name for left operand in comparison, default is 'contract'.", CommandOptionType.SingleValue);
            CommandOption rightOperand                 = app.Option("-r|--right-operand", "Name for right operand in comparison, default is 'implementation'.", CommandOptionType.SingleValue);
            CommandOption listRules                    = app.Option("--list-rules", "Outputs all the rules. If this options is supplied all other options are ignored.", CommandOptionType.NoValue);
            CommandOption remapFile                    = app.Option("--remap-file", "File with a list of type and/or namespace remappings to consider apply to names while diffing.", CommandOptionType.SingleValue);
            CommandOption skipGroupByAssembly          = app.Option("--skip-group-by-assembly", "Skip grouping the differences by assembly instead of flattening the namespaces.", CommandOptionType.NoValue);
            CommandOption skipUnifyToLibPath           = app.Option("--skip-unify-to-lib-path", "Skip unifying the assembly references to the loaded assemblies and the assemblies found in the given directories (contractDepends and implDirs).", CommandOptionType.NoValue);
            CommandOption resolveFx                    = app.Option("--resolve-fx", "If a contract or implementation dependency cannot be found in the given directories, fallback to try to resolve against the framework directory on the machine.", CommandOptionType.NoValue);
            CommandOption contractDepends              = app.Option("--contract-depends", "Comma delimited list of directories used to resolve the dependencies of the contract assemblies.", CommandOptionType.SingleValue);
            CommandOption contractCoreAssembly         = app.Option("--contract-core-assembly", "Simple name for the core assembly to use.", CommandOptionType.SingleValue);
            CommandOption ignoreDesignTimeFacades      = app.Option("--ignore-design-time-facades", "Ignore design time facades in the contract set while analyzing.", CommandOptionType.NoValue);
            CommandOption warnOnIncorrectVersion       = app.Option("--warn-on-incorrect-version", "Warn if the contract version number doesn't match the found implementation version number.", CommandOptionType.NoValue);
            CommandOption warnOnMissingAssemblies      = app.Option("--warn-on-missing-assemblies", "Warn if the contract assembly cannot be found in the implementation directories. Default is to error and not do analysis.", CommandOptionType.NoValue);
            CommandOption excludeNonBrowsable          = app.Option("--exclude-non-browsable", "When MDIL servicing rules are not being enforced, exclude validation on types that are marked with EditorBrowsable(EditorBrowsableState.Never).", CommandOptionType.NoValue);
            CommandOption excludeAttributes            = app.Option("--exclude-attributes", "Comma delimited list of files with types in DocId format of which attributes to exclude.", CommandOptionType.SingleValue);
            CommandOption enforceOptionalRules         = app.Option("--enforce-optional-rules", "Enforce optional rules, in addition to the mandatory set of rules.", CommandOptionType.NoValue);
            CommandOption allowDefaultInterfaceMethods = app.Option("--allow-default-interface-methods", "Allow default interface methods additions to not be considered breaks. This flag should only be used if you know your consumers support DIM", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                string leftOperandValue  = leftOperand.HasValue() ? leftOperand.Value() : "contract";
                string rightOperandValue = rightOperand.HasValue() ? rightOperand.Value() : "implementation";

                if (listRules.HasValue())
                {
                    CompositionHost c = GetCompositionHost();
                    ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer <ITypeReference>();

                    var rules = c.GetExports <IDifferenceRule>();

                    foreach (var rule in rules.OrderBy(r => r.GetType().Name, StringComparer.OrdinalIgnoreCase))
                    {
                        string ruleName = rule.GetType().Name;

                        if (IsOptionalRule(rule))
                        {
                            ruleName += " (optional)";
                        }

                        Console.WriteLine(ruleName);
                    }

                    return(0);
                }

                using (TextWriter output = GetOutput(outFilePath.Value()))
                {
                    if (DifferenceWriter.ExitCode != 0)
                    {
                        return(0);
                    }

                    if (output != Console.Out)
                    {
                        Trace.Listeners.Add(new TextWriterTraceListener(output)
                        {
                            Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning)
                        });
                    }

                    try
                    {
                        BaselineDifferenceFilter filter             = GetBaselineDifferenceFilter(HostEnvironment.SplitPaths(baseline.Value()), validateBaseline.HasValue());
                        NameTable sharedNameTable                   = new NameTable();
                        HostEnvironment contractHost                = new HostEnvironment(sharedNameTable);
                        contractHost.UnableToResolve               += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {leftOperandValue} assembly '{e.Referrer}'.");
                        contractHost.ResolveAgainstRunningFramework = resolveFx.HasValue();
                        contractHost.UnifyToLibPath                 = !skipUnifyToLibPath.HasValue();
                        contractHost.AddLibPaths(HostEnvironment.SplitPaths(contractDepends.Value()));
                        IEnumerable <IAssembly> contractAssemblies = contractHost.LoadAssemblies(contracts.Value, contractCoreAssembly.Value());

                        if (ignoreDesignTimeFacades.HasValue())
                        {
                            contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());
                        }

                        HostEnvironment implHost  = new HostEnvironment(sharedNameTable);
                        implHost.UnableToResolve += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {rightOperandValue} assembly '{e.Referrer}'.");
                        implHost.ResolveAgainstRunningFramework = resolveFx.HasValue();
                        implHost.UnifyToLibPath = !skipUnifyToLibPath.HasValue();
                        implHost.AddLibPaths(HostEnvironment.SplitPaths(implDirs.Value()));
                        if (warnOnMissingAssemblies.HasValue())
                        {
                            implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;
                        }

                        // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                        IEnumerable <IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), warnOnIncorrectVersion.HasValue());

                        // Exit after loading if the code is set to non-zero
                        if (DifferenceWriter.ExitCode != 0)
                        {
                            return(0);
                        }

                        ICciDifferenceWriter writer = GetDifferenceWriter(output, filter, enforceOptionalRules.HasValue(), mdil.HasValue(),
                                                                          excludeNonBrowsable.HasValue(), remapFile.Value(), !skipGroupByAssembly.HasValue(), leftOperandValue, rightOperandValue, excludeAttributes.Value(), allowDefaultInterfaceMethods.HasValue());
                        writer.Write(implDirs.Value(), implAssemblies, contracts.Value, contractAssemblies);

                        return(0);
                    }
                    catch (FileNotFoundException)
                    {
                        // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                        // OR if GetComparers doesn't find the remap file.
                        return(2);
                    }
                }
            });

            return(app.Execute(args));
        }
Ejemplo n.º 27
0
        public static int Main(string[] args)
        {
            try
            {
                var app = new CommandLineApplication
                {
                    Name = "dotnet dev-certs"
                };

                app.Command("https", c =>
                {
                    var exportPath = c.Option("-ep|--export-path",
                                              "Full path to the exported certificate",
                                              CommandOptionType.SingleValue);

                    var password = c.Option("-p|--password",
                                            "Password to use when exporting the certificate with the private key into a pfx file",
                                            CommandOptionType.SingleValue);

                    var check = c.Option(
                        "-c|--check",
                        "Check for the existence of the certificate but do not perform any action",
                        CommandOptionType.NoValue);

                    var clean = c.Option(
                        "--clean",
                        "Cleans all HTTPS development certificates from the machine.",
                        CommandOptionType.NoValue);

                    CommandOption trust = null;
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        trust = c.Option("-t|--trust",
                                         "Trust the certificate on the current platform",
                                         CommandOptionType.NoValue);
                    }

                    var verbose = c.Option("-v|--verbose",
                                           "Display more debug information.",
                                           CommandOptionType.NoValue);

                    var quiet = c.Option("-q|--quiet",
                                         "Display warnings and errors only.",
                                         CommandOptionType.NoValue);

                    c.HelpOption("-h|--help");

                    c.OnExecute(() =>
                    {
                        var reporter = new ConsoleReporter(PhysicalConsole.Singleton, verbose.HasValue(), quiet.HasValue());
                        if ((clean.HasValue() && (exportPath.HasValue() || password.HasValue() || trust?.HasValue() == true)) ||
                            (check.HasValue() && (exportPath.HasValue() || password.HasValue() || clean.HasValue())))
                        {
                            reporter.Error(@"Incompatible set of flags. Sample usages
'dotnet dev-certs https'
'dotnet dev-certs https --clean'
'dotnet dev-certs https --check --trust'
'dotnet dev-certs https -ep ./certificate.pfx -p password --trust'");
                        }

                        if (check.HasValue())
                        {
                            return(CheckHttpsCertificate(trust, reporter));
                        }

                        if (clean.HasValue())
                        {
                            return(CleanHttpsCertificates(reporter));
                        }

                        return(EnsureHttpsCertificate(exportPath, password, trust, reporter));
                    });
                });

                app.HelpOption("-h|--help");

                app.OnExecute(() =>
                {
                    app.ShowHelp();
                    return(Success);
                });

                return(app.Execute(args));
            }
            catch
            {
                return(CriticalError);
            }
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            CommandLineApplication application = new CommandLineApplication(true)
            {
                FullName = "E621 Downloader",
            };

            application.HelpOption("-?|-h|--help");

            CommandOption versionOption = application.VersionOption("-v|--version", PlatformServices.Default.Application.ApplicationVersion);

            application.Command("dump", command =>
            {
                command.Description = "Download entire images on the server of specified source.";
                command.HelpOption("-h|--help");

                CommandArgument outputPathArgument  = command.Argument("path", "Output path.", false);
                CommandOption startIdOption         = command.Option("-s|--start-id <id>", "Starting Id. Default is 1.", CommandOptionType.SingleValue);
                CommandOption ignoreHashCheckOption = command.Option("-i|--ignore-hash-check", "Ignore hash check.", CommandOptionType.NoValue);
                CommandOption includeDeletedOption  = command.Option("-d|--deleted", "Include deleted posts.", CommandOptionType.NoValue);

                command.OnExecute(() =>
                {
                    string path          = outputPathArgument.Value;
                    long startId         = 1;
                    bool ignoreHashCheck = ignoreHashCheckOption.HasValue();
                    bool includeDeleted  = includeDeletedOption.HasValue();

                    if (startIdOption.HasValue() && !long.TryParse(startIdOption.Value(), out startId))
                    {
                        Console.WriteLine("Invalid start id.");
                        return(-2);
                    }

                    DumpCommand.Run(path, startId, ignoreHashCheck, includeDeleted).Wait();

                    return(0);
                });
            });

            application.OnExecute(() =>
            {
                application.ShowHint();

                return(0);
            });

            try
            {
                int exitCode = application.Execute(args);

                if (exitCode == -2)
                {
                    application.ShowHint();
                }

                Environment.ExitCode = exitCode;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Environment.ExitCode = -1;
            }
        }
Ejemplo n.º 29
0
        public static int Main(string[] args)
        {
            if (args.Contains("--debug"))
            {
                Console.WriteLine("Press any key to continue...");
                _ = Console.ReadKey();
                var newArgs = new List <string>(args);
                newArgs.Remove("--debug");
                args = newArgs.ToArray();
            }

            try
            {
                var app = new CommandLineApplication
                {
                    Name = "dotnet dev-certs"
                };

                app.Command("https", c =>
                {
                    var exportPath = c.Option("-ep|--export-path",
                                              "Full path to the exported certificate",
                                              CommandOptionType.SingleValue);

                    var password = c.Option("-p|--password",
                                            "Password to use when exporting the certificate with the private key into a pfx file or to encrypt the Pem exported key",
                                            CommandOptionType.SingleValue);

                    // We want to force generating a key without a password to not be an accident.
                    var noPassword = c.Option("-np|--no-password",
                                              "Explicitly request that you don't use a password for the key when exporting a certificate to a PEM format",
                                              CommandOptionType.NoValue);

                    var check = c.Option(
                        "-c|--check",
                        "Check for the existence of the certificate but do not perform any action",
                        CommandOptionType.NoValue);

                    var clean = c.Option(
                        "--clean",
                        "Cleans all HTTPS development certificates from the machine.",
                        CommandOptionType.NoValue);

                    var import = c.Option(
                        "-i|--import",
                        "Imports the provided HTTPS development certificate into the machine. All other HTTPS developer certificates will be cleared out",
                        CommandOptionType.SingleValue);

                    var format = c.Option(
                        "--format",
                        "Export the certificate in the given format. Valid values are Pfx and Pem. Pfx is the default.",
                        CommandOptionType.SingleValue);

                    CommandOption trust = null;
                    trust = c.Option("-t|--trust",
                                     "Trust the certificate on the current platform. When combined with the --check option, validates that the certificate is trusted.",
                                     CommandOptionType.NoValue);

                    var verbose = c.Option("-v|--verbose",
                                           "Display more debug information.",
                                           CommandOptionType.NoValue);

                    var quiet = c.Option("-q|--quiet",
                                         "Display warnings and errors only.",
                                         CommandOptionType.NoValue);

                    c.HelpOption("-h|--help");

                    c.OnExecute(() =>
                    {
                        var reporter = new ConsoleReporter(PhysicalConsole.Singleton, verbose.HasValue(), quiet.HasValue());

                        if (verbose.HasValue())
                        {
                            var listener = new ReporterEventListener(reporter);
                            listener.EnableEvents(CertificateManager.Log, System.Diagnostics.Tracing.EventLevel.Verbose);
                        }

                        if (clean.HasValue())
                        {
                            if (exportPath.HasValue() || trust?.HasValue() == true || format.HasValue() || noPassword.HasValue() || check.HasValue() ||
                                (!import.HasValue() && password.HasValue()) ||
                                (import.HasValue() && !password.HasValue()))
                            {
                                reporter.Error(InvalidUsageErrorMessage);
                                return(CriticalError);
                            }
                        }

                        if (check.HasValue())
                        {
                            if (exportPath.HasValue() || password.HasValue() || noPassword.HasValue() || clean.HasValue() || format.HasValue() || import.HasValue())
                            {
                                reporter.Error(InvalidUsageErrorMessage);
                                return(CriticalError);
                            }
                        }

                        if (!clean.HasValue() && !check.HasValue())
                        {
                            if (password.HasValue() && noPassword.HasValue())
                            {
                                reporter.Error(InvalidUsageErrorMessage);
                                return(CriticalError);
                            }

                            if (noPassword.HasValue() && !(format.HasValue() && string.Equals(format.Value(), "PEM", StringComparison.OrdinalIgnoreCase)))
                            {
                                reporter.Error(InvalidUsageErrorMessage);
                                return(CriticalError);
                            }

                            if (import.HasValue())
                            {
                                reporter.Error(InvalidUsageErrorMessage);
                                return(CriticalError);
                            }
                        }

                        if (check.HasValue())
                        {
                            return(CheckHttpsCertificate(trust, reporter));
                        }

                        if (clean.HasValue())
                        {
                            var clean = CleanHttpsCertificates(reporter);
                            if (clean != Success || !import.HasValue())
                            {
                                return(clean);
                            }

                            return(ImportCertificate(import, password, reporter));
                        }

                        return(EnsureHttpsCertificate(exportPath, password, noPassword, trust, format, reporter));
                    });
                });

                app.HelpOption("-h|--help");

                app.OnExecute(() =>
                {
                    app.ShowHelp();
                    return(Success);
                });

                return(app.Execute(args));
            }
            catch
            {
                return(CriticalError);
            }
        }
Ejemplo n.º 30
0
 internal override bool CanHandle()
 {
     return(_outputOption.HasValue());
 }