示例#1
0
        public void TestModeledAction()
        {
            bool invoked = false;

            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();

            var action = new CommandLineAction((d) =>
            {
                Assert.AreEqual("go", d.SpecifiedAction.DefaultAlias);
                Assert.AreEqual("Hawaii", d.SpecifiedAction.Arguments[0].RevivedValue);
                invoked = true;
            });

            action.Aliases.Add("go");
            action.Description = "A simple action";

            definition.Actions.Add(action);

            var actionString = action.ToString(); // Make sure it doesn't throw

            var destination = new CommandLineArgument(typeof(string), "destination");

            destination.Metadata.Add(new ArgRequired());
            destination.Description = "The place to go to";

            action.Arguments.Add(destination);

            Args.InvokeAction(definition, "go", "-destination", "Hawaii");
            Assert.IsTrue(invoked);

            var usage = ArgUsage.GenerateUsageFromTemplate(definition);

            Assert.IsTrue(usage.Contains("A simple action"));
            Assert.IsTrue(usage.Contains("The place to go to"));
        }
 /// <summary>
 /// Creates a new in process stage given a base definition and a command line
 /// </summary>
 /// <param name="baseDefinition">The definition that describes actions that can be invoked using the given command line</param>
 /// <param name="commandLine">The command line that represents the structure of this stage</param>
 public InProcessPipelineStage(CommandLineArgumentsDefinition baseDefinition, string [] commandLine)
     : base(commandLine)
 {
     this.baseDefinition = baseDefinition;
     queueLock = new object();
     inputQueue = new Queue<object>();
 }
        public static void RunOptionProcessing([NotNull] string connectionString, [ItemNotNull][NotNull] string[] args, string exename)
        {
            CommandProcessor.ConnectionString = connectionString;
            Config.IsInHeadless = true;
            var definition = new CommandLineArgumentsDefinition(typeof(CommandProcessor))
            {
                ExeName = exename
            };

            if (!Config.CatchErrors)
            {
                try
                {
                    var parsed = Args.ParseAction(definition, args);
                    if (parsed.ActionArgs == null)
                    {
                        throw new LPGException("Invalid args: ");
                    }
                }
                catch (ArgException ex)
                {
                    throw new LPGException("Invalid args: " + ex.Message);
                }
            }

            Args.InvokeAction(definition, args);
        }
示例#4
0
        protected override void OnObjectReceived(object o)
        {
            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition(typeof(FilterAction));

            def.FindMatchingArgument("FilterTarget").RevivedValueOverride = o;
            Args.InvokeMain(def, CmdLineArgs.ToArray());
        }
        public void TestUsagePrimitive()
        {
            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition(typeof(TestArgs));
            var rendered = new DocumentRenderer().Render("Your program has {{Arguments.Count!}} arguments", def);

            Assert.AreEqual("Your program has 2 arguments", rendered.ToString());
        }
示例#6
0
        private static IEnumerable <ITabCompletionSource> FindNewTabCompletionHooks(CommandLineArgumentsDefinition definition)
        {
            List <ITabCompletionSource> completionSources = new List <ITabCompletionSource>();

            if (definition.Metadata.HasMeta <TabCompletion>() && definition.Metadata.Meta <TabCompletion>().CompletionSourceType != null && definition.Metadata.Meta <TabCompletion>().CompletionSourceType.GetInterfaces().Contains(typeof(ITabCompletionSource)))
            {
                completionSources.Add((ITabCompletionSource)ObjectFactory.CreateInstance(definition.Metadata.Meta <TabCompletion>().CompletionSourceType));
            }

            foreach (var argument in definition.AllGlobalAndActionArguments)
            {
                foreach (var argSource in argument.Metadata.Metas <ArgumentAwareTabCompletionAttribute>())
                {
                    var source = argSource.CreateTabCompletionSource(definition, argument);
                    if (source is ITabCompletionSource)
                    {
                        completionSources.Insert(0, (ITabCompletionSource)source);
                    }
                }

                if (argument.ArgumentType.IsEnum)
                {
                    completionSources.Insert(0, new EnumTabCompletionSource(argument));
                }
            }
            completionSources.Add(new ActionAndArgumentSmartTabCompletionSource());
            completionSources.Add(new FileSystemTabCompletionSource());

            return(completionSources);
        }
示例#7
0
 public PowerArgsMultiContextAssistProvider(CommandLineArgumentsDefinition definition)
 {
     this.Definition   = definition;
     standardProviders = new List <IContextAssistProvider>();
     standardProviders.Add(new EnumAssistant(definition));
     standardProviders.Add(new ActionAssistant(definition));
 }
示例#8
0
        public void TestPowerArgsRichCommandLineReaderFindContextualAction()
        {
            try
            {
                PowerArgsRichCommandLineReader.FindContextualAction("doesnotmatter");
                Assert.Fail("An exception should have been thrown");
            }
            catch (NullReferenceException ex)
            {
                Assert.IsTrue(ex.Message.Contains("ambient"));
            }

            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition();

            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualAction(null, def));
            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualAction("", def));
            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualAction("NonMatchingAction", def));

            var action = new CommandLineAction((d) => { });

            action.Aliases.Add("TheAction");

            def.Actions.Add(action);

            var found = PowerArgsRichCommandLineReader.FindContextualAction("theaction", def);

            Assert.AreSame(action, found);
        }
示例#9
0
        public void TestOverrideDefaultReviver()
        {
            var intReviver = ArgRevivers.GetReviver(typeof(int));

            try
            {
                ArgRevivers.SetReviver <int>((k, v) => { return(-1); });

                var def = new CommandLineArgumentsDefinition();
                def.Arguments.Add(new CommandLineArgument(typeof(int), "theInt"));
                Args.Parse(def, "-theInt", "100");
                Assert.AreEqual(-1, def.FindMatchingArgument("theInt").RevivedValue);
            }
            finally
            {
                ArgRevivers.SetReviver(typeof(int), intReviver);
            }

            // make sure the old reviver is working again
            var newDef = new CommandLineArgumentsDefinition();

            newDef.Arguments.Add(new CommandLineArgument(typeof(int), "theInt"));
            Args.Parse(newDef, "-theInt", "100");
            Assert.AreEqual(100, newDef.FindMatchingArgument("theInt").RevivedValue);
        }
示例#10
0
        public void TestShortcutGenerationEdgeCase2()
        {
            var def = new CommandLineArgumentsDefinition(typeof(StrangeShortcuts2));

            Assert.AreEqual(1, def.Arguments[1].Aliases.Count);
            Assert.AreEqual("Foo", def.Arguments[1].DefaultAlias);
        }
        public void TestREPLReset()
        {
            SetupCleanup.ClearAttributeCache();
            var provider = TestConsoleProvider.SimulateConsoleInput("-b{enter}-s a{enter}quit");
            var def      = new CommandLineArgumentsDefinition(typeof(TestArgsWithREPL));
            var boolArg  = def.FindMatchingArgument("b");

            Assert.IsNotNull(boolArg);

            bool first         = true;
            bool validatedBoth = false;
            var  interceptor   = new AfterInvokeInterceptor((context) =>
            {
                if (first)
                {
                    first = false;
                    Assert.IsTrue((bool)boolArg.RevivedValue);
                }
                else
                {
                    Assert.IsNull(boolArg.RevivedValue);
                    validatedBoth = true;
                }
            });

            def.Metadata.Add(interceptor);

            var finalResult = Args.InvokeMain(def, "$");

            Assert.IsTrue(validatedBoth);
            Assert.IsFalse((finalResult.Value as TestArgsWithREPL).BoolParam);
        }
示例#12
0
        public void TestPowerArgsRichCommandLineReaderFindContextualArgument()
        {
            var args = new PowerArgsRichCommandLineReader.FindContextualArgumentArgs()
            {
                CurrentTokenIndex = 0,
                CommandLine       = "-TheString",
                PreviousToken     = "-TheString",
            };

            try
            {
                PowerArgsRichCommandLineReader.FindContextualArgument(args);
                Assert.Fail("An exception should have been thrown");
            }
            catch (NullReferenceException ex)
            {
                Assert.IsTrue(ex.Message.Contains("ambient"));
            }

            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition();
            var globalArg = new CommandLineArgument(typeof(string), "TheString");

            def.Arguments.Add(globalArg);

            args.Definition = def;
            var found = PowerArgsRichCommandLineReader.FindContextualArgument(args);

            Assert.AreSame(globalArg, found);

            args.CommandLine   = "/TheString";
            args.PreviousToken = args.CommandLine;
            found = PowerArgsRichCommandLineReader.FindContextualArgument(args);
            Assert.AreSame(globalArg, found);

            args.CommandLine   = "-ActionInt";
            args.PreviousToken = args.CommandLine;
            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualArgument(args));
            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualArgument(args));

            var action = new CommandLineAction((d) => { });

            action.Aliases.Add("TheAction");

            var actionArg = new CommandLineArgument(typeof(int), "ActionInt");

            action.Arguments.Add(actionArg);
            def.Actions.Add(action);

            args.CommandLine   = "-TheString";
            args.PreviousToken = args.CommandLine;
            args.ActionContext = action;
            found = PowerArgsRichCommandLineReader.FindContextualArgument(args);
            Assert.AreSame(globalArg, found);

            args.CommandLine   = "-ActionInt";
            args.PreviousToken = args.CommandLine;
            found = PowerArgsRichCommandLineReader.FindContextualArgument(args);
            Assert.AreSame(actionArg, found);
        }
示例#13
0
        public IEnumerable <ICommandArgument> GetArguments(Type type)
        {
            var argDefinition = new CommandLineArgumentsDefinition(type);

            return(argDefinition.Arguments.Select(item => new CommandArgument {
                Name = item.DefaultAlias, Required = item.IsRequired
            }));
        }
示例#14
0
        protected override void OnObjectReceived(object o)
        {
            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition(typeof(FilterAction));
            var arg = def.FindMatchingArgument("FilterTarget");

            def.Metadata.Add(new ArgumentOverrideHook(arg, o));
            Args.InvokeMain(def, CmdLineArgs.ToArray());
        }
 private static bool TryParseStageAction(CommandLineArgumentsDefinition effectiveDefinition, string actionKey, out CommandLineAction action)
 {
     if (actionKey == null)
     {
         throw new ArgException("Unexpected '|' at end of pipeline");
     }
     action = effectiveDefinition.FindMatchingAction(actionKey);
     return(action != null);
 }
示例#16
0
 /// <summary>
 /// Finds the action that matches the given token in the given definition
 /// </summary>
 /// <param name="firstToken">the token to test.  If you pass null you will get null back.</param>
 /// <param name="def">The definition to inspect.  If null, the ambient definition will be used.  If there is no ambient definition and null is passed then this method throws a NullReferenceException.</param>
 /// <returns>the action that matches the given token in the given definition or null if no such action is found</returns>
 public static CommandLineAction FindContextualAction(string firstToken, CommandLineArgumentsDefinition def = null)
 {
     def = PassThroughOrTryGetAmbientDefinition(def);
     if (firstToken == null)
     {
         return(null);
     }
     return(def.FindMatchingAction(firstToken));
 }
示例#17
0
        public static List <string> GetShortcuts(this Type t, string propertyName)
        {
            var d = new CommandLineArgumentsDefinition(t);
            var p = d.Arguments.Where(a => a.DefaultAlias == propertyName).Single();

            var aliases = p.Aliases.ToList();

            aliases.RemoveAt(0);
            return(aliases);
        }
示例#18
0
        public void TestPhotoAlbumManagerConsoleUsage()
        {
            var def = new CommandLineArgumentsDefinition(typeof(PhotoAlbumManagerArgs));

            def.ExeName = "PhotoManager";
            var browserUsage = ArgUsage.GenerateUsageFromTemplate(def, template: PowerArgs.Resources.DefaultBrowserUsageTemplate).ToString().Replace("\r\n", "\n");
            var consoleUsage = ArgUsage.GenerateUsageFromTemplate(def).ToString().Replace("\r\n", "\n");

            AssertAreEqualWithDiffInfo(Resources.PhotoAlbumManagerExpectedBrowserUsage.Replace("\r\n", "\n"), browserUsage);
            AssertAreEqualWithDiffInfo(Resources.PhotoAlbumManagerExpectedConsoleUsage.Replace("\r\n", "\n"), consoleUsage);
        }
示例#19
0
        public void TestWhichShortcut()
        {
            var def    = new CommandLineArgumentsDefinition(typeof(WhichShortcutTest));
            var parsed = Args.Parse(def, "-vv");
            var which  = def.Arguments
                         .Where(a => a.DefaultAlias == nameof(Verbose))
                         .Single().Metadata
                         .WhereAs <WhichShortcutHook>().Single().ArgVal;

            Assert.AreEqual("-vv", which);
        }
示例#20
0
        public void TestNullablesInTableExpression()
        {
            var def   = new CommandLineArgumentsDefinition(typeof(NullableArgs));
            var usage = ArgUsage.GenerateUsageFromTemplate(def, UsageTemplates.ConsoleTemplate, "dynamic template").ToString();

            Assert.IsTrue(usage.Contains("Monday"));
            Assert.IsTrue(usage.Contains("Tuesday"));
            Assert.IsTrue(usage.Contains("Wednesday"));
            Assert.IsTrue(usage.Contains("Thursday"));
            Assert.IsTrue(usage.Contains("Friday"));
            Assert.IsTrue(usage.Contains("Saturday"));
            Assert.IsTrue(usage.Contains("Sunday"));
        }
示例#21
0
        public void TestProductMetadataFields()
        {
            var def = new CommandLineArgumentsDefinition(typeof(BasicArgs));

            Assert.AreEqual("The product name", def.ProductName);
            Assert.AreEqual("The copyright string", def.Copyright);
            Assert.AreEqual("The product version", def.ProductVersion);

            var def2 = new CommandLineArgumentsDefinition(typeof(BasicArgsSC));

            Assert.IsNull(def2.ProductName);
            Assert.IsNull(def2.Copyright);
            Assert.IsNull(def2.ProductVersion);
        }
示例#22
0
        public OptionSource[] Parse <TOptions>(string[] args) where TOptions : class
        {
            _parsedOptions = new List <OptionSource>();
            var definition     = new CommandLineArgumentsDefinition(typeof(TOptions));
            var options        = (TOptions)Args.Parse(definition, args).Value;
            var changedOptions = definition.Arguments.Where(x => x.RevivedValue != null).ToList();

            foreach (var changedOption in changedOptions)
            {
                var optionName = ((System.Reflection.PropertyInfo)changedOption.Source).Name;
                _parsedOptions.Add(new OptionSource("Command Line", optionName, changedOption.RevivedValue));
            }
            return(_parsedOptions.ToArray());
        }
示例#23
0
        public void TestPowerArgsRichCommandLineReaderFindCurrentTokenArgument()
        {
            bool expect;

            try
            {
                PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, null, out expect);
            }
            catch (NullReferenceException ex)
            {
                Assert.IsTrue(ex.Message.Contains("ambient"));
            }

            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition();
            var globalArg = new CommandLineArgument(typeof(int), "TheInt");

            def.Arguments.Add(globalArg);
            Assert.IsNull(PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, null, out expect, def));
            Assert.IsFalse(expect);

            var found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "-TheInt", out expect, def);

            Assert.AreSame(globalArg, found);
            Assert.IsTrue(expect);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "/TheInt", out expect, def);
            Assert.AreSame(globalArg, found);
            Assert.IsTrue(expect);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "TheInt", out expect, def);
            Assert.IsNull(found);
            Assert.IsFalse(expect);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "-ActionInt", out expect, def);
            Assert.IsNull(found);
            Assert.IsTrue(expect);

            var action = new CommandLineAction((d) => { });

            action.Aliases.Add("TheAction");
            var actionArg = new CommandLineArgument(typeof(int), "ActionInt");

            action.Arguments.Add(actionArg);
            def.Actions.Add(action);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(action, "-ActionInt", out expect, def);
            Assert.AreSame(actionArg, found);
            Assert.IsTrue(expect);
        }
        public void TestArgumentAwareSmartTabCompletion()
        {
            var input = "m\t -a\t \t"; // should expand to 'meats -animal Chicken;

            ConsoleProvider.Current = new TestConsoleProvider(input);
            var definition = new CommandLineArgumentsDefinition(typeof(ConflictingArgumentsThatAwesomeTabCompletionMakesBetter));

            PowerArgsRichCommandLineReader reader = new PowerArgsRichCommandLineReader(definition, new List <ConsoleString>());

            reader.ThrowOnSyntaxHighlightException = true;
            reader.TabHandler.ThrowOnTabCompletionHandlerException = true;
            var completed = string.Join(" ", reader.ReadCommandLine());

            Assert.AreEqual("meats -animal Chicken", completed);
        }
示例#25
0
        public void TestCustomTemplateInHelpHook()
        {
            var def = new CommandLineArgumentsDefinition(typeof(CustomUsageTemplateInHelpHookArgs));

            bool validated = false;

            def.Arguments.Find(a => a.DefaultAlias == "Help").Metadata.Meta <HelpHook>().UsageWritten += (theUsage) =>
            {
                Assert.AreEqual("Hello", theUsage.ToString());
                validated = true;
            };

            var action = Args.InvokeMain(def, "-h");

            Assert.IsTrue(validated);
        }
示例#26
0
        public void TestSimpleModel()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var argument = new CommandLineArgument(typeof(int), "somenumber");

            definition.Arguments.Add(argument);

            var argumentString = argument.ToString(); // Make sure it doesn't throw

            Args.Parse(definition, new string[] { "-somenumber", "100" });
            Assert.AreEqual(100, definition.Arguments[0].RevivedValue);

            definition.Arguments[0].RevivedValue = null;
            Args.Parse(definition, new string[] { "/somenumber:100" });
            Assert.AreEqual(100, definition.Arguments[0].RevivedValue);
        }
示例#27
0
        /// <summary>
        /// Configures the reader for the given definition and history information.
        /// </summary>
        /// <param name="definition">The definition to use to configure the reader</param>
        /// <param name="history">previous command line values that the end user will be able to cycle through using the up and down arrows</param>
        public PowerArgsRichCommandLineReader(CommandLineArgumentsDefinition definition, List <ConsoleString> history)
        {
            this.Console = ConsoleProvider.Current;
            this.HistoryManager.Values.AddRange(history);
            this.TabHandler.TabCompletionHandlers.Add(this);
            this.ContextAssistProvider = new PowerArgsMultiContextAssistProvider(definition);
            this.Definition            = definition;

            this.ArgumentNameForeground  = ConsoleColor.Cyan;
            this.NumericForeground       = ConsoleColor.Green;
            this.StringLiteralForeground = ConsoleColor.Yellow;
            this.ActionForeground        = ConsoleColor.Magenta;

            this.newHooks = FindNewTabCompletionHooks(this.Definition);
            InitHighlighters();
        }
示例#28
0
        public void TestConflictingAliasDefinitions()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var argument = new CommandLineArgument(typeof(int), "somenumber");

            argument.Metadata.Add(new ArgShortcut("some"));

            try
            {
                argument.Aliases.Add("some");
                Assert.Fail("An exception should have been thrown");
            }
            catch (InvalidArgDefinitionException ex)
            {
                Assert.AreEqual(ex.Message, "The alias 'some' has already been added");
            }
        }
示例#29
0
        public void TestLongFormBasic()
        {
            var args = Args.Parse <LongFormArgs>("--your-age", "100");

            Assert.AreEqual(100, args.Age);

            var args2 = Args.Parse <LongFormArgs>("--your-age=100");

            Assert.AreEqual(100, args2.Age);

            var definition = new CommandLineArgumentsDefinition(typeof(LongFormArgs));

            var aliases = definition.Arguments.Where(a => a.DefaultAlias == "Age").Single().Aliases;

            Assert.AreEqual(2, aliases.Count);
            Assert.AreEqual("-your-age", aliases[1]);
        }
        /// <summary>
        /// Configures the reader for the given definition and history information.
        /// </summary>
        /// <param name="definition">The definition to use to configure the reader</param>
        /// <param name="history">previous command line values that the end user will be able to cycle through using the up and down arrows</param>
        public PowerArgsRichCommandLineReader(CommandLineArgumentsDefinition definition, List<ConsoleString> history)
        {
            this.Console = ConsoleProvider.Current;
            this.HistoryManager.Values.AddRange(history);
            this.TabHandler.TabCompletionHandlers.Add(this);
            this.ContextAssistProvider = new PowerArgsMultiContextAssistProvider(definition);
            this.Definition = definition;

            this.ArgumentNameForeground = ConsoleColor.Cyan;
            this.NumericForeground = ConsoleColor.Green;
            this.StringLiteralForeground = ConsoleColor.Yellow;
            this.ActionForeground = ConsoleColor.Magenta;

            this.oldHooks = FindOldTabCompletionHooks(this.Definition);
            this.newHooks = FindNewTabCompletionHooks(this.Definition);
            InitHighlighters();
        }
示例#31
0
        public void TestPhotoAlbumManagerConsoleUsage()
        {
            ConsoleProvider.Current = new CLI.CliUnitTestConsole()
            {
                BufferWidth = 160
            };
            var def = new CommandLineArgumentsDefinition(typeof(PhotoAlbumManagerArgs));

            def.ExeName = "PhotoManager";
            var browserUsage = ArgUsage.GenerateUsageFromTemplate(def, template: UsageTemplates.BrowserTemplate).ToString().Replace("\r\n", "\n").Replace("\r", "\n");
            var consoleUsage = ArgUsage.GenerateUsageFromTemplate(def).ToString().Replace("\r\n", "\n").Replace("\r", "\n");



            Helpers.AssertAreEqualWithDiffInfo(Resources.PhotoAlbumManagerExpectedBrowserUsage.Replace("\r\n", "\n").Replace("\r", "\n"), browserUsage);
            Helpers.AssertAreEqualWithDiffInfo(Resources.PhotoAlbumManagerExpectedConsoleUsage.Replace("\r\n", "\n").Replace("\r", "\n"), consoleUsage);
        }
示例#32
0
        public void TestConflictingOverride(Action <CommandLineArgument> variation, string errorMessageExpectedContents)
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var argument = new CommandLineArgument(typeof(int), "somenumber");

            definition.Arguments.Add(argument);
            variation(argument);
            try
            {
                Args.Parse(definition, "-somenumber", "100");
                Assert.Fail("An exception should have been thrown");
            }
            catch (InvalidArgDefinitionException ex)
            {
                Assert.IsTrue(ex.Message.Contains(errorMessageExpectedContents));
            }
        }
        internal static TabCompletionContext ConvertContext(CommandLineArgumentsDefinition definition, RichCommandLineContext innerContext)
        {
            TabCompletionContext context = new TabCompletionContext();
            context.Definition = definition;
            context.Shift = innerContext.KeyPressed.Modifiers.HasFlag(ConsoleModifiers.Shift);
            context.PreviousToken = innerContext.CurrentTokenIndex > 0 ? innerContext.PreviousNonWhitespaceToken.Value : string.Empty;
            context.CompletionCandidate = innerContext.CurrentToken.Value;

            if (context.CompletionCandidate == " ")
            {
                context.CompletionCandidate = "";
            }

            context.CommandLineText = new ConsoleString(innerContext.Buffer).ToString();
            context.TargetAction = FindContextualAction(innerContext.Tokens.FirstOrDefault().Value, definition);
            context.TargetArgument = FindContextualArgument(context.PreviousToken, context.TargetAction, definition);
            return context;
        }
        private static IEnumerable<ITabCompletionSource> FindOldTabCompletionHooks(CommandLineArgumentsDefinition definition)
        {
            List<ITabCompletionSource> completionSources = new List<ITabCompletionSource>();

            if (definition.Metadata.HasMeta<TabCompletion>() && definition.Metadata.Meta<TabCompletion>().CompletionSourceType != null && definition.Metadata.Meta<TabCompletion>().CompletionSourceType.GetInterfaces().Contains(typeof(ITabCompletionSource)))
            {
                completionSources.Add((ITabCompletionSource)Activator.CreateInstance(definition.Metadata.Meta<TabCompletion>().CompletionSourceType));
            }

            foreach (var argument in definition.AllGlobalAndActionArguments)
            {
                foreach (var argSource in argument.Metadata.Metas<ArgumentAwareTabCompletionAttribute>())
                {
                    var source = argSource.CreateTabCompletionSource(definition, argument);
                    if (source is ITabCompletionSource)
                    {
                        completionSources.Insert(0, (ITabCompletionSource)source);
                    }
                }
            }

            return completionSources;
        }
示例#35
0
 private static bool TryParseStageAction(CommandLineArgumentsDefinition effectiveDefinition, string actionKey, out CommandLineAction action)
 {
     if (actionKey == null) throw new ArgException("Unexpected '|' at end of pipeline");
     action = effectiveDefinition.FindMatchingAction(actionKey);
     return action != null;
 }
 private static CommandLineArgumentsDefinition PassThroughOrTryGetAmbientDefinition(CommandLineArgumentsDefinition def)
 {
     if(def != null)
     {
         return def;
     }
     else if(ArgHook.HookContext.Current != null && ArgHook.HookContext.Current.Definition != null)
     {
         return ArgHook.HookContext.Current.Definition;
     }
     else
     {
         throw new NullReferenceException("There is no ambient CommandLineArgumentsDefinition argument and you did not pass one in explicitly");
     }
 }
示例#37
0
 /// <summary>
 /// Creates an instance of the stage given a base definition and a command line
 /// </summary>
 /// <param name="baseDefinition">The base definition that declares which actions are supported by this program</param>
 /// <param name="commandLine">The command line arguments</param>
 public ExternalPipelineInputStage(CommandLineArgumentsDefinition baseDefinition, string[] commandLine)
     : base(commandLine)
 {
 }
        /// <summary>
        /// A helper that detects the argument represented by the current token given a definition.  
        /// </summary>
        /// <param name="previousToken">The token to inspect.  If you pass null you will get null back.</param>
        /// <param name="contextualAction">An action to inspect for a match if the current token does not match a global argument.  Pass null to only check global arguments.</param>
        /// <param name="def">The definition to inspect.  If null, the ambient definition will be used.  If there is no ambient definition and null is passed then this method throws a NullReferenceException.</param>
        /// <returns>An argument that is matched by the given token or null if there was no match</returns>
        public static CommandLineArgument FindContextualArgument(string previousToken, CommandLineAction contextualAction, CommandLineArgumentsDefinition def = null)
        {
            def = PassThroughOrTryGetAmbientDefinition(def);

            if (previousToken == null)
            {
                return null;
            }

            string currentTokenArgumentNameValue = null;
            if (previousToken.StartsWith("-"))
            {
                currentTokenArgumentNameValue = previousToken.Substring(1);
            }
            else if (previousToken.StartsWith("/"))
            {
                currentTokenArgumentNameValue = previousToken.Substring(1);
            }

            CommandLineArgument currentTokenArgument = null;
            if (currentTokenArgumentNameValue != null)
            {
                currentTokenArgument = def.Arguments.Where(arg => arg.IsMatch(currentTokenArgumentNameValue) && arg.ArgumentType != typeof(bool)).SingleOrDefault();

                if (currentTokenArgument == null && contextualAction != null)
                {
                    currentTokenArgument = contextualAction.Arguments.Where(arg => arg.IsMatch(currentTokenArgumentNameValue) && arg.ArgumentType != typeof(bool)).SingleOrDefault();
                }
            }
            return currentTokenArgument;
        }
 public PowerArgsMultiContextAssistProvider(CommandLineArgumentsDefinition definition)
 {
     this.Definition = definition;
     standardProviders = new List<IContextAssistProvider>();
     standardProviders.Add(new EnumAssistant(definition));
     standardProviders.Add(new ActionAssistant(definition));
 }
 public EnumAssistant(CommandLineArgumentsDefinition definition)
     : base(definition)
 {
 }
 public PowerArgsContextAwareAssistant(CommandLineArgumentsDefinition definition)
 {
     this.Definition = definition;
 }
        public HttpInputPipelineStage(CommandLineArgumentsDefinition baseDefinition, string[] rawCommandLine)
            : base(baseDefinition, CleanCommandLineOfInputPortInfo(rawCommandLine))
        {
            int port;

            if (TryFindPort(rawCommandLine, out port) == false)
            {
                IsProgramLaunchedByExternalPipeline = false;
                return;
            }
            else
            {
                IsProgramLaunchedByExternalPipeline = true;
            }

            Init.InitIfNotAlreadyDone();

            interceptor = ConsoleOutInterceptor.Instance;
            interceptor.Attach();
            PowerLogger.LogLine("Initializing input pipe for command line on port "+port+": "+string.Join(" ", this.CmdLineArgs));
            wrappedStage = new InProcessPipelineStage(baseDefinition, this.CmdLineArgs.ToArray());
            listener = new HttpPipelineMessageListener(port, TimeSpan.FromSeconds(10));

            listener.Timeout += () =>
            {
                PowerLogger.LogLine("HttpInputPipelineStage listener timed out.");
                Process.GetCurrentProcess().Kill();
            };

            wrappedStage.UnhandledException += (ex) =>
            {
                QueueException(ex);
            };

            listener.ListenException += (ex) =>
            {
                QueueException(ex);
            };

            listener.MessageReceivedHandler = (message) =>
            {
                if (message.ControlAction == null)
                {
                    LogLine("Pipe input received");
                    var pipedObject = DeserializePipedObject(message);
                    wrappedStage.CommandLineDefinitionFactory = this.CommandLineDefinitionFactory;
                    wrappedStage.Accept(pipedObject);
                    LogLine("Pipe input processed");
                    return new HttpPipelineControlResponse() { StatusCode = HttpStatusCode.Accepted  };

                }
                else if (message.ControlAction == "Drain")
                {
                    Drain();
                    return new HttpPipelineControlResponse() { StatusCode = HttpStatusCode.Accepted };
                }
                else if (message.ControlAction == "Poll")
                {
                    LogLine("Poll requested");
                    string pipedObjectArrayJson = null;
                    string exceptionInfo = null;
                    List<ConsoleCharacter> textOutput = null;
                    lock (outputQueueLock)
                    {
                        List<object> batch = new List<object>();
                        while (outputQueue.Count > 0)
                        {
                            batch.Add(outputQueue.Dequeue());
                        }

                        if (batch.Count > 0)
                        {
                            LogLine("Pipe output sent");
                            pipedObjectArrayJson = JsonConvert.SerializeObject(batch, HttpPipelineMessage.CommonSettings);
                        }

                        while(exceptionQueue.Count > 0)
                        {
                            LogLine("Exception output sent");
                            exceptionInfo = exceptionInfo ?? "";
                            exceptionInfo += exceptionQueue.Dequeue().ToString() + Environment.NewLine + Environment.NewLine;
                        }

                        var interceptedText = interceptor.ReadAndClear();

                        while(interceptedText.Count > 0)
                        {
                            textOutput = textOutput ?? new List<ConsoleCharacter>();
                            textOutput.Add(interceptedText.Dequeue());
                        }

                        while(textOutputQueue.Count > 0)
                        {
                            textOutput = textOutput ?? new List<ConsoleCharacter>();
                            textOutput.Add(textOutputQueue.Dequeue());
                        }
                    }
                    return new HttpPipelineControlResponse() { StatusCode = HttpStatusCode.OK, ExceptionInfo = exceptionInfo, ConsoleOutput = textOutput, PipedObjectArrayJson = pipedObjectArrayJson, Value = wrappedStage.IsDrained + "" };
                }
                else if (message.ControlAction == "Close")
                {
                    LogLine("Close requested");
                    ArgPipeline.ObjectExitedPipeline -= outputHandler;
                    return new HttpPipelineControlResponse() { StatusCode = HttpStatusCode.OK, Close = true };
                }
                else
                {
                    LogLine("Unrecognized action: " + message.ControlAction);
                    return new HttpPipelineControlResponse() { StatusCode = HttpStatusCode.BadRequest, ConsoleOutput = new ConsoleString("Unrecognized action: "+message.ControlAction).ToList() };
                }
            };

            outputHandler = (obj) =>
            {
                LogLine("Pipe output queued");
                lock(outputQueueLock)
                {
                    outputQueue.Enqueue(obj);
                }
            };

            ArgPipeline.ObjectExitedPipeline += outputHandler;

            listener.Start();
        }
        private string[] MapObject(object o, CommandLineArgumentsDefinition effectiveDefinition)
        {
            List<string> newCommandLine = new List<string>();
            newCommandLine.AddRange(CmdLineArgs);

            var preParseResult = ArgParser.Parse(effectiveDefinition, newCommandLine.ToArray());

            var predictedAction = effectiveDefinition.FindMatchingAction(this.CmdLineArgs[0]);

            if (predictedAction == null)
            {
                PowerLogger.LogLine("Could not determine action: "+this.CmdLineArgs[0]+" - Here are the supported action:");
                foreach(var action in effectiveDefinition.Actions)
                {
                    PowerLogger.LogLine("  "+action.DefaultAlias);
                }
                throw new ArgException("TODO - Could not determine action: "+this.CmdLineArgs[0]);
            }

            PowerLogger.LogLine("Predicted action is " + predictedAction.DefaultAlias);

            var argsToInspectForDirectMappingTarget = predictedAction.Arguments.Union(effectiveDefinition.Arguments).ToList();
            var directMappingTarget = (from argument in argsToInspectForDirectMappingTarget
                                       where argument.Metadata.HasMeta<ArgPipelineTarget>()
                                       select argument).SingleOrDefault();

            if (directMappingTarget != null)
            {
                var revivedValue = o;
                if (IsCompatible(o, directMappingTarget) == false)
                {
                    PowerLogger.LogLine("Need to map "+o.GetType().FullName+" to "+directMappingTarget.ArgumentType.FullName);

                    if(TrySimpleConvert(o, directMappingTarget.ArgumentType, out revivedValue))
                    {
                        // we're good
                    }
                    else if (ArgPipelineObjectMapper.CurrentMapper == null)
                    {
                        throw new InvalidArgDefinitionException("Unable to attempt tp map type " + o.GetType().FullName + " to " + directMappingTarget.ArgumentType.FullName + " because no mapper is registered at ArgPipelineObjectMapperProvider.CurrentMapper");
                    }
                    else
                    {
                        revivedValue = ArgPipelineObjectMapper.CurrentMapper.MapIncompatibleDirectTargets(directMappingTarget.ArgumentType, o);
                    }
                }

                directMappingTarget.RevivedValueOverride = revivedValue;
            }
            else
            {
                PowerLogger.LogLine("Attempting to shred object: " + o.ToString());
                foreach (var argument in predictedAction.Arguments.Union(effectiveDefinition.Arguments))
                {
                    bool manualOverride = false;

                    foreach (var explicitKey in preParseResult.ExplicitParameters.Keys)
                    {
                        if (argument.IsMatch(explicitKey))
                        {
                            manualOverride = true;
                            break;
                        }
                    }

                    if (preParseResult.ImplicitParameters.ContainsKey(argument.Position))
                    {
                        manualOverride = true;
                    }

                    if (manualOverride) continue;

                    var mapper = argument.Metadata.Meta<ArgPipelineExtractor>() ?? new ArgPipelineExtractor();
                    string mappedKey, mappedValue;
                    if (mapper.TryExtractObjectPropertyIntoCommandLineArgument(o, argument, out mappedKey, out mappedValue))
                    {
                        newCommandLine.Add(mappedKey);
                        newCommandLine.Add(mappedValue);
                    }
                }
            }

            return newCommandLine.ToArray();
        }
        /// <summary>
        /// A helper that detects the argument represented by the current token given a definition.  
        /// </summary>
        /// <param name="contextualAction">An action to inspect for a match if the current token does not match a global argument.  Pass null to only check global arguments.</param>
        /// <param name="currentToken">The token to inspect.  If you pass null you will get null back.</param>
        /// <param name="expectMatchingArg">This will be set to true if the current token starts with a '-' or a '/' meaning that the token was an argument indicator, even if it didn't match an argument in the definition.</param>
        /// <param name="def">The definition to inspect.  If null, the ambient definition will be used.  If there is no ambient definition and null is passed then this method throws a NullReferenceException.</param>
        /// <returns>An argument that is matched by the given token or null if there was no match</returns>
        public static CommandLineArgument FindCurrentTokenArgument(CommandLineAction contextualAction, string currentToken, out bool expectMatchingArg, CommandLineArgumentsDefinition def = null)
        {
            def = PassThroughOrTryGetAmbientDefinition(def);

            if (currentToken == null)
            {
                expectMatchingArg = false;
                return null;
            }

            string currentTokenArgumentNameValue = null;
            expectMatchingArg = false;
            if (currentToken.StartsWith("-"))
            {
                currentTokenArgumentNameValue = currentToken.Substring(1);
                expectMatchingArg = true;
            }
            else if (currentToken.StartsWith("/"))
            {
                currentTokenArgumentNameValue = currentToken.Substring(1);
                expectMatchingArg = true;
            }

            CommandLineArgument currentTokenArgument = null;
            if (currentTokenArgumentNameValue != null)
            {
                currentTokenArgument = def.Arguments.Where(arg => arg.IsMatch(currentTokenArgumentNameValue)).SingleOrDefault();

                if (currentTokenArgument == null && contextualAction != null)
                {
                    currentTokenArgument = contextualAction.Arguments.Where(arg => arg.IsMatch(currentTokenArgumentNameValue)).SingleOrDefault();
                }
            }
            return currentTokenArgument;
        }
 public ValidationEnforcementTokenHighlighter(CommandLineArgumentsDefinition definition)
 {
     this.definition = definition;
 }
 /// <summary>
 /// Finds the action that matches the given token in the given definition
 /// </summary>
 /// <param name="firstToken">the token to test.  If you pass null you will get null back.</param>
 /// <param name="def">The definition to inspect.  If null, the ambient definition will be used.  If there is no ambient definition and null is passed then this method throws a NullReferenceException.</param>
 /// <returns>the action that matches the given token in the given definition or null if no such action is found</returns>
 public static CommandLineAction FindContextualAction(string firstToken, CommandLineArgumentsDefinition def = null)
 {
     def = PassThroughOrTryGetAmbientDefinition(def);
     if(firstToken == null)
     {
         return null;
     }
     return def.FindMatchingAction(firstToken);
 }
示例#47
0
 protected override void OnObjectReceived(object o)
 {
     CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition(typeof(FilterAction));
     def.FindMatchingArgument("FilterTarget").RevivedValueOverride = o;
     Args.InvokeMain(def, CmdLineArgs.ToArray());
 }