This is the root class used to define a program's command line arguments. You can start with an empty definition and programatically add arguments or you can start from a Type that you have defined and have the definition inferred from it.
        private List<string> FindActions(CommandLineArgumentsDefinition definition)
        {
            List<string> ret = new List<string>();

            foreach (var action in definition.Actions)
            {
                var name = action.Aliases.First();

                if (name.EndsWith(Constants.ActionArgConventionSuffix))
                {
                    name = name.Substring(0, name.Length - Constants.ActionArgConventionSuffix.Length);
                }

                if (action.IgnoreCase)
                {
                    ret.Add(name.ToLower());
                }
                else
                {
                    ret.Add(name);
                }
            }

            ret = ret.Distinct().ToList();
            return ret;
        }
 public PowerArgsMultiContextAssistProvider(CommandLineArgumentsDefinition definition)
 {
     this.Definition   = definition;
     standardProviders = new List <IContextAssistProvider>();
     standardProviders.Add(new EnumAssistant(definition));
     standardProviders.Add(new ActionAssistant(definition));
 }
        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(new FindContextualArgumentArgs()
            {
                ActionContext     = context.TargetAction,
                Definition        = definition,
                CommandLine       = new ConsoleString(innerContext.Buffer).StringValue,
                CurrentTokenIndex = innerContext.CurrentTokenIndex,
                CurrentToken      = innerContext.CurrentToken.Value,
                PreviousToken     = context.PreviousToken
            });
            return(context);
        }
Ejemplo n.º 4
0
        internal object CreateTabCompletionSource(CommandLineArgumentsDefinition definition, CommandLineArgument argument)
        {
            ITabCompletionSource ret;

            if (this.CompletionSourceType.GetInterfaces().Contains(typeof(ISmartTabCompletionSource)))
            {
                var source = Activator.CreateInstance(CompletionSourceType) as ISmartTabCompletionSource;
                return(new ArgumentAwareWrapperSmartTabCompletionSource(definition, argument, source));
            }
            else if (this.CompletionSourceType.IsSubclassOf(typeof(ArgumentAwareTabCompletionSource)))
            {
                ret = (ITabCompletionSource)Activator.CreateInstance(this.CompletionSourceType, definition, argument);
            }
            else if (this.CompletionSourceType.GetInterfaces().Contains(typeof(ITabCompletionSource)))
            {
                var toWrap = (ITabCompletionSource)Activator.CreateInstance(this.CompletionSourceType);
                ret = new ArgumentAwareWrapperTabCompletionSource(definition, argument, toWrap);
            }
            else
            {
                throw new InvalidArgDefinitionException("The type " + this.CompletionSourceType.FullName + " does not implement ITabCompletionSource or ITabCompletionSource.  The target argument was " + argument.DefaultAlias);
            }

            return(ret);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Parses the args for the given definition and then calls the Main() method defined by the type.
 /// </summary>
 /// <param name="definition">The command line definition to parse</param>
 /// <param name="args">the command line values</param>
 /// <returns></returns>
 public static ArgAction InvokeMain(CommandLineArgumentsDefinition definition, params string[] args)
 {
     return(REPL.DriveREPL <ArgAction>(definition.Metadata.Meta <TabCompletion>(), (a) =>
     {
         return Execute <ArgAction>(() =>
         {
             Args instance = new Args();
             var result = instance.ParseInternal(definition, a);
             if (result.HandledException == null)
             {
                 result.Context.RunBeforeInvoke();
                 result.Value.InvokeMainMethod();
                 result.Context.RunAfterInvoke();
             }
             return result;
         });
     }, args, () =>
     {
         return new ArgAction()
         {
             Cancelled = true,
             Definition = definition,
             Context = ArgHook.HookContext.Current,
         };
     }));
 }
Ejemplo n.º 6
0
        /// <summary>
        /// If properties on the given object contain default value attributes then this method will initalize those properties with
        /// the right defaults
        /// </summary>
        /// <param name="o">the object to initialize</param>
        public static void InitializeDefaults(object o)
        {
            if (o == null)
            {
                throw new ArgumentNullException("o cannot be null");
            }

            var def     = new CommandLineArgumentsDefinition(o.GetType());
            var context = new ArgHook.HookContext();

            context.Definition = def;
            context.Args       = o;

            foreach (var arg in def.Arguments)
            {
                context.ArgumentValue   = null;
                context.CurrentArgument = arg;
                context.RevivedProperty = null;
                if (arg.HasDefaultValue == false)
                {
                    continue;
                }

                arg.Populate(context);
            }

            def.SetPropertyValues(o);
        }
        private List <string> FindActions(CommandLineArgumentsDefinition definition)
        {
            List <string> ret = new List <string>();

            foreach (var action in definition.Actions)
            {
                var name = action.Aliases.First();

                if (name.EndsWith(Constants.ActionArgConventionSuffix))
                {
                    name = name.Substring(0, name.Length - Constants.ActionArgConventionSuffix.Length);
                }

                if (action.IgnoreCase)
                {
                    ret.Add(name.ToLower());
                }
                else
                {
                    ret.Add(name);
                }
            }

            ret = ret.Distinct().ToList();
            return(ret);
        }
        public EnumTabCompletionSource(CommandLineArgumentsDefinition definition, CommandLineArgument argument)
            : base(definition, argument)
        {
            var options = Enum.GetNames(argument.ArgumentType).Union(argument.ArgumentType.GetEnumShortcuts());

            wrappedSource = new SimpleTabCompletionSource(options);
        }
Ejemplo n.º 9
0
        private static bool IsBool(string key, CommandLineArgumentsDefinition definition, ParseResult resultContext)
        {
            var match = definition.FindMatchingArgument(key, true);

            if (match == null)
            {
                var possibleActionContext = resultContext.ImplicitParameters.ContainsKey(0) ? resultContext.ImplicitParameters[0] : null;

                if (possibleActionContext == null)
                {
                    return(false);
                }
                else
                {
                    var actionContext = definition.FindMatchingAction(possibleActionContext, true);
                    if (actionContext == null)
                    {
                        return(false);
                    }

                    match = actionContext.FindMatchingArgument(key, true);
                    if (match == null)
                    {
                        return(false);
                    }
                }
            }

            return(match.ArgumentType == typeof(bool));
        }
Ejemplo n.º 10
0
        private static IEnumerable <ITabCompletionSource> FindNewTabCompletionHooks(CommandLineArgumentsDefinition definition, bool enableFs)
        {
            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());
            if (enableFs)
            {
                completionSources.Add(new FileSystemTabCompletionSource());
            }
            return(completionSources);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generates a usage document given a template
        /// </summary>
        /// <param name="def">The object that describes your program</param>
        /// <param name="template">The template to use or null to use the default template that's built into PowerArgs</param>
        /// <param name="templateSourceLocation">The source of the template, usually a file name</param>
        /// <returns>The usage document</returns>
        public static ConsoleString GenerateUsageFromTemplate(CommandLineArgumentsDefinition def, string template = null, string templateSourceLocation = null)
        {
            bool needsContextCleanup = false;

            if (ArgHook.HookContext.Current == null)
            {
                needsContextCleanup                    = true;
                ArgHook.HookContext.Current            = new ArgHook.HookContext();
                ArgHook.HookContext.Current.Definition = def;
            }

            try
            {
                if (ArgHook.HookContext.Current.Definition == def)
                {
                    ArgHook.HookContext.Current.RunBeforePrepareUsage();
                }

                if (template == null)
                {
                    template = UsageTemplates.ConsoleTemplate;
                    templateSourceLocation = "Default console usage template";
                }
                var document = new DocumentRenderer().Render(template, def, templateSourceLocation);
                return(document);
            }
            finally
            {
                if (needsContextCleanup)
                {
                    ArgHook.HookContext.Current = null;
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generates web browser friendly usage documentation for your program and opens it using the local machine's default browser.
        /// </summary>
        /// <param name="def">The object that describes your program</param>
        /// <param name="template">The template to use or null to use the default browser friendly template that's built into PowerArgs</param>
        /// <param name="outputFileName">Where to save the output (the browser will open the file from here)</param>
        /// <param name="deleteFileAfterBrowse">True if the file should be deleted after browsing</param>
        /// <param name="waitForBrowserExit">True if you'd like this method to block until the browser is closed.  This only works for browsers that start a new process when opened with a document.</param>
        /// <returns>The usage document as a string</returns>
        public static string ShowUsageInBrowser(CommandLineArgumentsDefinition def, string template = null, string outputFileName = null, bool deleteFileAfterBrowse = true, bool waitForBrowserExit = true)
        {
            var usage = ArgUsage.GenerateUsageFromTemplate(def, template ?? UsageTemplates.BrowserTemplate);

            outputFileName = outputFileName ?? Path.GetTempFileName().ToLower().Replace(".tmp", ".html");
            Process proc = null;

            try
            {
                File.WriteAllText(outputFileName, usage.ToString());
                proc = Process.Start(outputFileName);
                if (proc != null && waitForBrowserExit)
                {
                    proc.WaitForExit();
                }
            }
            finally
            {
                if (deleteFileAfterBrowse)
                {
                    if (File.Exists(outputFileName))
                    {
                        if (waitForBrowserExit == false || proc == null)
                        {
                            Thread.Sleep(3000); // Gives the browser a few seconds to read the file before deleting it.
                        }

                        File.Delete(outputFileName);
                    }
                }
            }
            return(usage.ToString());
        }
Ejemplo n.º 13
0
 public CommandLineArgumentsDefinition MakeDefinition(CommandLineArgumentsDefinition other)
 {
     if (other.ArgumentScaffoldType == null)
     {
         throw new NotSupportedException("Your command line arguments definition was not created from a scaffold type. You created it manually using the default constructor of CommandLineArgumentsDefinition().  If you want to use ArgPipeline you must implement ICommandLineDefinitionFactory and pass your custom type to the ArgPipelineAttribute's CommandLineDefinitionFactory property");
     }
     return(new CommandLineArgumentsDefinition(other.ArgumentScaffoldType));
 }
 public CommandLineArgumentsDefinition MakeDefinition(CommandLineArgumentsDefinition other)
 {
     if (other.ArgumentScaffoldType == null)
     {
         throw new NotSupportedException("Your command line arguments definition was not created from a scaffold type. You created it manually using the default constructor of CommandLineArgumentsDefinition().");
     }
     return(new CommandLineArgumentsDefinition(other.ArgumentScaffoldType));
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Parses the given arguments using a command line arguments definition. The values will be populated within
 /// the definition.
 /// </summary>
 /// <param name="definition">The definition that defines a set of command line arguments and/or actions.</param>
 /// <param name="args">The command line arguments to parse</param>
 public static ArgAction Parse(CommandLineArgumentsDefinition definition, params string[] args)
 {
     ArgAction ret = Execute(() =>
     {
         return ParseAction(definition, args);
     });
     return ret;
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Parses the given arguments using a command line arguments definition.
        /// </summary>
        /// <param name="definition">The definition that defines a set of command line arguments and/or actions.</param>
        /// <param name="args">The command line arguments to parse</param>
        /// <returns></returns>
        public static ArgAction ParseAction(CommandLineArgumentsDefinition definition, params string[] args)
        {
            ArgAction ret = Execute(() =>
            {
                Args instance = new Args();
                return(instance.ParseInternal(definition, args));
            });

            return(ret);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Generates a usage document given a template
        /// </summary>
        /// <param name="def">The object that describes your program</param>
        /// <param name="template">The template to use or null to use the default template that's built into PowerArgs</param>
        /// <param name="templateSourceLocation">The source of the template, usually a file name</param>
        /// <returns>The usage document</returns>
        public static ConsoleString GenerateUsageFromTemplate(CommandLineArgumentsDefinition def, string template = null, string templateSourceLocation = null)
        {
            if (template == null)
            {
                template = Resources.DefaultConsoleUsageTemplate;
                templateSourceLocation = "Default console usage template";
            }
            var document = new DocumentRenderer().Render(template, def, templateSourceLocation);

            return(document);
        }
Ejemplo n.º 19
0
        public void TestPhotoAlbumManagerConsoleUsage()
        {
            ConsoleProvider.Current.BufferWidth = 160;
            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");

            Helpers.AssertAreEqualWithDiffInfo(Resources.PhotoAlbumManagerExpectedBrowserUsage.Replace("\r\n","\n"), browserUsage);
            Helpers.AssertAreEqualWithDiffInfo(Resources.PhotoAlbumManagerExpectedConsoleUsage.Replace("\r\n", "\n"), consoleUsage);
        }
Ejemplo n.º 20
0
        public static ConsoleString GetUsage(Type usageTemplateProviderType, CommandLineArgumentsDefinition definition)
        {
            if (usageTemplateProviderType.GetInterfaces().Contains(typeof(IUsageTemplateProvider)) == false)
            {
                throw new InvalidArgDefinitionException("The UsageTemplateProviderType "+usageTemplateProviderType.FullName+" does not implement " + typeof(IUsageTemplateProvider).Name);
            }

            var provider = Activator.CreateInstance(usageTemplateProviderType) as IUsageTemplateProvider;
            string template = provider.GetTemplate();
            var usage = ArgUsage.GenerateUsageFromTemplate(definition, template);
            return usage;
        }
        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);
        }
        public static ConsoleString GetUsage(Type usageTemplateProviderType, CommandLineArgumentsDefinition definition)
        {
            if (usageTemplateProviderType.GetInterfaces().Contains(typeof(IUsageTemplateProvider)) == false)
            {
                throw new InvalidArgDefinitionException("The UsageTemplateProviderType " + usageTemplateProviderType.FullName + " does not implement " + typeof(IUsageTemplateProvider).Name);
            }

            var    provider = ObjectFactory.CreateInstance(usageTemplateProviderType) as IUsageTemplateProvider;
            string template = provider.GetTemplate();
            var    usage    = ArgUsage.GenerateUsageFromTemplate(definition, template);

            return(usage);
        }
Ejemplo n.º 23
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]);
        }
Ejemplo n.º 24
0
 internal IContextAssistProvider GetContextAssistProvider(CommandLineArgumentsDefinition definition)
 {
     if (_cachedProvider == null)
     {
         try
         {
             ContextAssistProviderType.TryCreate <IContextAssistProvider>(new object[] { definition }, out _cachedProvider);
         }
         catch (InvalidArgDefinitionException)
         {
             ContextAssistProviderType.TryCreate <IContextAssistProvider>(out _cachedProvider);
         }
     }
     return(_cachedProvider);
 }
Ejemplo n.º 25
0
 internal IContextAssistProvider GetContextAssistProvider(CommandLineArgumentsDefinition definition)
 {
     if (_cachedProvider == null)
     {
         try
         {
             ContextAssistProviderType.TryCreate<IContextAssistProvider>(new object[] { definition }, out _cachedProvider);
         }
         catch (InvalidArgDefinitionException)
         {
             ContextAssistProviderType.TryCreate<IContextAssistProvider>(out _cachedProvider);
         }
     }
     return _cachedProvider;
 }
Ejemplo n.º 26
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));
     }
 }
Ejemplo n.º 27
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");
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Parses the given arguments using a command line arguments definition.  Then, invokes the action
 /// that was specified.
 /// </summary>
 /// <param name="definition">The definition that defines a set of command line arguments and actions.</param>
 /// <param name="args"></param>
 /// <returns>The raw result of the parse with metadata about the specified action.  The action is executed before returning.</returns>
 public static ArgAction InvokeAction(CommandLineArgumentsDefinition definition, params string[] args)
 {
     return(REPL.DriveREPL <ArgAction>(definition.Hooks.Where(h => h is TabCompletion).Select(h => h as TabCompletion).SingleOrDefault(), (a) =>
     {
         return Execute <ArgAction>(() =>
         {
             Args instance = new Args();
             var result = instance.ParseInternal(definition, a);
             if (result.HandledException == null)
             {
                 result.Invoke();
             }
             return result;
         });
     }, args));
 }
Ejemplo n.º 29
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>
        /// <param name="enableFileSystemTabCompletion">if set to false will disable file system tab completion</param>
        public PowerArgsRichCommandLineReader(CommandLineArgumentsDefinition definition, List <ConsoleString> history, bool enableFileSystemTabCompletion = true)
        {
            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, enableFileSystemTabCompletion);
            InitHighlighters();
        }
        /// <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();
        }
Ejemplo n.º 31
0
        private List <string> FindGlobalArguments(CommandLineArgumentsDefinition definition)
        {
            List <string> ret = new List <string>();

            var argIndicator = "-";

            foreach (var argument in definition.Arguments.Where(a => a.Metadata.Where(m => m is OmitFromUsageDocs).None()))
            {
                if (argument.ArgumentType == typeof(SecureStringArgument))
                {
                    continue;
                }

                ret.Add(argIndicator + argument.Aliases.First());
            }

            return(ret);
        }
        private List <string> FindGlobalArguments(CommandLineArgumentsDefinition definition)
        {
            List <string> ret = new List <string>();

            var argIndicator = "-";

            foreach (var argument in definition.Arguments)
            {
                if (argument.ArgumentType == typeof(SecureStringArgument))
                {
                    continue;
                }

                ret.Add(argIndicator + argument.Aliases.First());
            }

            return(ret);
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Parses the given arguments using a command line arguments definition.  Then, invokes the action
 /// that was specified.  
 /// </summary>
 /// <param name="definition">The definition that defines a set of command line arguments and actions.</param>
 /// <param name="args"></param>
 /// <returns>The raw result of the parse with metadata about the specified action.  The action is executed before returning.</returns>
 public static ArgAction InvokeAction(CommandLineArgumentsDefinition definition, params string[] args)
 {
     ArgAction ret = Execute(() =>
     {
         return REPL.DriveREPL<ArgAction>(definition.Hooks.Where(h => h is TabCompletion).Select(h => h as TabCompletion).SingleOrDefault(), (a) =>
         {
         var result = ParseAction(definition, a);
             if (result.HandledException == null)
             {
                 result.Context.RunBeforeInvoke();
                 result.Invoke();
                 result.Context.RunAfterInvoke();
             }
         return result;
     }
     , args);
     });
     return ret;
 }
Ejemplo n.º 34
0
        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);
        }
        private Dictionary<CommandLineAction, SimpleTabCompletionSource> FindActionSpecificSources(CommandLineArgumentsDefinition definition)
        {
            var ret = new Dictionary<CommandLineAction, SimpleTabCompletionSource>();

            var argIndicator = "-";

            foreach (var action in definition.Actions)
            {
                List<string> arguments = new List<string>();
                foreach (var argument in action.Arguments)
                {

                    if (argument.ArgumentType == typeof(SecureStringArgument))
                    {
                        continue;
                    }

                    arguments.Add(argIndicator + argument.Aliases.First());
                }
                ret.Add(action, new SimpleTabCompletionSource(arguments) { MinCharsBeforeCyclingBegins = 0 });
            }

            return ret;
        }
Ejemplo n.º 36
0
        internal object CreateTabCompletionSource(CommandLineArgumentsDefinition definition, CommandLineArgument argument)
        {
            ITabCompletionSource ret;
            if(this.CompletionSourceType.GetInterfaces().Contains(typeof(ISmartTabCompletionSource)))
            {
                var source = Activator.CreateInstance(CompletionSourceType) as ISmartTabCompletionSource;
                return new ArgumentAwareWrapperSmartTabCompletionSource(definition, argument, source);
            }
            else if (this.CompletionSourceType.IsSubclassOf(typeof(ArgumentAwareTabCompletionSource)))
            {
                ret = (ITabCompletionSource)Activator.CreateInstance(this.CompletionSourceType, definition, argument);
            }
            else if (this.CompletionSourceType.GetInterfaces().Contains(typeof(ITabCompletionSource)))
            {
                var toWrap = (ITabCompletionSource)Activator.CreateInstance(this.CompletionSourceType);
                ret = new ArgumentAwareWrapperTabCompletionSource(definition, argument, toWrap);
            }
            else
            {
                throw new InvalidArgDefinitionException("The type " + this.CompletionSourceType.FullName + " does not implement ITabCompletionSource or ITabCompletionSource.  The target argument was " + argument.DefaultAlias);
            }

            return ret;
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Finds the first CommandLineArgument that matches the given key.
 /// </summary>
 /// <param name="key">The key as if it was typed in on the command line.  This can also be an alias. </param>
 /// <param name="throwIfMoreThanOneMatch">If set to true then this method will throw and InvalidArgDeginitionException if more than 1 match is found</param>
 /// <returns>The first argument that matches the key.</returns>
 public CommandLineArgument FindMatchingArgument(string key, bool throwIfMoreThanOneMatch = false)
 {
     return(CommandLineArgumentsDefinition.FindMatchingArgument(key, throwIfMoreThanOneMatch, this.Arguments));
 }
        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;
        }
Ejemplo n.º 39
0
        public void TestSimpleModelWithSimpleValidator()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var definitionString = definition.ToString(); // Make sure it doesn't throw

            var argument = new CommandLineArgument(typeof(int), "somenumber");
            definition.Arguments.Add(argument);
            argument.Metadata.Add(new ArgRequired());

            try
            {
                Args.Parse(definition, new string[] { });
                Assert.Fail("An exception should have been thrown");
            }
            catch (MissingArgException ex)
            {
                Assert.IsTrue(ex.Message.Contains("somenumber"));
            }
        }
Ejemplo n.º 40
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);
        }
Ejemplo n.º 41
0
        public void TestModeledActionREPL()
        {
            int invokeCount = 0;

            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            definition.Metadata.Add(new TabCompletion() { REPL = true, Indicator = "$" });

            var action = new CommandLineAction((d) =>
            {
                Assert.AreEqual("go", d.SpecifiedAction.DefaultAlias);
                if (invokeCount == 0)
                {
                    Assert.AreEqual("Hawaii", d.SpecifiedAction.Arguments[0].RevivedValue);
                }
                else if (invokeCount == 1)
                {
                    Assert.AreEqual("Mexico", d.SpecifiedAction.Arguments[0].RevivedValue);
                }
                invokeCount++;
            });

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

            definition.Actions.Add(action);

            var destination = new CommandLineArgument(typeof(string), "destination");
            destination.Metadata.Add(new ArgRequired());
            destination.Description = "The place to go to";

            action.Arguments.Add(destination);

            var provider = TestConsoleProvider.SimulateConsoleInput("g\t -dest\t Hawaii{enter}go -dest\t Mexico{enter}quit");
            Args.InvokeAction(definition, "$");
            Assert.AreEqual(2, invokeCount);
        }
Ejemplo n.º 42
0
        private ArgAction ParseInternal(CommandLineArgumentsDefinition definition, string[] input)
        {
            // TODO - Validation should be consistently done against the definition, not against the raw type
            if (definition.ArgumentScaffoldType != null)
            {
                ValidateArgScaffold(definition.ArgumentScaffoldType);
            }

            var context = ArgHook.HookContext.Current;

            context.Definition = definition;
            _ambientDefinition = definition;

            definition.Validate(context);

            if (definition.ArgumentScaffoldType != null)
            {
                context.Args = Activator.CreateInstance(definition.ArgumentScaffoldType);
            }
            context.CmdLineArgs = input;

            context.RunBeforeParse();
            context.ParserData = ArgParser.Parse(definition, context.CmdLineArgs);

            var actionToken = context.CmdLineArgs.FirstOrDefault();
            var actionQuery = context.Definition.Actions.Where(a => a.IsMatch(actionToken));

            if (actionQuery.Count() == 1)
            {
                context.SpecifiedAction = actionQuery.First();
            }
            else if (actionQuery.Count() > 1)
            {
                throw new InvalidArgDefinitionException("There are multiple actions that match argument '" + actionToken + "'");
            }

            context.RunBeforePopulateProperties();
            CommandLineArgument.PopulateArguments(context.Definition.Arguments, context);
            context.Definition.SetPropertyValues(context.Args);

            object actionArgs = null;

            object[] actionParameters = null;

            if (context.SpecifiedAction == null && context.Definition.Actions.Count > 0)
            {
                if (context.CmdLineArgs.FirstOrDefault() == null)
                {
                    throw new MissingArgException("No action was specified");
                }
                else
                {
                    throw new UnknownActionArgException(string.Format("Unknown action: '{0}'", context.CmdLineArgs.FirstOrDefault()));
                }
            }
            else if (context.SpecifiedAction != null)
            {
                PropertyInfo actionProp = null;
                if (context.Definition.ArgumentScaffoldType != null)
                {
                    actionProp = ArgAction.GetActionProperty(context.Definition.ArgumentScaffoldType);
                }

                if (actionProp != null)
                {
                    actionProp.SetValue(context.Args, context.SpecifiedAction.Aliases.First(), null);
                }

                context.ParserData.ImplicitParameters.Remove(0);
                CommandLineArgument.PopulateArguments(context.SpecifiedAction.Arguments, context);
            }

            context.RunAfterPopulateProperties();

            if (context.SpecifiedAction != null)
            {
                actionArgs = context.SpecifiedAction.PopulateArguments(context.Args, ref actionParameters);
            }

            if (context.Definition.Metadata.HasMeta <AllowUnexpectedArgs>() == false)
            {
                if (context.ParserData.ImplicitParameters.Count > 0)
                {
                    throw new UnexpectedArgException("Unexpected unnamed argument: " + context.ParserData.ImplicitParameters.First().Value);
                }

                if (context.ParserData.ExplicitParameters.Count > 0)
                {
                    throw new UnexpectedArgException("Unexpected named argument: " + context.ParserData.ExplicitParameters.First().Key);
                }
            }
            else
            {
                definition.UnexpectedExplicitArguments = context.ParserData.ExplicitParameters;
                definition.UnexpectedImplicitArguments = context.ParserData.ImplicitParameters;
            }


            if (definition.ArgumentScaffoldType != null)
            {
                if (AmbientArgs.ContainsKey(definition.ArgumentScaffoldType))
                {
                    AmbientArgs[definition.ArgumentScaffoldType] = context.Args;
                }
                else
                {
                    AmbientArgs.Add(definition.ArgumentScaffoldType, context.Args);
                }
            }

            PropertyInfo actionArgsPropertyInfo = null;

            if (context.SpecifiedAction != null)
            {
                if (context.SpecifiedAction.Source is PropertyInfo)
                {
                    actionArgsPropertyInfo = context.SpecifiedAction.Source as PropertyInfo;
                }
                else if (context.SpecifiedAction.Source is MethodInfo)
                {
                    actionArgsPropertyInfo = new ArgActionMethodVirtualProperty(context.SpecifiedAction.Source as MethodInfo);
                }
            }

            return(new ArgAction()
            {
                Value = context.Args,
                ActionArgs = actionArgs,
                ActionParameters = actionParameters,
                ActionArgsProperty = actionArgsPropertyInfo,
                ActionArgsMethod = context.SpecifiedAction != null ? context.SpecifiedAction.ActionMethod : null,
                Definition = context.Definition,
                Context = context,
            });
        }
Ejemplo n.º 43
0
 public void TestNullablesInTableExpression()
 {
     var def = new CommandLineArgumentsDefinition(typeof(NullableArgs));
     var usage = ArgUsage.GenerateUsageFromTemplate(def, PowerArgs.Resources.DefaultConsoleUsageTemplate, "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"));
 }
Ejemplo n.º 44
0
        private static T DoStandardExceptionHandling<T>(ArgException ex, ArgHook.HookContext context, CommandLineArgumentsDefinition definition) where T : class
        {
            Console.WriteLine(ex.Message);

            ArgUsage.GetStyledUsage(definition, definition.ExceptionBehavior.ExeName, new ArgUsageOptions
            {
                ShowPosition = definition.ExceptionBehavior.ShowPositionColumn,
                ShowType = definition.ExceptionBehavior.ShowTypeColumn,
                ShowPossibleValues = definition.ExceptionBehavior.ShowPossibleValues,
            }).Write();

            return CreateEmptyResult<T>(context, ex);
        }
 public ArgumentAwareTabCompletionSource(CommandLineArgumentsDefinition definition)
 {
     this.definition = definition;
 }
Ejemplo n.º 46
0
        internal static ParseResult Parse(CommandLineArgumentsDefinition Definition, string[] commandLineArgs)
        {
            var args = commandLineArgs;

            ParseResult result = new ParseResult();

            int argumentPosition = 0;
            for (int i = 0; i < args.Length; i++)
            {
                var token = args[i];

                if (i == 0 && Definition.Actions.Count > 0 && Definition.FindMatchingAction(token) != null)
                {
                    result.ImplicitParameters.Add(0, token);
                    argumentPosition++;
                }
                else if (token.StartsWith("/"))
                {
                    var param = ParseSlashExplicitOption(token);
                    if (result.ExplicitParameters.ContainsKey(param.Key)) throw new DuplicateArgException("Argument specified more than once: " + param.Key);
                    result.ExplicitParameters.Add(param.Key, param.Value);
                    argumentPosition = -1;
                }
                else if (token.StartsWith("-"))
                {
                    string key = token.Substring(1);

                    if (key.Length == 0) throw new ArgException("Missing argument value after '-'");

                    string value;

                    // Handles long form syntax --argName=argValue.
                    if (key.StartsWith("-") && key.Contains("="))
                    {
                        var index = key.IndexOf("=");
                        value = key.Substring(index + 1);
                        key = key.Substring(0, index);
                    }
                    else
                    {
                        if (i == args.Length - 1)
                        {
                            value = "";
                        }
                        else if (IsBool(key, Definition, result))
                        {
                            var next = args[i + 1].ToLower();

                            if (next == "true" || next == "false" || next == "0" || next == "1")
                            {
                                i++;
                                value = next;
                            }
                            else
                            {
                                value = "true";
                            }
                        }
                        else
                        {
                            i++;
                            value = args[i];
                        }
                    }

                    if (result.ExplicitParameters.ContainsKey(key))
                    {
                        throw new DuplicateArgException("Argument specified more than once: " + key);
                    }

                    result.ExplicitParameters.Add(key, value);
                    argumentPosition = -1;
                }
                else
                {
                    if (argumentPosition < 0) throw new UnexpectedArgException("Unexpected argument: " + token);
                    result.ImplicitParameters.Add(argumentPosition, token);
                    argumentPosition++;
                }
            }

            return result;
        }
Ejemplo n.º 47
0
        private static bool IsBool(string key, CommandLineArgumentsDefinition definition, ParseResult resultContext)
        {
            var match = definition.FindMatchingArgument(key, true);
            if (match == null)
            {
                var possibleActionContext = resultContext.ImplicitParameters.ContainsKey(0) ? resultContext.ImplicitParameters[0] : null;

                if (possibleActionContext == null)
                {
                    return false;
                }
                else
                {
                    var actionContext = definition.FindMatchingAction(possibleActionContext, true);
                    if (actionContext == null)
                    {
                        return false;
                    }

                    match = actionContext.FindMatchingArgument(key, true);
                    if (match == null)
                    {
                        return false;
                    }
                }

            }

            return match.ArgumentType == typeof(bool);
        }
Ejemplo n.º 48
0
        // todo - This class was originally very dumb.  It parsed the command line arguments without knowledge of the definition.
        //        However, several special syntaxes that folks were expecting would only be possible if the parser had pretty deep
        //        knowledge of the program structure.  So now this class takes in the definition and inspects it to handle these
        //        special cases.  I should finish the job and handle positional elements this way too.  This would remove the need
        //        for the 'ImplicitParameters' collection in the ParseResult.  On that other hand that would be a breaking change just
        //        for the sake of cleanup. I need to think it over.
        //
        //        Another potential item would be to refactor the parse method here.  It's a mess, but it's a working, heavily tested mess
        //        so cleaning it up will mean accepting some risk.
        internal static ParseResult Parse(CommandLineArgumentsDefinition Definition, string[] commandLineArgs)
        {
            var args = commandLineArgs;

            ParseResult result = new ParseResult();

            int argumentPosition = 0;
            for (int i = 0; i < args.Length; i++)
            {
                var token = args[i];

                // this block handles action parameters that must always be the first token
                if (i == 0 && Definition.Actions.Count > 0 && Definition.FindMatchingAction(token) != null)
                {
                    result.ImplicitParameters.Add(0, token);
                    argumentPosition++;
                }
                else if (token.StartsWith("/"))
                {
                    var param = ParseSlashExplicitOption(token);
                    if (result.ExplicitParameters.ContainsKey(param.Key)) throw new DuplicateArgException("Argument specified more than once: " + param.Key);
                    result.ExplicitParameters.Add(param.Key, param.Value);
                    argumentPosition = -1;
                }
                else if (token.StartsWith("-"))
                {
                    string key = token.Substring(1);

                    if (key.Length == 0) throw new ArgException("Missing argument value after '-'");

                    string value;

                    // Handles long form syntax --argName=argValue.
                    if (key.StartsWith("-") && key.Contains("="))
                    {
                        var index = key.IndexOf("=");
                        value = key.Substring(index + 1);
                        key = key.Substring(0, index);
                    }
                    else
                    {
                        if (i == args.Length - 1)
                        {
                            value = "";
                        }
                        else if (IsBool(key, Definition, result))
                        {
                            var next = args[i + 1].ToLower();

                            if (next == "true" || next == "false" || next == "0" || next == "1")
                            {
                                i++;
                                value = next;
                            }
                            else
                            {
                                value = "true";
                            }
                        }
                        else
                        {
                            i++;
                            value = args[i];
                        }
                    }

                    if (result.ExplicitParameters.ContainsKey(key))
                    {
                        throw new DuplicateArgException("Argument specified more than once: " + key);
                    }

                    result.ExplicitParameters.Add(key, value);

                    if(IsArrayOrList(key, Definition, result))
                    {
                        while((i+1) < args.Length)
                        {
                            var nextToken = args[i+1];

                            if(nextToken.StartsWith("/") || nextToken.StartsWith("-"))
                            {
                                break;
                            }
                            else
                            {
                                result.AddAdditionalParameter(key, nextToken);
                                i++;
                            }

                        }
                    }

                    argumentPosition = -1;
                }
                else
                {
                    if (argumentPosition < 0) throw new UnexpectedArgException("Unexpected argument: " + token);

                    var possibleActionContext = result.ImplicitParameters.ContainsKey(0) ? result.ImplicitParameters[0] : null;
                    var potentialListArgument = Definition.FindArgumentByPosition(argumentPosition, possibleActionContext);

                    if (potentialListArgument != null)
                    {
                        bool isArrayOrList = potentialListArgument.ArgumentType.IsArray || potentialListArgument.ArgumentType.GetInterfaces().Contains(typeof(IList));

                        if (isArrayOrList)
                        {
                            // this block does special handling to allow for space separated collections for positioned parameters

                            result.ExplicitParameters.Add(potentialListArgument.DefaultAlias, token);
                            argumentPosition = -1; // no more positional arguments are allowed after this
                            while ((i + 1) < args.Length)
                            {
                                var nextToken = args[i + 1];

                                if (nextToken.StartsWith("/") || nextToken.StartsWith("-"))
                                {
                                    break;
                                }
                                else
                                {
                                    result.AddAdditionalParameter(potentialListArgument.DefaultAlias, nextToken);
                                    i++;
                                }

                            }
                        }
                        else
                        {
                            // not an array or list parameter so add to the implicit parameter collection
                            result.ImplicitParameters.Add(argumentPosition, token);
                            argumentPosition++;
                        }
                    }
                    else
                    {
                        // not an array or list parameter so add to the implicit parameter collection
                        result.ImplicitParameters.Add(argumentPosition, token);
                        argumentPosition++;
                    }
                }
            }

            return result;
        }
 /// <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);
 }
 /// <summary>
 /// Creates a definition from a base using the provided Func
 /// </summary>
 /// <param name="other">the base definition</param>
 /// <returns>a definition</returns>
 public CommandLineArgumentsDefinition MakeDefinition(CommandLineArgumentsDefinition other)
 {
     return fromOtherImpl(other);
 }
        /// <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;
        }
Ejemplo n.º 52
0
 public void TestNullableIsEnum()
 {
     var def = new CommandLineArgumentsDefinition(typeof(NullableArgs));
     Assert.IsTrue(def.FindMatchingArgument("OptionalDayOfWeek").IsEnum);
 }
        /// <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 CommandLineArgumentsDefinition MakeDefinition(CommandLineArgumentsDefinition other)
 {
     if (other.ArgumentScaffoldType == null) throw new NotSupportedException("Your command line arguments definition was not created from a scaffold type. You created it manually using the default constructor of CommandLineArgumentsDefinition().  If you want to use ArgPipeline you must implement ICommandLineDefinitionFactory and pass your custom type to the ArgPipelineAttribute's CommandLineDefinitionFactory property");
     return new CommandLineArgumentsDefinition(other.ArgumentScaffoldType);
 }
        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;
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Parses the given arguments using a command line arguments definition. The values will be populated within
 /// the definition.
 /// </summary>
 /// <param name="definition">The definition that defines a set of command line arguments and/or actions.</param>
 /// <param name="args">The command line arguments to parse</param>
 public static ArgAction Parse(CommandLineArgumentsDefinition definition, params string[] args)
 {
     return(ParseAction(definition, args));
 }
Ejemplo n.º 57
0
        private static T DoStandardExceptionHandling <T>(ArgException ex, ArgHook.HookContext context, CommandLineArgumentsDefinition definition) where T : class
        {
            Console.WriteLine(ex.Message);

            if (definition.ExceptionBehavior.UsageTemplateFile != null)
            {
                var template = File.ReadAllText(definition.ExceptionBehavior.UsageTemplateFile);
                ArgUsage.GenerateUsageFromTemplate(definition, template).Write();
            }
            else
            {
                UsageTemplateProvider.GetUsage(definition.ExceptionBehavior.UsageTemplateProviderType, definition).Write();
            }

            return(CreateEmptyResult <T>(context, ex));
        }
 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");
     }
 }
Ejemplo n.º 59
0
 public EnumTabCompletionSource(CommandLineArgumentsDefinition definition)
     : base(definition)
 {
     manager = new CycledTabCompletionManager();
 }
 public ValidationEnforcementTokenHighlighter(CommandLineArgumentsDefinition definition)
 {
     this.definition = definition;
 }