protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     var pyoptions = (PythonConsoleOptions) options;
     return pyoptions.BasicConsole
                ? new BasicConsole(options.ColorfulConsole)
                : new SuperConsole(commandLine, options.ColorfulConsole);
 }
示例#2
0
        private static int Main(string[] args)
        {
            ConsoleOptions options;
            try {
                options = new ConsoleOptions(args);
            }
            catch (OptionException e) {
                Console.Error.Write("PhantomIis: ");
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine("Try `PhantomIis --help' for more information.");
                return -1;
            }

            if (options.DisplayVersion) {
                options.ShowVersion();
                return 0;
            }

            if (options.DisplayHelp) {
                options.ShowHelp();
                return 0;
            }

            List<string> validationErrors = options.Validate();
            if (validationErrors.Any()) {
                validationErrors.ForEach(Console.Error.WriteLine);
                return -1;
            }

            return (new Program()).Run(options);
        }
        public int EditSettings(ConsoleOptions options)
        {
            var settings = this.settingRepository.Load(options.SettingsFile);
            var message = string.Empty;

            this.consoleWriter
                .WriteLine()
                .WriteLine(Resources.SettingsEditorLaunching)
                .WriteLine(Resources.SettingsEditorCloseWarning);

            using (var viewModel = new SettingsViewModel(settings))
            {
                var view = this.viewFactory.CreateSettings(viewModel);
                var result = view.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    this.settingRepository.Save(settings, options.SettingsFile);

                    message = string.Format(Resources.SettingsEditorSavedFormat, options.SettingsFile);
                }
                else
                {
                    message = Resources.SettingsEditorCanceled;
                }
            }

            this.consoleWriter
                .WriteLine()
                .WriteLine(message);

            return 0;
        }
示例#4
0
		public static int Main(string[] args)
		{
			options = new ConsoleOptions ();
			options.ProcessArgs (args);
			args = options.RemainingArguments;

			NUnit.Core.TestDomain domain = new NUnit.Core.TestDomain();

			if (args.Length < 1) {
				options.DoUsage ();
				return 1;
			}

			string assembly = args [0];
			Console.WriteLine ("ASSEMBLY: " + assembly);

			Test test;

			if (args.Length == 1)
				test = domain.LoadAssembly (assembly);
			else
				test = domain.LoadAssembly (assembly, args [1]);
			if (test == null) {
				Console.Error.WriteLine("\nERROR: Unable to load test suite from assembly {0}", assembly);
				return 1;
			}
				
			Directory.SetCurrentDirectory(new FileInfo(assembly).DirectoryName);
			string xmlResult = "result.xml";

			XmlTextReader reader = GetTransformReader();
			ConsoleUi consoleUi = new ConsoleUi(domain, xmlResult, reader);
			return consoleUi.Execute();
		}
示例#5
0
		/// <remarks>
		/// After the engine is created the standard output is replaced with our custom Stream class so we
		/// can redirect the stdout to the text editor window.
		/// This can be done in this method since the Runtime object will have been created before this method
		/// is called.
		/// </remarks>
		protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
		{
			ScriptingConsoleOutputStream stream = pythonConsole.CreateOutputStream();
			SetOutput(stream);
			pythonConsole.CommandLine = commandLine;
			return pythonConsole;
		}
示例#6
0
        static void Main(string[] args)
        {
            var metadata = ExecutionEnvironment.GetApplicationMetadata();
            Log(metadata + "\r\n");

            var options = new ConsoleOptions(args);

            if (options.ShowHelp)
            {
                Console.WriteLine("Options:");
                options.OptionSet.WriteOptionDescriptions(Console.Out);
                Console.ReadKey();
                return;
            }

            AppAction appAction = null;

            switch (options.Mode)
            {
                case Mode.AllEvents:
                    appAction = new AllEventsDump();
                    break;
                case Mode.InterestingEvents:
                    appAction = new InterestingEventDump();
                    break;
            }

            appAction.Run();

            Log("Press enter to exit...");
            Console.ReadLine();
        }
示例#7
0
        public override void Parse(string[] args)
        {
            if (_consoleOptions == null) _consoleOptions = GetDefaultConsoleOptions();
            if (_engineOptions == null) _engineOptions = GetDefaultEngineOptions();

            base.Parse(args);
        }
示例#8
0
 /// <remarks>
 /// After the engine is created the standard output is replaced with our custom Stream class so we
 /// can redirect the stdout to the text editor window.
 /// This can be done in this method since the Runtime object will have been created before this method
 /// is called.
 /// </remarks>
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     SetOutput(new PythonOutputStream(textEditor));
     pythonConsole = new PythonConsole(textEditor, commandLine);
     if (ConsoleCreated != null) ConsoleCreated(this, EventArgs.Empty);
     return pythonConsole;
 }
示例#9
0
        public void CanRecognizeBooleanOptions(string propertyName, string pattern)
        {
            string[] prototypes = pattern.Split('|');

            PropertyInfo property = GetPropertyInfo(propertyName);
            Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName);

            foreach (string option in prototypes)
            {
                ConsoleOptions options = new ConsoleOptions("-" + option);
                Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option);

                options = new ConsoleOptions("-" + option + "+");
                Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "+");

                options = new ConsoleOptions("-" + option + "-");
                Assert.AreEqual(false, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "-");

                options = new ConsoleOptions("--" + option);
                Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option);

                options = new ConsoleOptions("/" + option);
                Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option);
            }
        }
 public ResultReporter(XmlNode result, ConsoleOptions options)
 {
     this.result = result;
     this.testRunResult = result.GetAttribute("result");
     this.options = options;
     this.summary = new ResultSummary(result);
 }
示例#11
0
文件: Program.cs 项目: Revex/RPi.Demo
        private void Run(string[] args)
        {
            // Creating this from static causes an exception in Raspian. Not in ubunti though?
            Log  = LogManager.GetCurrentClassLogger();
            var options = new ConsoleOptions(args);

            if (options.ShowHelp)
            {
                Console.WriteLine("Options:");
                options.OptionSet.WriteOptionDescriptions(Console.Out);
                return;
            }

            var deviceFactory = new Pca9685DeviceFactory();
            var device = deviceFactory.GetDevice(options.UseFakeDevice);
            var motorController = new PwmController(device);
            motorController.Init();

            Log.InfoFormat("RPi.Console running with {0}", options);

            switch (options.Mode)
            {
                case Mode.DcMotor:
                    RunDcMotor(motorController);
                    break;

                case Mode.Servo:
                    RunServo(motorController);
                    break;

                case Mode.Stepper:
                    motorController.Stepper.Rotate(600);
                    break;

                case Mode.Led:
                    RunLed(motorController);
                    break;

                case Mode.RawPwm:
                    RunRawPwm(device);
                    break;

                case Mode.AlarmClock:
                    var alarmClock = new AlarmClock(motorController);
                    alarmClock.Set(options.AlarmDate);
                    alarmClock.WaitForAlarm();
                    break;

                case Mode.SignalRTest:
                    var signalRConnection = new SignalRConnection(motorController);
                    signalRConnection.Run();
                    break;
            }

            motorController.AllStop();
            deviceFactory.Dispose();

            //http://nlog-project.org/2011/10/30/using-nlog-with-mono.html
           // NLog.LogManager.Configuration = null;
        }
示例#12
0
        public PythonConsoleWindow()
        {
            Initialized += new EventHandler(MainWindow_Initialized);
            // Load our custom highlighting definition:
            IHighlightingDefinition pythonHighlighting;
            using (Stream s = typeof(PythonConsoleWindow).Assembly.GetManifestResourceStream("IronPythonConsole.Resources.Python.xshd"))
            {
                if (s == null)
                    throw new InvalidOperationException("Could not find embedded resource");
                using (XmlReader reader = new XmlTextReader(s))
                {
                    pythonHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.
                        HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }
            // and register it in the HighlightingManager
            HighlightingManager.Instance.RegisterHighlighting("Python Highlighting", new string[] { ".cool" }, pythonHighlighting);

            InitializeComponent();

            textEditor.SyntaxHighlighting = pythonHighlighting;

            textEditor.PreviewKeyDown += new KeyEventHandler(textEditor_PreviewKeyDown);

            consoleOptionsProvider = new ConsoleOptions(console.Pad);

            propertyGridComboBox.SelectedIndex = 0;

            expander.Expanded += new RoutedEventHandler(expander_Expanded);

            console.Pad.Host.ConsoleCreated +=new PythonConsoleControl.ConsoleCreatedEventHandler(Host_ConsoleCreated);
        }
示例#13
0
        /******************************************************************************************
        ** Protected methods                                                                     **
        ******************************************************************************************/
        protected void run(string[] args)
        {
            long startTime = DateTime.Now.Ticks;

            // Load options from command-line arguments
            this.options = new ConsoleOptions(args);

            if (this.options.Paths.Length > 0) {
                // Output header if not running silent
                if (this.options.Verbose) {
                    WriteHeader();
                }

                Generator generator = new Generator(options);

                generator.OnProgress += new MessageHandler(this.generator_OnProgress);
                generator.OnWarning += new MessageHandler(this.generator_OnWarning);
                generator.OnError += new MessageHandler(this.generator_OnError);

                generator.generate();

                if (this.options.Verbose) {
                    TimeSpan interval = new TimeSpan(DateTime.Now.Ticks - startTime);
                    System.Console.WriteLine("Processed in " + interval.TotalSeconds + " seconds");
                }

            } else {
                this.options.DoHelp();
            }
        }
示例#14
0
        /// <summary>
        /// Executes the comand line - depending upon the options provided we will
        /// either run a single file, a single command, or enter the interactive loop.
        /// </summary>
        public int Run(IScriptEngine engine, IConsole console, ConsoleOptions options) {
            Contract.RequiresNotNull(engine, "engine");
            Contract.RequiresNotNull(console, "console");
            Contract.RequiresNotNull(options, "options");

            _engine = engine;
            _options = options;
            _console = console;

            Initialize();
            
            try {
                return Run();

#if !SILVERLIGHT // ThreadAbortException.ExceptionState
            } catch (System.Threading.ThreadAbortException tae) {
                if (tae.ExceptionState is KeyboardInterruptException) {
                    Thread.ResetAbort();
                }
                return -1;
#endif
            } finally {
                Shutdown(engine);
            }
        }
示例#15
0
        private static void ProcessArgs(string[] args)
        {
            _logger.InfoFormat("Processing args: {0}", string.Join(",", args));

            var options = new ConsoleOptions();
            ICommandLineParser parser = new CommandLineParser();

            if (parser.ParseArguments(args, options) && args.Length > 0)
            {
                if (options.ScheduleBackupTasks)
                {
                    var scheduleEngine = ObjectFactory.GetInstance<IScheduleManager>();

                    scheduleEngine.ScheduleBackupTasks();
                }

                if (options.UnScheduleBackupTasks)
                {
                    var scheduleEngine = ObjectFactory.GetInstance<IScheduleManager>();

                    scheduleEngine.RemoveScheduledBackupTasks();
                }

                if (options.RunBackups)
                {
                    var backupManager = ObjectFactory.GetInstance<IBackupManager>();

                    backupManager.RunBackups();
                }

                if (options.Info)
                {
                    var configResourceAccess = ObjectFactory.GetInstance<IConfigResourceAccess>();

                    System.Console.WriteLine("Amount of days to keep backups: {0}", configResourceAccess.GetBackupRetentionDays());
                    System.Console.WriteLine("Press any key to continue...");
                    System.Console.ReadKey();
                }
            }
            else
            {
                System.Console.WriteLine(options.GetUsage());
            }

            if (!options.RunSilent)
            {
                System.Console.WriteLine("Input arg or Enter to exit.");

                var input = System.Console.ReadLine();

                if (!string.IsNullOrWhiteSpace(input))
                {
                    var newArgs = new List<string>();
                    newArgs.Add(input);

                    ProcessArgs(newArgs.ToArray());
                }
            }
        }
        public void SingleAssembly()
        {
            var options = new ConsoleOptions("test.dll");
            var package = ConsoleRunner.MakeTestPackage(options);

            Assert.AreEqual(1, package.TestFiles.Length);
            Assert.AreEqual(Path.GetFullPath("test.dll"), package.FullName);
        }
        public void WhenProcessModelIsSpecified_PackageIncludesIt()
        {
            var options = new ConsoleOptions("test.dll", "--process=Separate");
            var package = ConsoleRunner.MakeTestPackage(options);

            Assert.That(package.Settings.ContainsKey("ProcessModel"));
            Assert.AreEqual("Separate", package.Settings["ProcessModel"]);
        }
        public void WhenTimeoutIsSpecified_PackageIncludesIt()
        {
            var options = new ConsoleOptions("test.dll", "--timeout=50");
            var package = ConsoleRunner.MakeTestPackage(options);

            Assert.That(package.Settings.ContainsKey("DefaultTimeout"));
            Assert.AreEqual(50, package.Settings["DefaultTimeout"]);
        }
        public void WhenDomainUsageIsSpecified_PackageIncludesIt()
        {
            var options = new ConsoleOptions("test.dll", "--domain=Multiple");
            var package = ConsoleRunner.MakeTestPackage(options);

            Assert.That(package.Settings.ContainsKey("DomainUsage"));
            Assert.AreEqual("Multiple", package.Settings["DomainUsage"]);
        }
示例#20
0
        private static void Main(string[] args)
        {
            // creates the options class
            var options = new ConsoleOptions();

            // Parses the arguments, if the parse fails, it displays Usage information
            Parser.Default.ParseArguments(args, options, OnVerbCommand);
        }
示例#21
0
 private static PwmController GetPwmController(ConsoleOptions options)
 {
     var deviceFactory = new Pca9685DeviceFactory();
     var device = deviceFactory.GetDevice(options.UseFakeDevice);
     var motorController = new PwmController(device);
     motorController.Init();
     return motorController;
 }
示例#22
0
        private static void Main(string[] args)
        {
            // creates the options class
            var options = new ConsoleOptions();

            // Parses the arguments, if the parse fails, it displays Usage information
            // in this scenario, all options are verb options, so when a valid verb is found, the instantiated class appletbase will be passed to the OnVerbCommand method.
            Parser.Default.ParseArguments(args, options, OnVerbCommand);
        }
示例#23
0
文件: Program.cs 项目: michyer/canape
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     PythonConsoleOptions options2 = (PythonConsoleOptions)options;
     if (!options2.BasicConsole)
     {
         return new SuperConsole(commandLine, options.ColorfulConsole);
     }
     return new BasicConsole(options.ColorfulConsole);
 }
示例#24
0
		public static int Main(string[] args)
		{
			ConsoleOptions options = new ConsoleOptions(args);
			if(!options.nologo)
				WriteCopyright();

			if(options.help)
			{
				options.Help();
				return 0;
			}
			
			if(options.NoArgs) 
			{
				Console.Error.WriteLine("fatal error: no inputs specified");
				options.Help();
				return 0;
			}
			
			if(!options.Validate())
			{
				Console.Error.WriteLine("fatal error: invalid arguments");
				options.Help();
				return 2;
			}

			try
			{
				ConsoleUi consoleUi = new ConsoleUi();
				consoleUi.Execute( options );
				return 0;
			}
			catch( FileNotFoundException ex )
			{
				Console.WriteLine( ex.Message );
				return 2;
			}
			catch( BadImageFormatException ex )
			{
				Console.WriteLine( ex.Message );
				return 2;
			}
			catch( Exception ex )
			{
				Console.WriteLine( "Unhandled Exception:\n{0}", ex.ToString() );
				return 2;
			}
			finally
			{
				if(options.wait)
				{
					Console.Out.WriteLine("\nHit <enter> key to continue");
					Console.ReadLine();
				}
			}
		}
示例#25
0
 public ConsoleRunner(ITestEngine engine, ConsoleOptions options)
 {
     _engine = engine;
     _options = options;
     _workDirectory = options.WorkDirectory;
     if (_workDirectory == null)
         _workDirectory = Environment.CurrentDirectory;
     else if (!Directory.Exists(_workDirectory))
         Directory.CreateDirectory(_workDirectory);
 }
示例#26
0
 public void When_printing_help_text()
 {
     _original = System.Console.Out;
     var output = new StringBuilder();
     TextWriter writer = new StringWriter(output);
     System.Console.SetOut(writer);
     var c = new ConsoleOptions();
     c.ShowHelp();
     _output = output.ToString();
 }
示例#27
0
        public void CreateReporter()
        {
            _report = new StringBuilder();

            var writer = new ExtendedTextWrapper(new StringWriter(_report));
            var options = new ConsoleOptions();
            options.Parse(new string[] { "MockTestResult.xml" });

            _reporter = new ResultReporter(_result, writer, options);
        }
示例#28
0
        public void CreateTextUI()
        {
            _reportBuilder = new StringBuilder();
            var writer = new ExtendedTextWrapper(new StringWriter(_reportBuilder));
#if !SILVERLIGHT
            var options = new ConsoleOptions();
            _textUI = new TextUI(writer, options);
#else
            _textUI = new TextUI(writer);
#endif
        }
		public EventCollector( ConsoleOptions options, TextWriter outWriter, TextWriter errorWriter )
		{
			level = 0;
			this.options = options;
			this.outWriter = outWriter;
			this.errorWriter = errorWriter;
			this.currentTestName = string.Empty;
			this.progress = !options.xmlConsole && !options.labels && !options.nodots;

			AppDomain.CurrentDomain.UnhandledException += 
				new UnhandledExceptionEventHandler(OnUnhandledException);
		}
示例#30
0
    protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options) {
        IConsole console = base.CreateConsole(engine, commandLine, options);

        Thread mainThread = Thread.CurrentThread;
        RubyContext context = (RubyContext)HostingHelpers.GetLanguageContext(engine);
        context.InterruptSignalHandler = delegate() { RubyUtils.RaiseAsyncException(mainThread, new Interrupt()); };
        ((BasicConsole)console).ConsoleCancelEventHandler = delegate(object sender, ConsoleCancelEventArgs e) {
            OnCancelKey(e, context, mainThread); 
        };

        return console;
    }
示例#31
0
 public void ThreeTestParametersInTwoOptions()
 {
     var options = new ConsoleOptions("--params:X=5;Y=7", "-p:Z=3");
     Assert.That(options.errorMessages, Is.Empty);
     Assert.That(options.TestParameters, Is.EqualTo("X=5;Y=7;Z=3"));
 }
        public void NoResultSuppressesDefaultResultSpecification()
        {
            var options = new ConsoleOptions("test.dll", "-noresult");

            Assert.That(options.ResultOutputSpecifications.Count, Is.EqualTo(0));
        }
示例#33
0
        public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs)
        {
            var actualArgs = ConsoleOptions.GetArgs(cmdline);

            Assert.That(actualArgs, Is.EqualTo(expectedArgs));
        }
        public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs)
        {
            var actualArgs = ConsoleOptions.GetArgs(cmdline);

            Assert.AreEqual(expectedArgs, actualArgs);
        }
示例#35
0
 public void CanRegognizeInProcessOption()
 {
     ConsoleOptions options = new ConsoleOptions("--inprocess");
     Assert.True(options.Validate(), "Should be valid: --inprocess");
     Assert.AreEqual("InProcess", options.ProcessModel, "Didn't recognize --inprocess");
 }
示例#36
0
 public void ResultOptionWithoutFileNameIsInvalid()
 {
     ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:");
     Assert.False(options.Validate(), "Should not be valid");
     Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected");
 }
示例#37
0
 public void X86AndInProcessAreNotCompatibleIn64BitProcess()
 {
     ConsoleOptions options = new ConsoleOptions("nunit.tests.dll", "--x86", "--inprocess");
     Assert.False(options.Validate(), "Should be invalid");
     Assert.AreEqual("The --x86 and --inprocess options are incompatible.", options.ErrorMessages[0]);
 }
示例#38
0
 /// <remarks>
 /// After the engine is created the standard output is replaced with our custom Stream class so we
 /// can redirect the stdout to the text editor window.
 /// This can be done in this method since the Runtime object will have been created before this method
 /// is called.
 /// </remarks>
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     //SetOutput(new PythonOutputStream(textEditor));
     pythonConsole = new IPYConsole(commandLine);
     if (ConsoleCreated != null)
     {
         ConsoleCreated(this, EventArgs.Empty);
     }
     Runtime.SetTrace(OnTracebackReceived);
     return(pythonConsole);
 }
示例#39
0
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     return(_control.Console);
 }
示例#40
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            var            commandLineParser = new Parser(settings => settings.CaseSensitive = false);
            var            optionsResult     = commandLineParser.ParseArguments <ConsoleOptions>(args);
            var            runtimeDictionary = new Dictionary <string, string>();
            ConsoleOptions consoleOptions    = new ConsoleOptions();

            optionsResult.WithNotParsed(errors =>
            {
                var text       = HelpText.AutoBuild(optionsResult);
                text.Copyright = " ";
                text.Heading   = "Jackett v" + EnvironmentUtil.JackettVersion;
                Console.WriteLine(text);
                Environment.Exit(1);
                return;
            });

            optionsResult.WithParsed(options =>
            {
                if (string.IsNullOrEmpty(options.Client))
                {
                    //TODO: Remove libcurl once off owin
                    bool runningOnDotNetCore = RuntimeInformation.FrameworkDescription.IndexOf("Core", StringComparison.OrdinalIgnoreCase) >= 0;

                    if (runningOnDotNetCore)
                    {
                        options.Client = "httpclientnetcore";
                    }
                    else
                    {
                        options.Client = "httpclient";
                    }
                }

                Settings          = options.ToRunTimeSettings();
                consoleOptions    = options;
                runtimeDictionary = GetValues(Settings);
            });

            LogManager.Configuration = LoggingSetup.GetLoggingConfiguration(Settings);
            Logger logger = LogManager.GetCurrentClassLogger();

            logger.Info("Starting Jackett v" + EnvironmentUtil.JackettVersion);

            // create PID file early
            if (!string.IsNullOrWhiteSpace(Settings.PIDFile))
            {
                try
                {
                    var proc = Process.GetCurrentProcess();
                    File.WriteAllText(Settings.PIDFile, proc.Id.ToString());
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while creating the PID file");
                }
            }

            Initialisation.ProcessSettings(Settings, logger);

            ISerializeService     serializeService     = new SerializeService();
            IProcessService       processService       = new ProcessService(logger);
            IConfigurationService configurationService = new ConfigurationService(serializeService, processService, logger, Settings);

            if (consoleOptions.Install || consoleOptions.Uninstall || consoleOptions.StartService || consoleOptions.StopService || consoleOptions.ReserveUrls)
            {
                bool isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;

                if (isWindows)
                {
                    ServerConfig serverConfig = configurationService.BuildServerConfig(Settings);
                    Initialisation.ProcessWindowsSpecificArgs(consoleOptions, processService, serverConfig, logger);
                }
                else
                {
                    logger.Error($"ReserveUrls and service arguments only apply to Windows, please remove them from your start arguments");
                    Environment.Exit(1);
                }
            }

            var builder = new ConfigurationBuilder();

            builder.AddInMemoryCollection(runtimeDictionary);

            Configuration = builder.Build();

            do
            {
                if (!isWebHostRestart)
                {
                    if (consoleOptions.Port != 0 || consoleOptions.ListenPublic || consoleOptions.ListenPrivate)
                    {
                        ServerConfig serverConfiguration = configurationService.BuildServerConfig(Settings);
                        Initialisation.ProcessConsoleOverrides(consoleOptions, processService, serverConfiguration, configurationService, logger);
                    }
                }

                ServerConfig serverConfig = configurationService.BuildServerConfig(Settings);
                Int32.TryParse(serverConfig.Port.ToString(), out Int32 configPort);
                string[] url = serverConfig.GetListenAddresses(serverConfig.AllowExternal).Take(1).ToArray(); //Kestrel doesn't need 127.0.0.1 and localhost to be registered, remove once off OWIN

                isWebHostRestart = false;

                try
                {
                    logger.Debug("Creating web host...");
                    CreateWebHostBuilder(args, url).Build().Run();
                }
                catch (Exception ex)
                {
                    if (ex.InnerException is Microsoft.AspNetCore.Connections.AddressInUseException)
                    {
                        logger.Error("Address already in use: Most likely Jackett is already running. " + ex.Message);
                        Environment.Exit(1);
                    }
                    logger.Error(ex);
                    throw;
                }
            } while (isWebHostRestart);
        }
示例#41
0
    protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
    {
        PythonConsoleOptions pyoptions = (PythonConsoleOptions)options;

        return(pyoptions.BasicConsole ? new BasicConsole(options.ColorfulConsole) : new SuperConsole(commandLine, options.ColorfulConsole));
    }
示例#42
0
        public void NoResultSuppressesAllResultSpecifications()
        {
            var options = new ConsoleOptions("test.dll", "-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2");

            Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
        }
示例#43
0
 /// <remarks>
 /// After the engine is created the standard output is replaced with our custom Stream class so we
 /// can redirect the stdout to the text editor window.
 /// This can be done in this method since the Runtime object will have been created before this method
 /// is called.
 /// </remarks>
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     SetOutput(new PythonOutputStream(textEditor));
     pythonConsole = new PythonConsole(textEditor, commandLine);
     if (ConsoleCreated != null)
     {
         ConsoleCreated(this, EventArgs.Empty);
     }
     return(pythonConsole);
 }
示例#44
0
 public ConsoleApp(IConsole console, ConsoleOptions options)
     : base(console, options)
 {
 }
示例#45
0
 public void TimeoutIsMinusOneIfNoOptionIsProvided()
 {
     ConsoleOptions options = new ConsoleOptions("tests.dll");
     Assert.True(options.Validate());
     Assert.AreEqual(-1, options.DefaultTimeout);
 }
示例#46
0
 public void MissingValuesAreReported(string option)
 {
     ConsoleOptions options = new ConsoleOptions(option + "=");
     Assert.False(options.Validate(), "Missing value should not be valid");
     Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]);
 }
示例#47
0
 public void X86AndInProcessAreCompatibleIn32BitProcess()
 {
     ConsoleOptions options = new ConsoleOptions("nunit.tests.dll", "--x86", "--inprocess");
     Assert.True(options.Validate());
     Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid");
 }
示例#48
0
 public ConsoleApp(ConsoleOptions options)
     : base(new StandardConsole(), options)
 {
 }
示例#49
0
 public void TwoTestParametersInSeparateOptions()
 {
     var options = new ConsoleOptions("-p:X=5", "-p:Y=7");
     Assert.That(options.errorMessages, Is.Empty);
     Assert.That(options.TestParameters, Is.EqualTo("X=5;Y=7"));
 }
示例#50
0
 public void ExploreOptionWithoutPath()
 {
     ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore");
     Assert.True(options.Validate());
     Assert.True(options.Explore);
 }
示例#51
0
 public void AssemblyAloneIsValid()
 {
     ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
     Assert.True(options.Validate());
     Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid");
 }
示例#52
0
 public void TimeoutParsesIntValueCorrectly()
 {
     ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:5000");
     Assert.True(options.Validate());
     Assert.AreEqual(5000, options.DefaultTimeout);
 }
示例#53
0
        static void Main(string[] args)
        {
            try
            {
                var options = new ConsoleOptions();
                if (!Parser.Default.ParseArguments(args, options) || options.ShowHelp == true)
                {
                    if (options.LastParserState != null && options.LastParserState.Errors.Count > 0)
                    {
                        var help   = new HelpText();
                        var errors = help.RenderParsingErrorsText(options, 2); // indent with two spaces
                        Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
                        Console.WriteLine("Switch error: " + errors);
                        Console.WriteLine("See --help for further details on switches.");
                        Environment.ExitCode = 1;
                        return;
                    }
                    else
                    {
                        var text = HelpText.AutoBuild(options, (HelpText current) => HelpText.DefaultParsingErrorsHandler(options, current));
                        text.Copyright = " ";
                        text.Heading   = "Jackett v" + Engine.ConfigService.GetVersion() + " options:";
                        Console.WriteLine(text);
                        Environment.ExitCode = 1;
                        return;
                    }
                }
                else
                {
                    if (options.ListenPublic && options.ListenPrivate)
                    {
                        Console.WriteLine("You can only use listen private OR listen publicly.");
                        Environment.ExitCode = 1;
                        return;
                    }
                    /*  ======     Options    =====  */

                    // SSL Fix
                    JackettStartup.DoSSLFix = options.SSLFix;

                    // Use curl
                    if (options.Client != null)
                    {
                        JackettStartup.ClientOverride = options.Client.ToLowerInvariant();
                    }

                    // Use Proxy
                    if (options.ProxyConnection != null)
                    {
                        JackettStartup.ProxyConnection = options.ProxyConnection.ToLowerInvariant();
                        Engine.Logger.Info("Proxy enabled. " + JackettStartup.ProxyConnection);
                    }
                    // Logging
                    if (options.Logging)
                    {
                        JackettStartup.LogRequests = true;
                    }

                    // Tracing
                    if (options.Tracing)
                    {
                        JackettStartup.TracingEnabled = true;
                    }

                    // Log after the fact as using the logger will cause the options above to be used

                    if (options.Logging)
                    {
                        Engine.Logger.Info("Logging enabled.");
                    }

                    if (options.Tracing)
                    {
                        Engine.Logger.Info("Tracing enabled.");
                    }

                    if (options.SSLFix == true)
                    {
                        Engine.Logger.Info("SSL ECC workaround enabled.");
                    }
                    else if (options.SSLFix == false)
                    {
                        Engine.Logger.Info("SSL ECC workaround has been disabled.");
                    }

                    // Ignore SSL errors on Curl
                    JackettStartup.IgnoreSslErrors = options.IgnoreSslErrors;
                    if (options.IgnoreSslErrors == true)
                    {
                        Engine.Logger.Info("Jackett will ignore SSL certificate errors.");
                    }

                    // Choose Data Folder
                    if (!string.IsNullOrWhiteSpace(options.DataFolder))
                    {
                        JackettStartup.CustomDataFolder = options.DataFolder.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(@"\\", @"\");
                        Engine.Logger.Info("Jackett Data will be stored in: " + JackettStartup.CustomDataFolder);
                    }

                    /*  ======     Actions    =====  */

                    // Install service
                    if (options.Install)
                    {
                        Engine.ServiceConfig.Install();
                        return;
                    }

                    // Uninstall service
                    if (options.Uninstall)
                    {
                        Engine.Server.ReserveUrls(doInstall: false);
                        Engine.ServiceConfig.Uninstall();
                        return;
                    }

                    // Reserve urls
                    if (options.ReserveUrls)
                    {
                        Engine.Server.ReserveUrls(doInstall: true);
                        return;
                    }

                    // Start Service
                    if (options.StartService)
                    {
                        if (!Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Start();
                        }
                        return;
                    }

                    // Stop Service
                    if (options.StopService)
                    {
                        if (Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Stop();
                        }
                        return;
                    }

                    // Migrate settings
                    if (options.MigrateSettings)
                    {
                        Engine.ConfigService.PerformMigration();
                        return;
                    }


                    // Show Version
                    if (options.ShowVersion)
                    {
                        Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
                        return;
                    }

                    /*  ======     Overrides    =====  */

                    // Override listen public
                    if (options.ListenPublic || options.ListenPrivate)
                    {
                        if (Engine.ServerConfig.AllowExternal != options.ListenPublic)
                        {
                            Engine.Logger.Info("Overriding external access to " + options.ListenPublic);
                            Engine.ServerConfig.AllowExternal = options.ListenPublic;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch to public listening without admin rights.");
                                    Environment.ExitCode = 1;
                                    return;
                                }
                            }

                            Engine.SaveServerConfig();
                        }
                    }

                    // Override port
                    if (options.Port != 0)
                    {
                        if (Engine.ServerConfig.Port != options.Port)
                        {
                            Engine.Logger.Info("Overriding port to " + options.Port);
                            Engine.ServerConfig.Port = options.Port;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch ports when not running as administrator");
                                    Environment.ExitCode = 1;
                                    return;
                                }
                            }

                            Engine.SaveServerConfig();
                        }
                    }

                    JackettStartup.NoRestart = options.NoRestart;
                }

                Engine.Server.Initalize();
                Engine.Server.Start();
                Engine.RunTime.Spin();
                Engine.Logger.Info("Server thread exit");
            }
            catch (Exception e)
            {
                Engine.Logger.Error(e, "Top level exception");
            }
        }
        public void ParameterWithMissingValueIsInvalid()
        {
            var options = new ConsoleOptions("--testparam:X=");

            Assert.That(options.ErrorMessages.Count, Is.EqualTo(1));
        }
示例#55
0
 public void SingleTestParameter()
 {
     var options = new ConsoleOptions("--params=X=5");
     Assert.That(options.errorMessages, Is.Empty);
     Assert.That(options.TestParameters, Is.EqualTo("X=5"));
 }
        public void ParameterWithoutEqualSignIsInvalid()
        {
            var options = new ConsoleOptions("--testparam=X5");

            Assert.That(options.ErrorMessages.Count, Is.EqualTo(1));
        }
示例#57
0
 public void TimeoutCausesErrorIfValueIsNotInteger()
 {
     ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:abc");
     Assert.False(options.Validate());
     Assert.AreEqual(-1, options.DefaultTimeout);
 }
 /// <remarks>
 /// After the engine is created the standard output is replaced with our custom Stream class so we
 /// can redirect the stdout to the text editor window.
 /// This can be done in this method since the Runtime object will have been created before this method
 /// is called.
 /// </remarks>
 protected override IConsole CreateConsole(ScriptEngine engine, CommandLine commandLine, ConsoleOptions options)
 {
     SetOutput(new PythonOutputStream(textEditor));
     pythonConsole = new PythonConsole(textEditor, commandLine);
     ConsoleCreated?.Invoke(this, EventArgs.Empty);
     //Runtime.SetTrace(OnTracebackReceived);//yzx
     return(pythonConsole);
 }
示例#59
0
        public void NoResultSuppressesDefaultResultSpecification()
        {
            var options = new ConsoleOptions("test.dll", "-noresult");

            Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
        }
示例#60
0
 public void NoInputFiles()
 {
     ConsoleOptions options = new ConsoleOptions();
     Assert.True(options.Validate());
     Assert.AreEqual(0, options.InputFiles.Count);
 }