コード例 #1
0
        public async Task DestroyExecutes()
        {
            using (var tmpCacheFile = new TemporaryFile())
            {
                var parameters = CommandLineParameters.Parse($"kdestroy --cache {tmpCacheFile.File}");

                var io = new InputControl
                {
                    Clear     = () => { },
                    HookCtrlC = hook => { },
                    Writer    = new StringWriter()
                };

                var command = (KerberosDestroyCommand)parameters.CreateCommandExecutor(io);

                Assert.IsNotNull(command);

                await command.Execute();

                var result = io.Writer.ToString();

                Assert.IsTrue(result.Contains("Cache file has been deleted."));

                var exists = File.Exists(tmpCacheFile.File);

                Assert.IsFalse(exists);
            }
        }
コード例 #2
0
ファイル: CommandLineTests.cs プロジェクト: z0h3/Kerberos.NET
        public void AllCommandsFound()
        {
            var types = LoadTypes();
            var io    = InputControl.Default();

            Assert.AreEqual(6, types.Count());

            foreach (var type in types)
            {
                var attr = type.GetCustomAttribute <CommandLineCommandAttribute>();

                Assert.IsNotNull(attr);

                Assert.IsNotNull(attr.Command);
                Assert.IsNotNull(attr.Description);

                var commandLine = CommandLineParameters.Parse(attr.Command);

                Assert.IsNotNull(commandLine);

                io.Writer = new StringWriter();

                var command = commandLine.CreateCommandExecutor(io);
                Assert.IsNotNull(command);

                command.DisplayHelp();

                Assert.IsTrue(!string.IsNullOrWhiteSpace(io.Writer.ToString()));
                Assert.IsTrue(io.Writer.ToString().Contains(attr.Command));
            }
        }
コード例 #3
0
        public void ParserGeneratesCommand()
        {
            var parameters = CommandLineParameters.Parse(KInitParameters);

            var command = parameters.CreateCommandExecutor(InputControl.Default());

            Assert.IsNotNull(command);
            Assert.IsInstanceOfType(command, typeof(KerberosInitCommand));
        }
コード例 #4
0
        public void CommandProcessesParameters()
        {
            var parameters = CommandLineParameters.Parse(KInitParameters);

            var command = (KerberosInitCommand)parameters.CreateCommandExecutor(InputControl.Default());

            Assert.AreEqual("foo\\bar\\baz.cache", command.Cache);
            Assert.AreEqual("foo.key", command.Keytab);

            Assert.IsTrue(command.Verbose);
            Assert.IsTrue(command.Forward.Value);
            Assert.IsTrue(command.Canonicalize.Value);
            Assert.IsNull(command.Proxy);
        }
コード例 #5
0
        public void CommandLineParser()
        {
            var parameters = CommandLineParameters.Parse(KInitParameters);

            Assert.IsNotNull(parameters);
            Assert.AreEqual("kinit", parameters.Command);
            Assert.AreEqual(7, parameters.Parameters.Length);
            Assert.AreEqual("-f", parameters.Parameters[0]);
            Assert.AreEqual("-C", parameters.Parameters[1]);
            Assert.AreEqual("-V", parameters.Parameters[2]);
            Assert.AreEqual("-t", parameters.Parameters[3]);
            Assert.AreEqual("foo.key", parameters.Parameters[4]);
            Assert.AreEqual("-c", parameters.Parameters[5]);
            Assert.AreEqual("foo\\bar\\baz.cache", parameters.Parameters[6]);
        }
コード例 #6
0
        public void Template_parameter_is_optional()
        {
            // ARRANGE
            var args = new[] { "--repository", "some-path" };

            // ACT
            var result = CommandLineParameters.Parse(args);

            // ASSERT
            Assert.Equal(ParserResultType.Parsed, result.Tag);
            Assert.Equal(typeof(CommandLineParameters), result.TypeInfo.Current);
            result.WithParsed(parsed =>
            {
                Assert.Null(parsed.Template);
            });
        }
コード例 #7
0
        private static async Task <Krb5Config> ExecuteCommand(string commandLine, string tmpCacheFile)
        {
            var io = new InputControl
            {
                Clear     = () => { },
                HookCtrlC = hook => { },
                Writer    = new StringWriter()
            };

            var parameters = CommandLineParameters.Parse(commandLine);

            var command = (KerberosConfigCommand)parameters.CreateCommandExecutor(io);

            await command.Execute();

            return(Krb5Config.Parse(File.ReadAllText(tmpCacheFile)));
        }
コード例 #8
0
        public void Template_parameter_is_parsed_correctly(string template, ChangeLogConfiguration.TemplateName expected)
        {
            // ARRANGE
            var args = new[] { "--repository", "some-path", "--template", template };

            // ACT
            var result = CommandLineParameters.Parse(args);

            // ASSERT
            Assert.Equal(ParserResultType.Parsed, result.Tag);
            Assert.Equal(typeof(CommandLineParameters), result.TypeInfo.Current);
            result.WithParsed(parsed =>
            {
                Assert.NotNull(parsed.Template);
                Assert.Equal(expected, parsed.Template);
            });
        }
コード例 #9
0
        public void CommandDisplaysHelp()
        {
            var parameters = CommandLineParameters.Parse(KInitParameters);

            var io = InputControl.Default();

            var textWriter = new StringWriter();

            io.Writer = textWriter;

            var command = parameters.CreateCommandExecutor(io);

            command.DisplayHelp();

            textWriter.Flush();
            var str = textWriter.ToString();

            Assert.IsTrue(str.Trim().StartsWith("Usage: kinit principal", System.StringComparison.OrdinalIgnoreCase));
        }
コード例 #10
0
        public async Task CommandLineHelpCommand()
        {
            var parameters = CommandLineParameters.Parse("help");

            var io = InputControl.Default();

            var textWriter = new StringWriter();

            io.Writer = textWriter;

            var command = parameters.CreateCommandExecutor(io);

            await command.Execute();

            textWriter.Flush();
            var str = textWriter.ToString();

            foreach (var result in new[] { "help", "kconfig", "kdestroy", "kinit", "klist" })
            {
                Assert.IsTrue(str.Contains(result));
            }
        }
コード例 #11
0
        static int MainWithContext(ScriptContext context, string[] args)
        {
            CommandLineParameters xsParams = getXsParams();
            int exitCode = 0;

            ConsoleRedirector redir = null;

            AppDomainLoader.progress("MainWithContext: Entering --------------------");
            bool utf8 = false;

            foreach (string arg in args)
            {
                if (arg.Equals(xs.utf8.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase))
                {
                    utf8 = true;
                }
            }
            using (ConsoleWithColors cout = new ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS"), utf8))
                using (CtrlCInterceptor ctrl = new CtrlCInterceptor())
                {
                    context.Output += cout.OnOutput;
                    ctrl.Output     = context.Error;
                    ctrl.Abort     += delegate { context.Abort(); };

                    Stopwatch w = Stopwatch.StartNew();
                    try
                    {
                        // Parse arguments
                        var usage = new UsageGenerator()
                        {
                            Options = UsageOptions.None
                        };
                        xsParams.Parse(context, args, false);
                        setOutputOptions(context, cout);

                        if (context.IsSet(xs.path))
                        {
                            context.ScriptPath = context.GetString(xs.path);
                        }

                        // Load references
                        List <IScriptAction> preScript = getCommandlineReferences(context);

                        // Print help
                        if (args.Length == 0 || context.IsSet(xs.help))
                        {
                            loadReferences(context, preScript);
                            exitCode = HelpHelper.Help(context, usage, xsParams);
                            goto end;
                        }

                        // Handle upgrade
                        if (context.GetBool(xs.upgrade, false))
                        {
                            return(upgrade(context));
                        }
                        if (context.IsSet(xs.updateStage))
                        {
                            return(updateStage(context, context.GetStringArray(xs.updateStage)));
                        }

                        AppDomainLoader.progress("MainWithContext: Processing options");
                        // Process the remaining options
                        context.Compiler.AddRequireAdmin(Utils.To <RequireAdminMode>(context.GetStr(xs.requireAdmin, RequireAdminMode.User.ToString())));

                        if (context.IsSet(xs.codeout))
                        {
                            context.CodeOutputDirectory = Path.GetFullPath(context.GetString(xs.codeout));
                        }
                        if (context.IsSet(xs.genconfig) || context.IsSet(xs.gensample))
                        {
                            genDemoConfig(cout, context);
                        }
                        if (context.IsSet(xs.forcenet20))
                        {
                            context.Compiler.DefaultNETVersion = new Version(2, 0);
                        }

                        AppDomainLoader.progress("MainWithContext: Processing options, continuing");

                        List <string> filteredArgs = new List <string>();
                        if (context.IsSet(xs.scriptargs))
                        {
                            filteredArgs.AddRange(context.GetStringArray(xs.scriptargs));
                        }


                        // Run utilities, like //download etc
                        Script script     = getInlineScript(context, filteredArgs);
                        string scriptName = context.GetString(xs.script, null);
                        if (script == null)
                        {
                            // Load the script
                            if (scriptName == "/?" || scriptName == "-?")
                            {
                                for (int i = 0; i < args.Length; ++i)
                                {
                                    if (args[i] == "/?" || args[i] == "-?")
                                    {
                                        if (i != args.Length - 1)
                                        {
                                            context[xs.help] = args[i + 1];
                                        }
                                        break;
                                    }
                                }
                                loadReferences(context, preScript);
                                return(HelpHelper.Help(context, usage, xsParams));
                            }
                            if (scriptName != null)
                            {
                                AppDomainLoader.progress("MainWithContext: Loading script " + scriptName);
                                script = loadScript(scriptName, context);
                                AppDomainLoader.progress("MainWithContext: Loading completed");
                            }
                        }

                        AppDomainLoader.progress("MainWithContext: About to initialize");
                        // Attach script
                        if (script != null)
                        {
                            // Insert pre-script before the script body
                            int n = 0;
                            foreach (var list in preScript)
                            {
                                script.Items.Insert(n++, list);
                            }

                            AppDomainLoader.BaseDirectory = script.DirectoryName;

                            RequireAdminMode mode = context.Compiler.RequireAdmin;
                            if ((!context.IsAdministrator || context.GetBool(xs.testElevation, false)) && !isCodeGeneration(context) && mode != RequireAdminMode.User)
                            {
                                return(restartAsAdmin(context, args, mode == RequireAdminMode.Hidden && !(context.GetBool(xs.testElevation, false))));
                            }

                            AppDomainLoader.progress("MainWithContext: Before script initialization");
                            if (isCodeGeneration(context))
                            {
                                if (!context.EnableCodePrecompilation && (context.IsSet(xs.genexe) ||
                                                                          context.IsSet(xs.genwinexe) ||
                                                                          context.IsSet(xs.genlibrary) ||
                                                                          context.IsSet(xs.gencs)))
                                {
                                    throw new ParsingException("One of the loaded scripts has precompilation disabled. Executable cannot be generated from this script.");
                                }
                                context.EnableCodePrecompilation = false;
                            }
                            ctrl.IgnoreCtrlC = script.IgnoreCtrlC;
                            ctrl.AbortDelay  = Utils.ToTimeSpan(script.AbortDelay) ?? ctrl.AbortDelay;
                            ctrl.ExitDelay   = Utils.ToTimeSpan(script.ExitDelay) ?? ctrl.ExitDelay;
                            context.Initialize(script);

                            AppDomainLoader.progress("MainWithContext: Script initialization completed");
                        }

                        // After precompilation we're ready to write .exe, if requested
                        if (isCodeGeneration(context))
                        {
                            doCodeGeneration(context, script);
                        }
                        else if (script != null)
                        {
                            // Run the script
                            AppDomainLoader.progress("MainWithContext: Before script execution");
                            redir = new ConsoleRedirector(context);
                            try
                            {
                                object r = context.ExecuteScript(script, filteredArgs.ToArray(), CallIsolation.High);
                                if (r != null)
                                {
                                    int.TryParse(r.ToString(), out exitCode);
                                }
                            }
                            finally
                            {
                                ctrl.KillAbortTimer();
                                redir.Dispose();
                                redir = null;
                            }

                            AppDomainLoader.progress("MainWithContext: Script execution completed");
                        }
                    }
                    catch (ThreadAbortException ae)
                    {
                        AppDomainLoader.progress("MainWithContext: ThreadAbortException is being aborted");
                        resetAbort(context);
                        context.WriteException(ae);
                        exitCode = -1;
                    }
                    catch (ScriptTerminateException te)
                    {
                        exitCode = te.ExitCode;
                        resetAbort(context);
                        if (te.InnerException != null)
                        {
                            context.WriteException(te.InnerException);
                            AppDomainLoader.progress("MainWithContext: " + te.InnerException);
                        }
                        AppDomainLoader.progress("MainWithContext: Terminating with exit code " + exitCode);
                    }
                    catch (Exception e)
                    {
                        exitCode = -1;
                        resetAbort(context);
                        context.WriteException(e);
                        AppDomainLoader.progress("MainWithContext: " + e);
                    }
                    finally
                    {
                        resetAbort(context);
                        AppDomainLoader.BaseDirectory = null;
                    }
end:
                    // Display how long did it take
                    w.Stop();
                    if (context.GetBool(xs.wait, false))
                    {
                        cout.WriteLine(OutputType.Info, string.Format("Completed in {0} with exit code={1}. Press Enter to close...", w.Elapsed, exitCode));
                        Console.ReadLine();
                    }
                }
            AppDomainLoader.progress("MainWithContext: Exiting with code " + exitCode);
            return(exitCode);
        }
コード例 #12
0
        private static KerberosInitCommand CreateCommand(string kdc, string upn, string cache, InputControl io)
        {
            var parameters = CommandLineParameters.Parse(string.Format(KInitParameters, kdc, upn, cache));

            return((KerberosInitCommand)parameters.CreateCommandExecutor(io));
        }
コード例 #13
0
ファイル: Script.cs プロジェクト: xsharper/xsharper
 /// Parse command line arguments
 public void ParseArguments(IEnumerable<string> args)
 {
     CommandLineParameters c = new CommandLineParameters(Parameters, SwitchPrefixes, UnknownSwitches);
     c.Parse(Context, args, (Usage.Options & UsageOptions.IfHelp) != 0);
 }