Beispiel #1
0
        public void Main(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = app.FullName = "Nine.Graphics.Test";
            app.HelpOption("-?|--help");

            var width = app.Option("--width <WIDTH>", "Set the width of the host window", CommandOptionType.SingleValue);
            var height = app.Option("--height <HEIGHT>", "Set the height of the host window", CommandOptionType.SingleValue);
            var topMost = app.Option("--pin", "Enables the host window to be top most", CommandOptionType.NoValue);
            var channel = app.Option("--channel <CHANNEL>", "", CommandOptionType.SingleValue);

            app.Execute(args);

            if (app.IsShowingInformation)
            {
                return;
            }
            
            if (!channel.HasValue())
            {
                new Host(shutdown, serviceProvider).Run(
                    width.HasValue() ? int.Parse(width.Value()) : (int?)null,
                    width.HasValue() ? int.Parse(height.Value()) : (int?)null,
                    topMost.HasValue(),
                    app.RemainingArguments.ToArray());
            }
            else
            {
                new Guest(channel.Value(), shutdown, serviceProvider).Run(app.RemainingArguments.ToArray());
            }
        }
Beispiel #2
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "dpa";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            var optionToolsPath = app.Option("--tools-path", "", CommandOptionType.SingleValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            app.Command("tpa", c =>
            {
                c.Description = "Build minimal trusted platform assembly list";

                var assemblyFolder = c.Argument("[assemblies]", "Path to the folder contains the assemblies from which the TPA is built from.");
                var tpaSourceFile = c.Argument("[tpa.cpp]", "Path to the source file where the TPA list is generated in place.");

                c.HelpOption("-?|-h|-help");
                c.OnExecute(() =>
                {
                    var command = new BuildTpaCommand(_environment, assemblyFolder.Value, tpaSourceFile.Value);

                    return command.Execute();
                });
            });

            app.Command("runtime", c =>
            {
                c.Description = "Build the minimal required runtime assemblies";

                var assemblyFolder = c.Argument("[assemblies]", "Path to the folder contains the assemblies from which the TPA is built from.");
                var outputFile = c.Argument("[output]", "Path to the file where the TPA list is saved to. If omitted, output to console");

                c.HelpOption("-?|-h|-help");
                c.OnExecute(() =>
                {
                    var command = new BuildRuntimeCommand(_environment, assemblyFolder.Value, outputFile.Value);

                    return command.Execute();
                });
            });

            return app.Execute(args);
        }
Beispiel #3
0
        public int Main(string[] args)
        {
            #if DEBUG
            // Add our own debug helper because DNU is usually run from a wrapper script,
            // making it too late to use the DNX one. Technically it's possible to use
            // the DNX_OPTIONS environment variable, but that's difficult to do per-command
            // on Windows
            if (args.Any(a => string.Equals(a, "--debug", StringComparison.OrdinalIgnoreCase)))
            {
                args = args.Where(a => !string.Equals(a, "--debug", StringComparison.OrdinalIgnoreCase)).ToArray();
                Console.WriteLine($"Process Id: {Process.GetCurrentProcess().Id}");
                Console.WriteLine("Waiting for Debugger to attach...");
                SpinWait.SpinUntil(() => Debugger.IsAttached);
            }
            #endif
            var app = new CommandLineApplication();
            app.Name = "dnu";
            app.FullName = "Microsoft .NET Development Utility";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", () => _runtimeEnv.GetShortVersion(), () => _runtimeEnv.GetFullVersion());

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            var reportsFactory = new ReportsFactory(_runtimeEnv, optionVerbose.HasValue());

            BuildConsoleCommand.Register(app, reportsFactory, _hostServices);
            CommandsConsoleCommand.Register(app, reportsFactory, _environment);
            InstallConsoleCommand.Register(app, reportsFactory, _environment);
            ListConsoleCommand.Register(app, reportsFactory, _environment);
            PackConsoleCommand.Register(app, reportsFactory, _hostServices);
            PackagesConsoleCommand.Register(app, reportsFactory);
            PublishConsoleCommand.Register(app, reportsFactory, _environment, _hostServices);
            RestoreConsoleCommand.Register(app, reportsFactory, _environment);
            SourcesConsoleCommand.Register(app, reportsFactory);
            WrapConsoleCommand.Register(app, reportsFactory);
            FeedsConsoleCommand.Register(app, reportsFactory);

            return app.Execute(args);
        }
Beispiel #4
0
        internal static FeedCommandLineOptions Add(CommandLineApplication app)
        {
            var options = new FeedCommandLineOptions();

            options.SourceOptions = app.Option(
                "-s|--source <FEED>",
                "A list of packages sources to use for this command",
                CommandOptionType.MultipleValue);

            options.FallbackSourceOptions = app.Option(
                "-f|--fallbacksource <FEED>",
                "A list of packages sources to use as a fallback",
                CommandOptionType.MultipleValue);

            options.ProxyOptions = app.Option(
                "-p|--proxy <ADDRESS>",
                "The HTTP proxy to use when retrieving packages",
                CommandOptionType.SingleValue);

            options.NoCacheOptions = app.Option(
                "--no-cache",
                "Do not use local cache",
                CommandOptionType.NoValue);

            options.TargetPackagesFolderOptions = app.Option(
                "--packages",
                "Path to restore packages",
                CommandOptionType.SingleValue);

            options.IgnoreFailedSourcesOptions = app.Option(
                "--ignore-failed-sources",
                "Ignore failed remote sources if there are local packages meeting version requirements",
                CommandOptionType.NoValue);

            options.QuietOptions = app.Option(
                "--quiet", "Do not show output such as HTTP request/cache information",
                CommandOptionType.NoValue);

            options.ParallelOptions = app.Option("--parallel",
                "Restores in parallel when more than one project.json is discovered.",
                CommandOptionType.NoValue);

            return options;
        }
        internal void AddCommandLineParameterTo(CommandLineApplication command)
        {
            var isBoolProperty = Property.PropertyType == typeof(bool);
            var optionAttribute = Property.GetOptionAttribute();

            //Note: This means all bool properties are treated as options by default.
            //ArgumentAttribute on such a property is ignored.
            if (isBoolProperty || optionAttribute != null)
            {
                //This is just so that all the below code does not need to
                //check for null on attribute. Not pure but works.
                var nullSafeOptionAttribute = optionAttribute ?? new OptionAttribute();

                var template = GetOptionTemplate(nullSafeOptionAttribute);
                var optionType = isBoolProperty ? CommandOptionType.NoValue : CommandOptionType.SingleValue;

                var option = command.Option(template, nullSafeOptionAttribute.Description ?? "", optionType);

                _valueAccessor = () =>
                {
                    if (isBoolProperty)
                    {
                        return option.HasValue() ? true : (nullSafeOptionAttribute.DefaultValue ?? false);
                    }
                    else
                    {
                        return option.HasValue() ? option.Value() : (nullSafeOptionAttribute.DefaultValue ?? "");
                    }
                };
            }
            else
            {
                //And all other string properties are considered arguments by default
                //even if the ArgumentAttribute is not mentioned on them.
                var argumentAttribute = Property.GetArgumentAttribute();
                var description = argumentAttribute != null && !string.IsNullOrWhiteSpace(argumentAttribute.Description)
                    ? argumentAttribute.Description
                    : "";

                var argument = command.Argument(Property.Name, description);
                _valueAccessor = () => argument.Value;
            }
        }
Beispiel #6
0
        public static Task<int> ExecuteAsync(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = Constants.BootstrapperExeName;
            app.FullName = Constants.BootstrapperFullName;

            // These options were handled in the native code, but got passed through here.
            // We just need to capture them and clean them up.
            var optionAppbase = app.Option("--appbase <PATH>", "Application base directory path",
                CommandOptionType.SingleValue);
            var optionLib = app.Option("--lib <LIB_PATHS>", "Paths used for library look-up",
                CommandOptionType.MultipleValue);
            var optionDebug = app.Option("--debug", "Waits for the debugger to attach before beginning execution.",
                CommandOptionType.NoValue);

            var env = new RuntimeEnvironment();

            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version",
                              () => env.GetShortVersion(),
                              () => env.GetFullVersion());

            // Options below are only for help info display
            // They will be forwarded to Microsoft.Framework.ApplicationHost
            var optionsToForward = new[]
            {
                app.Option("--watch", "Watch file changes", CommandOptionType.NoValue),
                app.Option("--packages <PACKAGE_DIR>", "Directory containing packages", CommandOptionType.SingleValue),
                app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue),
                app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue)
            };

            app.Execute(args);

            // Help information was already shown because help option was specified
            if (app.IsShowingInformation)
            {
                return Task.FromResult(0);
            }

            // Show help information if no subcommand/option was specified
            if (!app.IsShowingInformation && app.RemainingArguments.Count == 0)
            {
                app.ShowHelp();
                return Task.FromResult(2);
            }

            // Some options should be forwarded to Microsoft.Framework.ApplicationHost
            var appHostName = "Microsoft.Framework.ApplicationHost";
            var appHostIndex = app.RemainingArguments.FindIndex(s =>
                string.Equals(s, appHostName, StringComparison.OrdinalIgnoreCase));
            foreach (var option in optionsToForward)
            {
                if (option.HasValue())
                {
                    if (appHostIndex < 0)
                    {
                        Console.WriteLine("The option '--{0}' can only be used with {1}", option.LongName, appHostName);
                        return Task.FromResult(1);
                    }

                    if (option.OptionType == CommandOptionType.NoValue)
                    {
                        app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName);
                    }
                    else if (option.OptionType == CommandOptionType.SingleValue)
                    {
                        app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName);
                        app.RemainingArguments.Insert(appHostIndex + 2, option.Value());
                    }
                    else if (option.OptionType == CommandOptionType.MultipleValue)
                    {
                        foreach (var value in option.Values)
                        {
                            app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName);
                            app.RemainingArguments.Insert(appHostIndex + 2, value);
                        }
                    }
                }
            }

            // Resolve the lib paths
            IEnumerable<string> searchPaths = ResolveSearchPaths(optionLib.Values, app.RemainingArguments);

            var bootstrapper = new Bootstrapper(searchPaths);
            return bootstrapper.RunAsync(app.RemainingArguments, env);
        }
Beispiel #7
0
        static int Main(string[] args)
        {
            var app = new CommandLineApplication();
            var pkgRoot = app.Option("--root|-r", "Package root directory", CommandOptionType.SingleValue);
            var outputRoot = app.Option("--out|-o", "Output directory", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                var di = new DirectoryInfo(pkgRoot.Value());
                var outRoot = String.IsNullOrEmpty(outputRoot.Value()) ? "help" : outputRoot.Value();

                foreach (var indexDir in di.EnumerateDirectories("_indexes", SearchOption.AllDirectories))
                {
                    var pkgName = indexDir.Parent.Parent.Name;
                    var cmdletIndexFilePath = Path.Combine(indexDir.FullName, "_cmdlets.idx");
                    if (File.Exists(cmdletIndexFilePath))
                    {
                        var contentDir = Path.Combine(indexDir.Parent.FullName, "content");
                        var helpDir = Path.Combine(outRoot, pkgName);
                        var libDir = Path.Combine(indexDir.Parent.FullName, "lib");
                        foreach (var cmdletRow in File.ReadAllLines(cmdletIndexFilePath))
                        {
                            var keys = cmdletRow.Split(':')[0];
                            var assemblyAndType = cmdletRow.Split(':')[1];
                            var assembly = assemblyAndType.Split('/')[0];
                            var typeName = assemblyAndType.Split('/')[1];

                            var libDirectoryInfo = new DirectoryInfo(libDir);
                            var assemblyFileInfo = libDirectoryInfo.GetFiles(assembly, SearchOption.AllDirectories).FirstOrDefault();

                            if (assemblyFileInfo != null)
                            {
                                var loader = new Loader(assemblyFileInfo.DirectoryName);
                                PlatformServices.Default.AssemblyLoaderContainer.AddLoader(loader);
                                var assemblyName = assembly.Substring(0, assembly.Length - ".dll".Length);
                                var loadedAssembly = loader.LoadFromAssemblyName(new System.Reflection.AssemblyName(assemblyName));
                                var type = loadedAssembly.GetType(typeName);

                                var help = GenerateHelp(contentDir, assembly, keys, type);
                                var helpFile = Path.Combine(helpDir, keys.Replace(';', '.') + ".hlp");

                                if (!Directory.Exists(helpDir))
                                {
                                    Directory.CreateDirectory(helpDir);
                                }
                                if (File.Exists(helpFile))
                                {
                                    Console.WriteLine($"File {helpFile} already exists - skipping!");
                                }
                                else {
                                    File.WriteAllLines(helpFile, help);
                                }
                            }
                        }
                    }
                }
                return 0;
            });

            return app.Execute(args);
        }
Beispiel #8
0
        public int Main(string[] args)
        {
            _originalForeground = Console.ForegroundColor;

            var app = new CommandLineApplication();
            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 0;
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                    CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                    CommandOptionType.SingleValue);
                var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    try
                    {
                        var command = new RestoreCommand(_environment);
                        command.Reports = new Reports()
                        {
                            Information = this,
                            Verbose = optionVerbose.HasValue() ? (this as IReport) : new NullReport()
                        };

                        // If the root argument is a directory
                        if (Directory.Exists(argRoot.Value))
                        {
                            command.RestoreDirectory = argRoot.Value;
                        }
                        // If the root argument is a project.json file
                        else if (string.Equals(
                            Project.ProjectFileName,
                            Path.GetFileName(argRoot.Value),
                            StringComparison.OrdinalIgnoreCase))
                        {
                            command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value));
                        }
                        // If the root argument is a global.json file
                        else if (string.Equals(
                            GlobalSettings.GlobalFileName,
                            Path.GetFileName(argRoot.Value),
                            StringComparison.OrdinalIgnoreCase))
                        {
                            command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value));
                            command.GlobalJsonFile = argRoot.Value;
                        }
                        else if (!string.IsNullOrEmpty(argRoot.Value))
                        {
                            throw new InvalidOperationException("The given root is invalid.");
                        }

                        if (optSource.HasValue())
                        {
                            command.Sources = optSource.Values;
                        }

                        if (optFallbackSource.HasValue())
                        {
                            command.FallbackSources = optFallbackSource.Values;
                        }

                        if (optProxy.HasValue())
                        {
                            Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                        }

                        command.NoCache = optNoCache.HasValue();
                        command.PackageFolder = optPackageFolder.Value();

                        var success = command.ExecuteCommand();

                        return success ? 0 : 1;
                    }
                    catch (Exception ex)
                    {
                        this.WriteLine("----------");
                        this.WriteLine(ex.ToString());
                        this.WriteLine("----------");
                        this.WriteLine("Restore failed");
                        this.WriteLine(ex.Message);
                        return 1;
                    }
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment", CommandOptionType.SingleValue);
                var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders",
                    CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Don't include sources of project dependencies",
                    CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <KRE>", "Names or paths to KRE files to include",
                    CommandOptionType.MultipleValue);
                var optionAppFolder = c.Option("--appfolder <NAME>",
                    "Determine the name of the application primary folder", CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    Console.WriteLine("verbose:{0} out:{1} project:{2}",
                        optionVerbose.HasValue(),
                        optionOut.Value(),
                        argProject.Value);

                    var options = new PackOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        AppFolder = optionAppFolder.Value(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.TargetFramework,
                        Overwrite = optionOverwrite.HasValue(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                            string.Join(";", optionRuntime.Values).
                                Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                            new string[0],
                    };

                    var manager = new PackManager(_hostServices, options);
                    if (!manager.Package())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionCheck = c.Option("--check", "Check diagnostics", CommandOptionType.NoValue);
                var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.RuntimeTargetFramework = _environment.TargetFramework;
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.CheckDiagnostics = optionCheck.HasValue();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var command = new AddCommand();
                    command.Report = this;
                    command.Name = argName.Value;
                    command.Version = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            return app.Execute(args);
        }
Beispiel #9
0
        private bool ParseArgs(string[] args, out DefaultHostOptions defaultHostOptions, out string[] outArgs, out int exitCode)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = "Microsoft.Framework.ApplicationHost";
            app.FullName = app.Name;
            var optionWatch = app.Option("--watch", "Watch file changes", CommandOptionType.NoValue);
            var optionPackages = app.Option("--packages <PACKAGE_DIR>", "Directory containing packages",
                CommandOptionType.SingleValue);
            var optionConfiguration = app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue);
            var optionCompilationServer = app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue);
            var runCmdExecuted = false;
            app.HelpOption("-?|-h|--help");

            var env = (IRuntimeEnvironment)_serviceProvider.GetService(typeof(IRuntimeEnvironment));
            app.VersionOption("--version", () => env.GetShortVersion(), () => env.GetFullVersion());
            var runCmd = app.Command("run", c =>
            {
                // We don't actually execute "run" command here
                // We are adding this command for the purpose of displaying correct help information
                c.Description = "Run application";
                c.OnExecute(() =>
                {
                    runCmdExecuted = true;
                    return 0;
                });
            },
            addHelpCommand: false,
            throwOnUnexpectedArg: false);
            app.Execute(args);

            defaultHostOptions = null;
            outArgs = null;
            exitCode = 0;

            if (app.IsShowingInformation)
            {
                // If help option or version option was specified, exit immediately with 0 exit code
                return true;
            }
            else if (!(app.RemainingArguments.Any() || runCmdExecuted))
            {
                // If no subcommand was specified, show error message
                // and exit immediately with non-zero exit code
                Console.WriteLine("Please specify the command to run");
                exitCode = 2;
                return true;
            }

            defaultHostOptions = new DefaultHostOptions();
            defaultHostOptions.WatchFiles = optionWatch.HasValue();
            defaultHostOptions.PackageDirectory = optionPackages.Value();

            defaultHostOptions.TargetFramework = _environment.RuntimeFramework;
            defaultHostOptions.Configuration = optionConfiguration.Value() ?? _environment.Configuration ?? "Debug";
            defaultHostOptions.ApplicationBaseDirectory = _environment.ApplicationBasePath;
            var portValue = optionCompilationServer.Value() ?? Environment.GetEnvironmentVariable(EnvironmentNames.CompilationServerPort);

            int port;
            if (!string.IsNullOrEmpty(portValue) && int.TryParse(portValue, out port))
            {
                defaultHostOptions.CompilationServerPort = port;
            }

            var remainingArgs = new List<string>();
            if (runCmdExecuted)
            {
                // Later logic will execute "run" command
                // So we put this argment back after it was consumed by parser
                remainingArgs.Add("run");
                remainingArgs.AddRange(runCmd.RemainingArguments);
            }
            else
            {
                remainingArgs.AddRange(app.RemainingArguments);
            }

            if (remainingArgs.Any())
            {
                defaultHostOptions.ApplicationName = remainingArgs[0];
                outArgs = remainingArgs.Skip(1).ToArray();
            }
            else
            {
                outArgs = remainingArgs.ToArray();
            }

            return false;
        }
Beispiel #10
0
        public int Main(string[] args)
        {
            // We want to allow unexpected args, in case future VS needs to pass anything in that we don't current.
            // This will allow us to retain backwards compatibility.
            var application = new CommandLineApplication(throwOnUnexpectedArg: false);
            application.HelpOption("-?|-h|--help");

            var env = (IApplicationEnvironment)_services.GetService(typeof(IApplicationEnvironment));

            var portOption = application.Option("--port", "Port number to listen for a connection.", CommandOptionType.SingleValue);
            var projectOption = application.Option("--project", "Path to a project file.", CommandOptionType.SingleValue);

            var debugOption = application.Option("--debug", "Launch the debugger", CommandOptionType.NoValue);

            var waitOption = application.Option("--wait", "Wait for attach", CommandOptionType.NoValue);

            // If no command was specified at the commandline, then wait for a command via message.
            application.OnExecute(async () =>
            {
                if (debugOption.HasValue())
                {
                    Debugger.Launch();
                }

                if (waitOption.HasValue())
                {
                    Thread.Sleep(10 * 1000);
                }

                var projectPath = projectOption.Value() ?? env.ApplicationBasePath;
                var port = int.Parse(portOption.Value());

                Console.WriteLine("Listening on port {0}", port);
                using (var channel = await ReportingChannel.ListenOn(port))
                {
                    Console.WriteLine("Client accepted {0}", channel.Socket.LocalEndPoint);

                    try
                    {
                        string testCommand = null;
                        Project project = null;
                        if (Project.TryGetProject(projectPath, out project, diagnostics: null))
                        {
                            project.Commands.TryGetValue("test", out testCommand);
                        }

                        if (testCommand == null)
                        {
                            // No test command means no tests.
                            Trace.TraceInformation("[ReportingChannel]: OnTransmit(ExecuteTests)");
                            channel.Send(new Message()
                            {
                                MessageType = "TestExecution.Response",
                            });
                            return -1;
                        }

                        var message = channel.ReadQueue.Take();

                        // The message might be a request to negotiate protocol version. For now we only know
                        // about version 1.
                        if (message.MessageType == "ProtocolVersion")
                        {
                            var version = message.Payload?.ToObject<ProtocolVersionMessage>().Version;
                            var supportedVersion = 1;
                            Trace.TraceInformation(
                                "[ReportingChannel]: Requested Version: {0} - Using Version: {1}",
                                version,
                                supportedVersion);

                            channel.Send(new Message()
                            {
                                MessageType = "ProtocolVersion",
                                Payload = JToken.FromObject(new ProtocolVersionMessage()
                                {
                                    Version = supportedVersion,
                                }),
                            });

                            // Take the next message, which should be the command to execute.
                            message = channel.ReadQueue.Take();
                        }

                        if (message.MessageType == "TestDiscovery.Start")
                        {
                            var commandArgs = new string[]
                            {
                                "--list",
                                "--designtime"
                            };

                            var testServices = TestServices.CreateTestServices(_services, project, channel);
                            await ProjectCommand.Execute(testServices, project, "test", commandArgs);

                            Trace.TraceInformation("[ReportingChannel]: OnTransmit(DiscoverTests)");
                            channel.Send(new Message()
                            {
                                MessageType = "TestDiscovery.Response",
                            });
                            return 0;
                        }
                        else if (message.MessageType == "TestExecution.Start")
                        {
                            var commandArgs = new List<string>()
                            {
                                "--designtime"
                            };

                            var tests = message.Payload?.ToObject<RunTestsMessage>().Tests;
                            if (tests != null)
                            {
                                foreach (var test in tests)
                                {
                                    commandArgs.Add("--test");
                                    commandArgs.Add(test);
                                }
                            }

                            var testServices = TestServices.CreateTestServices(_services, project, channel);
                            await ProjectCommand.Execute(testServices, project, "test", commandArgs.ToArray());

                            Trace.TraceInformation("[ReportingChannel]: OnTransmit(ExecuteTests)");
                            channel.Send(new Message()
                            {
                                MessageType = "TestExecution.Response",
                            });
                            return 0;
                        }
                        else
                        {
                            var error = string.Format("Unexpected message type: '{0}'.", message.MessageType);
                            Trace.TraceError(error);
                            channel.SendError(error);
                            return -1;
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.ToString());
                        channel.SendError(ex);
                        return -2;
                    }
                }
            });

            application.Command("list", command =>
            {
                command.Name = "list";
                command.Description = "Lists all available tests.";

                command.OnExecute(async () =>
                {
                    if (debugOption.HasValue())
                    {
                        Debugger.Launch();
                    }

                    if (waitOption.HasValue())
                    {
                        Thread.Sleep(10 * 1000);
                    }

                    var projectPath = projectOption.Value() ?? env.ApplicationBasePath;
                    var port = int.Parse(portOption.Value());

                    return await DiscoverTests(port, projectPath);
                });
            });

            application.Command("run", command =>
            {
                command.Name = "run";
                command.Description = "Runs specified tests.";

                var tests = command.Option("--test <test>", "test to run", CommandOptionType.MultipleValue);

                command.OnExecute(async () =>
                {
                    if (debugOption.HasValue())
                    {
                        Debugger.Launch();
                    }

                    if (waitOption.HasValue())
                    {
                        Thread.Sleep(10 * 1000);
                    }

                    var projectPath = projectOption.Value() ?? env.ApplicationBasePath;
                    var port = int.Parse(portOption.Value());

                    return await ExecuteTests(port, projectPath, tests.Values);
                });

            });

            return application.Execute(args);
        }
Beispiel #11
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                    CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                    CommandOptionType.SingleValue);
                var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                    CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                    "Ignore failed remote sources if there are local packages meeting version requirements",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var command = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    command.RestoreDirectory = argRoot.Value;
                    command.Sources = optSource.Values;
                    command.FallbackSources = optFallbackSource.Values;
                    command.NoCache = optNoCache.HasValue();
                    command.PackageFolder = optPackageFolder.Value();
                    command.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var success = await command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("bundle", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
                    CommandOptionType.SingleValue);
                var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders",
                    CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
                    CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include",
                    CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                    CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                    CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                    "Name of public folder in the bundle, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                    CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of bundled files",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new BundleOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        Overwrite = optionOverwrite.HasValue(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                            string.Join(";", optionRuntime.Values).
                                Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                            new string[0],
                        Native = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new BundleManager(_hostServices, options);
                    if (!manager.Bundle())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = true;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command = new AddCommand();
                    command.Reports = reports;
                    command.Name = argName.Value;
                    command.Version = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                    CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                    CommandOptionType.SingleValue);
                var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                    CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                    "Ignore failed remote sources if there are local packages meeting version requirements",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    var addCmd = new AddCommand();
                    addCmd.Reports = reports;
                    addCmd.Name = argName.Value;
                    addCmd.Version = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd = new RestoreCommand(_environment);
                    restoreCmd.Reports = reports;

                    restoreCmd.RestoreDirectory = argProject.Value;
                    restoreCmd.Sources = optSource.Values;
                    restoreCmd.FallbackSources = optFallbackSource.Values;
                    restoreCmd.NoCache = optNoCache.HasValue();
                    restoreCmd.PackageFolder = optPackageFolder.Value();
                    restoreCmd.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var installCmd = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return 2;
                });

                packagesCommand.Command("add", c =>
                {
                    c.Description = "Add a NuGet package to the specified packages folder";
                    var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package");
                    var argSource = c.Argument("[source]", "Path to packages folder");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async () =>
                    {
                        var options = new AddOptions
                        {
                            Reports = CreateReports(optionVerbose.HasValue(), quiet: false),
                            SourcePackages = argSource.Value,
                            NuGetPackage = argNupkg.Value
                        };
                        var command = new Packages.AddCommand(options);
                        var success = await command.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("push", c =>
                {
                    c.Description = "Incremental copy of files from local packages to remote location";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        // Implicitly commit changes before push
                        var commitOptions = new CommitOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        var success = commitCommand.Execute();
                        if (!success)
                        {
                            return 1;
                        }

                        var pushOptions = new PushOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pushCommand = new PushCommand(pushOptions);
                        success = pushCommand.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("pull", c =>
                {
                    c.Description = "Incremental copy of files from remote location to local packages";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        bool success;
                        if (Directory.Exists(argSource.Value))
                        {
                            // Implicitly commit changes before pull
                            var commitOptions = new CommitOptions
                            {
                                Reports = reports,
                                SourcePackages = argSource.Value
                            };
                            var commitCommand = new CommitCommand(commitOptions);
                            success = commitCommand.Execute();
                            if (!success)
                            {
                                return 1;
                            }
                        }

                        var pullOptions = new PullOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pullCommand = new PullCommand(pullOptions);
                        success = pullCommand.Execute();
                        return success ? 0 : 1;
                    });
                });
            });

            app.Command("list", c =>
            {
                c.Description = "Print the dependencies of a given project.";
                var showAssemblies = c.Option("-a|--assemblies",
                    "Show the assembly files that are depended on by given project.",
                    CommandOptionType.NoValue);
                var framework = c.Option("--framework",
                    "Show dependencies for only the given framework.",
                    CommandOptionType.SingleValue);
                var runtimeFolder = c.Option("--runtime",
                    "The folder containing all available framework assemblies.",
                    CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "The path to project. If omitted, the command will use the project in the current directory.");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject, framework)
                    {
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("A project could not be found in {0}.", options.Path).Red());
                            return 1;
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return 2;
                        }
                    }

                    var command = new DependencyListCommand(options);
                    return command.Execute();
                });
            });

            // "kpm wrap" invokes MSBuild, which is not available on *nix
            if (!PlatformHelper.IsMono)
            {
                app.Command("wrap", c =>
                {
                    c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files";

                    var argPath = c.Argument("[path]", "Path to csproj to be wrapped");
                    var optConfiguration = c.Option("--configuration <CONFIGURATION>",
                        "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue);
                    var optMsBuildPath = c.Option("--msbuild <PATH>",
                        @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'",
                        CommandOptionType.SingleValue);
                    var optInPlace = c.Option("-i|--in-place",
                        "Generate or update project.json files in project directories of csprojs",
                        CommandOptionType.NoValue);
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        var command = new WrapCommand();
                        command.Reports = reports;
                        command.CsProjectPath = argPath.Value;
                        command.Configuration = optConfiguration.Value();
                        command.MsBuildPath = optMsBuildPath.Value();
                        command.InPlace = optInPlace.HasValue();

                        var success = command.ExecuteCommand();

                        return success ? 0 : 1;
                    });
                });
            }

            return app.Execute(args);
        }
Beispiel #12
0
        private bool ParseArgs(string[] args, out DefaultHostOptions defaultHostOptions, out string[] outArgs)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = "k";
            var optionWatch = app.Option("--watch", "Watch file changes", CommandOptionType.NoValue);
            var optionPackages = app.Option("--packages <PACKAGE_DIR>", "Directory containing packages",
                CommandOptionType.SingleValue);
            var optionConfiguration = app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue);

            var runCmdExecuted = false;
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());
            var runCmd = app.Command("run", c =>
            {
                // We don't actually execute "run" command here
                // We are adding this command for the purpose of displaying correct help information
                c.Description = "Run application";
                c.OnExecute(() =>
                {
                    runCmdExecuted = true;
                    return 0;
                });
            },
            addHelpCommand: false,
            throwOnUnexpectedArg: false);
            app.Execute(args);

            if (!(app.IsShowingInformation || app.RemainingArguments.Any() || runCmdExecuted))
            {
                app.ShowHelp(commandName: null);
            }

            defaultHostOptions = new DefaultHostOptions();
            defaultHostOptions.WatchFiles = optionWatch.HasValue();
            defaultHostOptions.PackageDirectory = optionPackages.Value();

            defaultHostOptions.TargetFramework = _environment.TargetFramework;
            defaultHostOptions.Configuration = optionConfiguration.Value() ?? _environment.Configuration ?? "Debug";
            defaultHostOptions.ApplicationBaseDirectory = _environment.ApplicationBasePath;

            var remainingArgs = new List<string>();
            if (runCmdExecuted)
            {
                // Later logic will execute "run" command
                // So we put this argment back after it was consumed by parser
                remainingArgs.Add("run");
                remainingArgs.AddRange(runCmd.RemainingArguments);
            }
            else
            {
                remainingArgs.AddRange(app.RemainingArguments);
            }

            if (remainingArgs.Any())
            {
                defaultHostOptions.ApplicationName = remainingArgs[0];
                outArgs = remainingArgs.Skip(1).ToArray();
            }
            else
            {
                outArgs = remainingArgs.ToArray();
            }

            return app.IsShowingInformation;
        }
Beispiel #13
0
        public static Task<int> ExecuteAsync(string[] args)
        {
            var enableTrace = Environment.GetEnvironmentVariable("KRE_TRACE") == "1";
            #if NET45
            // TODO: Make this pluggable and not limited to the console logger
            if (enableTrace)
            {
                var listener = new ConsoleTraceListener();
                Trace.Listeners.Add(listener);
                Trace.AutoFlush = true;
            }
            #endif
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = "klr";
            var optionLib = app.Option("--lib <LIB_PATHS>", "Paths used for library look-up",
                CommandOptionType.MultipleValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());
            app.Execute(args);

            if (!app.IsShowingInformation && !app.RemainingArguments.Any())
            {
                app.ShowHelp();
            }

            if (app.IsShowingInformation)
            {
                return Task.FromResult(0);
            }

            // Resolve the lib paths
            string[] searchPaths = ResolveSearchPaths(optionLib.Values, app.RemainingArguments);

            Func<string, Assembly> loader = _ => null;
            Func<Stream, Assembly> loadStream = _ => null;
            Func<string, Assembly> loadFile = _ => null;

            Func<AssemblyName, Assembly> loaderCallback = assemblyName =>
            {
                string name = assemblyName.Name;

                // Skip resource assemblies
                if (name.EndsWith(".resources"))
                {
                    return null;
                }

                // If the assembly was already loaded use it
                Assembly assembly;
                if (_assemblyCache.TryGetValue(name, out assembly))
                {
                    return assembly;
                }

                var loadLock = _assemblyLoadLocks.GetOrAdd(name, new object());
                try
                {
                    // Concurrently loading the assembly might result in two distinct instances of the same assembly
                    // being loaded. This was observed when loading via Assembly.LoadStream. Prevent this by locking on the name.
                    lock (loadLock)
                    {
                        if (_assemblyCache.TryGetValue(name, out assembly))
                        {
                            // This would succeed in case the thread was previously waiting on the lock when assembly
                            // load was in progress
                            return assembly;
                        }

                        assembly = loader(name) ?? ResolveHostAssembly(loadFile, searchPaths, name);

                        if (assembly != null)
                        {
            #if K10
                            ExtractAssemblyNeutralInterfaces(assembly, loadStream);
            #endif
                            _assemblyCache[name] = assembly;
                        }
                    }
                }
                finally
                {
                    _assemblyLoadLocks.TryRemove(name, out loadLock);
                }

                return assembly;
            };
            #if K10
            var loaderImpl = new DelegateAssemblyLoadContext(loaderCallback);
            loadStream = assemblyStream => loaderImpl.LoadStream(assemblyStream, pdbStream: null);
            loadFile = path => loaderImpl.LoadFile(path);

            AssemblyLoadContext.InitializeDefaultContext(loaderImpl);

            if (loaderImpl.EnableMultiCoreJit())
            {
                loaderImpl.StartMultiCoreJitProfile("startup.prof");
            }
            #else
            var loaderImpl = new LoaderEngine();
            loadStream = assemblyStream => loaderImpl.LoadStream(assemblyStream, pdbStream: null);
            loadFile = path => loaderImpl.LoadFile(path);

            ResolveEventHandler handler = (sender, a) =>
            {
                // Special case for retargetable assemblies on desktop
                if (a.Name.EndsWith("Retargetable=Yes"))
                {
                    return Assembly.Load(a.Name);
                }

                return loaderCallback(new AssemblyName(a.Name));
            };

            AppDomain.CurrentDomain.AssemblyResolve += handler;
            AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs loadedArgs) =>
            {
                // Skip loading interfaces for dynamic assemblies
                if (loadedArgs.LoadedAssembly.IsDynamic)
                {
                    return;
                }

                ExtractAssemblyNeutralInterfaces(loadedArgs.LoadedAssembly, loadStream);
            };
            #endif

            try
            {
                var assembly = Assembly.Load(new AssemblyName("klr.host"));

                // Loader impl
                // var loaderEngine = new DefaultLoaderEngine(loaderImpl);
                var loaderEngineType = assembly.GetType("klr.host.DefaultLoaderEngine");
                var loaderEngine = Activator.CreateInstance(loaderEngineType, loaderImpl);

                // The following code is doing:
                // var loaderContainer = new klr.host.LoaderContainer();
                // var libLoader = new klr.host.PathBasedAssemblyLoader(loaderEngine, searchPaths);
                // loaderContainer.AddLoader(libLoader);
                // var bootstrapper = new klr.host.Bootstrapper(loaderContainer, loaderEngine);
                // bootstrapper.Main(bootstrapperArgs);

                var loaderContainerType = assembly.GetType("klr.host.LoaderContainer");
                var pathBasedLoaderType = assembly.GetType("klr.host.PathBasedAssemblyLoader");

                var loaderContainer = Activator.CreateInstance(loaderContainerType);
                var libLoader = Activator.CreateInstance(pathBasedLoaderType, new object[] { loaderEngine, searchPaths });

                MethodInfo addLoaderMethodInfo = loaderContainerType.GetTypeInfo().GetDeclaredMethod("AddLoader");
                var disposable = (IDisposable)addLoaderMethodInfo.Invoke(loaderContainer, new[] { libLoader });
                var loaderContainerLoadMethodInfo = loaderContainerType.GetTypeInfo().GetDeclaredMethod("Load");

                loader = (Func<string, Assembly>)loaderContainerLoadMethodInfo.CreateDelegate(typeof(Func<string, Assembly>), loaderContainer);

                var bootstrapperType = assembly.GetType("klr.host.Bootstrapper");
                var mainMethod = bootstrapperType.GetTypeInfo().GetDeclaredMethod("Main");
                var bootstrapper = Activator.CreateInstance(bootstrapperType, loaderContainer, loaderEngine);

                try
                {
                    var bootstrapperArgs = new object[]
                    {
                        app.RemainingArguments.ToArray()
                    };

                    var task = (Task<int>)mainMethod.Invoke(bootstrapper, bootstrapperArgs);

                    return task.ContinueWith(async (t, state) =>
                    {
                        // Dispose the host
                        ((IDisposable)state).Dispose();

            #if NET45
                        AppDomain.CurrentDomain.AssemblyResolve -= handler;
            #endif
                        return await t;
                    },
                    disposable).Unwrap();
                }
                catch
                {
                    // If we throw synchronously then dispose then rethtrow
                    disposable.Dispose();
                    throw;
                }
            }
            catch
            {
            #if NET45
                AppDomain.CurrentDomain.AssemblyResolve -= handler;
            #endif
                throw;
            }
        }
Beispiel #14
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "dnu";
            app.FullName = "Microsoft .NET Development Utility";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion);

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var feedOptions = FeedOptions.Add(c);
                var optLock = c.Option("--lock",
                    "Creates dependencies file with locked property set to true. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optUnlock = c.Option("--unlock",
                    "Creates dependencies file with locked property set to false. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optParallel = c.Option("--parallel",
                    "Restores in parallel when more than one project.json is discovered.",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var command = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                    command.RestoreDirectory = argRoot.Value;
                    command.FeedOptions = feedOptions;
                    command.Lock = optLock.HasValue();
                    command.Unlock = optUnlock.HasValue();
                    command.Parallel = optParallel.HasValue();

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var success = await command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("publish", c =>
            {
                c.Description = "Publish application for deployment";

                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
                    CommandOptionType.SingleValue);
                var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
                    CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include, or \"active\" for current runtime on PATH",
                    CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                    CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                    CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                    "Name of public folder in the output, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                    CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of published files",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new PublishOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                            string.Join(";", optionRuntime.Values).
                                Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                            new string[0],
                        Native = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new PublishManager(_hostServices, options);
                    if (!manager.Publish())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = true;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");

                var feedOptions = FeedOptions.Add(c);

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

                c.OnExecute(async () =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);

                    var addCmd = new AddCommand();
                    addCmd.Reports = reports;
                    addCmd.Name = argName.Value;
                    addCmd.Version = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd = new RestoreCommand(_environment);
                    restoreCmd.Reports = reports;
                    restoreCmd.FeedOptions = feedOptions;

                    restoreCmd.RestoreDirectory = argProject.Value;

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var installCmd = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return 2;
                });

                packagesCommand.Command("add", c =>
                {
                    c.Description = "Add a NuGet package to the specified packages folder";
                    var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package");
                    var argSource = c.Argument("[source]", "Path to packages folder");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async () =>
                    {
                        var options = new AddOptions
                        {
                            Reports = CreateReports(optionVerbose.HasValue(), quiet: false),
                            SourcePackages = argSource.Value,
                            NuGetPackage = argNupkg.Value
                        };
                        var command = new Packages.AddCommand(options);
                        var success = await command.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("push", c =>
                {
                    c.Description = "Incremental copy of files from local packages to remote location";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        // Implicitly commit changes before push
                        var commitOptions = new CommitOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        var success = commitCommand.Execute();
                        if (!success)
                        {
                            return 1;
                        }

                        var pushOptions = new PushOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pushCommand = new PushCommand(pushOptions);
                        success = pushCommand.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("pull", c =>
                {
                    c.Description = "Incremental copy of files from remote location to local packages";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        bool success;
                        if (Directory.Exists(argSource.Value))
                        {
                            // Implicitly commit changes before pull
                            var commitOptions = new CommitOptions
                            {
                                Reports = reports,
                                SourcePackages = argSource.Value
                            };
                            var commitCommand = new CommitCommand(commitOptions);
                            success = commitCommand.Execute();
                            if (!success)
                            {
                                return 1;
                            }
                        }

                        var pullOptions = new PullOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pullCommand = new PullCommand(pullOptions);
                        success = pullCommand.Execute();
                        return success ? 0 : 1;
                    });
                });
            });

            app.Command("list", c =>
            {
                c.Description = "Print the dependencies of a given project";
                var showAssemblies = c.Option("-a|--assemblies",
                    "Show the assembly files that are depended on by given project",
                    CommandOptionType.NoValue);
                var frameworks = c.Option("--framework <TARGET_FRAMEWORK>",
                    "Show dependencies for only the given frameworks",
                    CommandOptionType.MultipleValue);
                var runtimeFolder = c.Option("--runtime <PATH>",
                    "The folder containing all available framework assemblies",
                    CommandOptionType.SingleValue);
                var hideDependents = c.Option("--hide-dependents",
                    "Hide the immediate dependents of libraries referenced in the project",
                    CommandOptionType.NoValue);
                var resultsFilter = c.Option("--filter <PATTERN>",
                    "Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?",
                    CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject)
                    {
                        TargetFrameworks = frameworks.Values,
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                        HideDependents = hideDependents.HasValue(),
                        ResultsFilter = resultsFilter.Value()
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName));
                            return 1;
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return 2;
                        }
                    }

                    var command = new DependencyListCommand(options, _environment.RuntimeFramework);
                    return command.Execute();
                });
            });

            app.Command("commands", cmd =>
            {
                cmd.Description = "Commands related to managing application commands (add, remove)";
                cmd.HelpOption("-?|-h|--help");
                cmd.OnExecute(() =>
                {
                    cmd.ShowHelp();
                    return 2;
                });

                cmd.Command("install", c =>
                {
                    c.Description = "Installs application commands";

                    var argPackage = c.Argument("[package]", "The name of the application package");
                    var argVersion = c.Argument("[version]", "The version of the application package");

                    var optOverwrite = c.Option("-o|--overwrite", "Overwrites conflicting commands", CommandOptionType.NoValue);

                    var feedOptions = FeedOptions.Add(c);

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

                    c.OnExecute(async () =>
                    {
                        var command = new InstallGlobalCommand(
                                _environment,
                                string.IsNullOrEmpty(feedOptions.TargetPackagesFolder) ?
                                    AppCommandsFolderRepository.CreateDefault() :
                                    AppCommandsFolderRepository.Create(feedOptions.TargetPackagesFolder));

                        command.FeedOptions = feedOptions;
                        command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                        command.OverwriteCommands = optOverwrite.HasValue();

                        if (feedOptions.Proxy != null)
                        {
                            Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                        }

                        var success = await command.Execute(argPackage.Value, argVersion.Value);
                        return success ? 0 : 1;
                    });

                });

                cmd.Command("uninstall", c =>
                {
                    c.Description = "Uninstalls application commands";

                    var argCommand = c.Argument("[command]", "The name of the command to uninstall");

                    var optNoPurge = c.Option("--no-purge", "Do not try to remove orphaned packages", CommandOptionType.NoValue);

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

                    c.OnExecute(() =>
                    {
                        var command = new UninstallCommand(
                            _environment,
                            AppCommandsFolderRepository.CreateDefault(),
                            reports: CreateReports(optionVerbose.HasValue(), quiet: false));

                        command.NoPurge = optNoPurge.HasValue();

                        var success = command.Execute(argCommand.Value);
                        return success ? 0 : 1;
                    });
                });
            });

            app.Command("wrap", c =>
            {
                c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files";

                var argPath = c.Argument("[path]", "Path to csproj to be wrapped");
                var optConfiguration = c.Option("--configuration <CONFIGURATION>",
                    "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue);
                var optMsBuildPath = c.Option("--msbuild <PATH>",
                    @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'",
                    CommandOptionType.SingleValue);
                var optInPlace = c.Option("-i|--in-place",
                    "Generate or update project.json files in project directories of csprojs",
                    CommandOptionType.NoValue);
                var optFramework = c.Option("-f|--framework",
                    "Target framework of assembly to be wrapped",
                    CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command = new WrapCommand();
                    command.Reports = reports;
                    command.InputFilePath = argPath.Value;
                    command.Configuration = optConfiguration.Value();
                    command.MsBuildPath = optMsBuildPath.Value();
                    command.InPlace = optInPlace.HasValue();
                    command.Framework = optFramework.Value();

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            return app.Execute(args);
        }
Beispiel #15
0
        public static Task<int> ExecuteAsync(string[] args)
        {
            var enableTrace = Environment.GetEnvironmentVariable(EnvironmentNames.Trace) == "1";
            #if ASPNET50
            // TODO: Make this pluggable and not limited to the console logger
            if (enableTrace)
            {
                var listener = new ConsoleTraceListener();
                Trace.Listeners.Add(listener);
                Trace.AutoFlush = true;
            }
            #endif
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = Constants.BootstrapperExeName;

            // RuntimeBootstrapper doesn't need to consume '--appbase' option because
            // klr/klr.cpp consumes the option value before invoking RuntimeBootstrapper
            // This is only for showing help info and swallowing useless '--appbase' option
            var optionAppbase = app.Option("--appbase <PATH>", "Application base directory path",
                CommandOptionType.SingleValue);
            var optionLib = app.Option("--lib <LIB_PATHS>", "Paths used for library look-up",
                CommandOptionType.MultipleValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Options below are only for help info display
            // They will be forwarded to Microsoft.Framework.ApplicationHost
            var optionsToForward = new[]
            {
                app.Option("--watch", "Watch file changes", CommandOptionType.NoValue),
                app.Option("--packages <PACKAGE_DIR>", "Directory containing packages", CommandOptionType.SingleValue),
                app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue),
                app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue)
            };

            app.Execute(args);

            // Help information was already shown because help option was specified
            if (app.IsShowingInformation)
            {
                return Task.FromResult(0);
            }

            // Show help information if no subcommand/option was specified
            if (!app.IsShowingInformation && !app.RemainingArguments.Any())
            {
                app.ShowHelp();
                return Task.FromResult(2);
            }

            // Some options should be forwarded to Microsoft.Framework.ApplicationHost
            var appHostName = "Microsoft.Framework.ApplicationHost";
            var appHostIndex = app.RemainingArguments.FindIndex(s =>
                string.Equals(s, appHostName, StringComparison.OrdinalIgnoreCase));
            foreach (var option in optionsToForward)
            {
                if (option.HasValue())
                {
                    if (appHostIndex < 0)
                    {
                        Console.WriteLine("The option '--{0}' can only be used with {1}", option.LongName, appHostName);
                        return Task.FromResult(1);
                    }

                    if (option.OptionType == CommandOptionType.NoValue)
                    {
                        app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName);
                    }
                    else if (option.OptionType == CommandOptionType.SingleValue)
                    {
                        app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName);
                        app.RemainingArguments.Insert(appHostIndex + 2, option.Value());
                    }
                    else if (option.OptionType == CommandOptionType.MultipleValue)
                    {
                        foreach (var value in option.Values)
                        {
                            app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName);
                            app.RemainingArguments.Insert(appHostIndex + 2, value);
                        }
                    }
                }
            }

            // Resolve the lib paths
            string[] searchPaths = ResolveSearchPaths(optionLib.Values, app.RemainingArguments);

            Func<string, Assembly> loader = _ => null;
            Func<Stream, Assembly> loadStream = _ => null;
            Func<string, Assembly> loadFile = _ => null;

            Func<AssemblyName, Assembly> loaderCallback = assemblyName =>
            {
                string name = assemblyName.Name;

                // Skip resource assemblies
                if (name.EndsWith(".resources"))
                {
                    return null;
                }

                // If the assembly was already loaded use it
                Assembly assembly;
                if (_assemblyCache.TryGetValue(name, out assembly))
                {
                    return assembly;
                }

                var loadLock = _assemblyLoadLocks.GetOrAdd(name, new object());
                try
                {
                    // Concurrently loading the assembly might result in two distinct instances of the same assembly
                    // being loaded. This was observed when loading via Assembly.LoadStream. Prevent this by locking on the name.
                    lock (loadLock)
                    {
                        if (_assemblyCache.TryGetValue(name, out assembly))
                        {
                            // This would succeed in case the thread was previously waiting on the lock when assembly
                            // load was in progress
                            return assembly;
                        }

                        assembly = loader(name) ?? ResolveHostAssembly(loadFile, searchPaths, name);

                        if (assembly != null)
                        {
            #if ASPNETCORE50
                            ExtractAssemblyNeutralInterfaces(assembly, loadStream);
            #endif
                            _assemblyCache[name] = assembly;
                        }
                    }
                }
                finally
                {
                    _assemblyLoadLocks.TryRemove(name, out loadLock);
                }

                return assembly;
            };
            #if ASPNETCORE50
            var loaderImpl = new DelegateAssemblyLoadContext(loaderCallback);
            loadStream = assemblyStream => loaderImpl.LoadStream(assemblyStream, assemblySymbols: null);
            loadFile = path => loaderImpl.LoadFile(path);

            AssemblyLoadContext.InitializeDefaultContext(loaderImpl);

            if (loaderImpl.EnableMultiCoreJit())
            {
                loaderImpl.StartMultiCoreJitProfile("startup.prof");
            }
            #else
            var loaderImpl = new LoaderEngine();
            loadStream = assemblyStream => loaderImpl.LoadStream(assemblyStream, assemblySymbols: null);
            loadFile = path => loaderImpl.LoadFile(path);

            ResolveEventHandler handler = (sender, a) =>
            {
                var appDomain = (AppDomain)sender;
                var afterPolicy = appDomain.ApplyPolicy(a.Name);
                if (afterPolicy != a.Name)
                {
                    return Assembly.Load(afterPolicy);
                }

                return loaderCallback(new AssemblyName(afterPolicy));
            };

            AppDomain.CurrentDomain.AssemblyResolve += handler;
            AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs loadedArgs) =>
            {
                // Skip loading interfaces for dynamic assemblies
                if (loadedArgs.LoadedAssembly.IsDynamic)
                {
                    return;
                }

                ExtractAssemblyNeutralInterfaces(loadedArgs.LoadedAssembly, loadStream);
            };
            #endif

            try
            {
                var assembly = Assembly.Load(new AssemblyName(Constants.BootstrapperHostName));

                // Loader impl
                // The following code is doing:
                // var loaderContainer = new kre.host.LoaderContainer();
                // var cachedAssemblyLoader = new kre.host.CachedAssemblyLoader(_assemblyCache);
                // var libLoader = new kre.host.PathBasedAssemblyLoader(searchPaths);
                // loaderContainer.AddLoader(cachedAssemblyLoader);
                // loaderContainer.AddLoader(libLoader);
                // var bootstrapper = new kre.host.Bootstrapper(loaderContainer);
                // bootstrapper.Main(bootstrapperArgs);

                var loaderContainerType = assembly.GetType(Constants.BootstrapperHostName + ".LoaderContainer");
                var cachedAssemblyLoaderType = assembly.GetType(Constants.BootstrapperHostName + ".CachedAssemblyLoader");
                var pathBasedLoaderType = assembly.GetType(Constants.BootstrapperHostName + ".PathBasedAssemblyLoader");

                var loaderContainer = Activator.CreateInstance(loaderContainerType);
                var cachedAssemblyLoader = Activator.CreateInstance(cachedAssemblyLoaderType, new object[] { _assemblyCache });
                var libLoader = Activator.CreateInstance(pathBasedLoaderType, new object[] { searchPaths });

                MethodInfo addLoaderMethodInfo = loaderContainerType.GetTypeInfo().GetDeclaredMethod("AddLoader");
                var disposable1 = (IDisposable)addLoaderMethodInfo.Invoke(loaderContainer, new[] { cachedAssemblyLoader });
                var disposable2 = (IDisposable)addLoaderMethodInfo.Invoke(loaderContainer, new[] { libLoader });

                var disposable = new CombinedDisposable(disposable1, disposable2);

                var loaderContainerLoadMethodInfo = loaderContainerType.GetTypeInfo().GetDeclaredMethod("Load");

                loader = (Func<string, Assembly>)loaderContainerLoadMethodInfo.CreateDelegate(typeof(Func<string, Assembly>), loaderContainer);

                var bootstrapperType = assembly.GetType(Constants.BootstrapperHostName + ".Bootstrapper");
                var mainMethod = bootstrapperType.GetTypeInfo().GetDeclaredMethod("Main");
                var bootstrapper = Activator.CreateInstance(bootstrapperType, loaderContainer);

                try
                {
                    var bootstrapperArgs = new object[]
                    {
                        app.RemainingArguments.ToArray()
                    };

                    var task = (Task<int>)mainMethod.Invoke(bootstrapper, bootstrapperArgs);

                    return task.ContinueWith(async (t, state) =>
                    {
                        // Dispose the host
                        ((IDisposable)state).Dispose();

            #if ASPNET50
                        AppDomain.CurrentDomain.AssemblyResolve -= handler;
            #endif
                        return await t;
                    },
                    disposable).Unwrap();
                }
                catch
                {
                    // If we throw synchronously then dispose then rethtrow
                    disposable.Dispose();
                    throw;
                }
            }
            catch
            {
            #if ASPNET50
                AppDomain.CurrentDomain.AssemblyResolve -= handler;
            #endif
                throw;
            }
        }
Beispiel #16
0
        public void Main(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = app.FullName = "OpenInput";
            app.HelpOption("-?|--help");

            var platform = app.Option("-p|--platform <TYPE>", "Set the input platform (DirectInput, RawInput, XInput, OpenTK)", CommandOptionType.SingleValue);

            app.Execute(args);

            if (app.IsShowingInformation) return;

            string target = "rawinput";

            if (platform.HasValue())
                target = platform.Value().ToLower();

            Func<IntPtr, IContainer> createContainer;
            string title = string.Empty;

            switch (target)
            {
                //case "directinput":
                //    title = "DirectInput";
                //    createContainer = (handle) =>
                //    {
                //        var container = new Container();
                //        container
                //            .Map<IMouse>(new DirectInput.Mouse())
                //            .Map<IKeyboard>(new DirectInput.Keyboard());
                //        return container;
                //    };
                //    break;

                default:
                case "rawinput":
                    title = "RawInput";
                    createContainer = (handle) =>
                    {
                        var container = new Container();
                        container
                            .Map<IMouse>(new RawInput.Mouse(handle))
                            .Map<IKeyboard>(new RawInput.Keyboard(handle));
                        return container;
                    };
                    break;

                case "opentk":
                    title = "OpenTK";

                    // Not sure if I have to create a opentk window or how it works
                    gameWindowThread = new Thread(() => {
                        using (var game = new tkGameWindow())
                            game.Run(30.0);
                    });
                    gameWindowThread.Start();

                    createContainer = (handle) =>
                    {
                        var container = new Container();
                        container
                            .Map<IMouse>(new OpenInput.OpenTK.Mouse())
                            .Map<IKeyboard>(new OpenInput.OpenTK.Keyboard());
                        return container;
                    };
                    break;
            }

            var form = new OutputForm(title, createContainer);
            Application.Run(form);
        }