Example #1
0
		public List<string> Parse (IEnumerable<string> arguments)
		{
			if (arguments == null)
				throw new ArgumentNullException (nameof(arguments));
			OptionContext c = CreateOptionContext ();
			c.OptionIndex = -1;
			bool process = true;
			List<string> unprocessed = new List<string> ();
			Option def = Contains ("<>") ? this ["<>"] : null;
			ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
			foreach (string argument in ae) {
				++c.OptionIndex;
				if (argument == "--") {
					process = false;
					continue;
				}
				if (!process) {
					Unprocessed (unprocessed, def, c, argument);
					continue;
				}
				if (AddSource (ae, argument))
					continue;
				if (!Parse (argument, c))
					Unprocessed (unprocessed, def, c, argument);
			}
			if (c.Option != null)
				c.Option.Invoke (c);
			return unprocessed;
		}
        public void ParseArgumentsArray()
        {
            Argument[] arguments = new Argument[]
            {
                new Argument("check", bool.TrueString, "/check"),
                new Argument("uncheck", bool.FalseString, "/-uncheck"),
                new Argument("named", "value", "/named:value"),
                new Argument(string.Empty, "unnamed", "unnamed"),
                new Argument("named", "quoted value\"\"", "/named:quoted value\"\""),
                new Argument(string.Empty, "quoted value\"\"", "quoted value\"\""),
            };

            foreach (IEnumerable <Argument> permutation in arguments.Permutations())
            {
                ArgumentEnumerator enumerator = new ArgumentEnumerator(permutation.Select(p => p.Representation).ToArray());

                foreach (Argument argument in permutation)
                {
                    Assert.IsTrue(enumerator.MoveNext());
                    Assert.AreEqual(enumerator.CurrentName, argument.Name);
                    Assert.AreEqual(enumerator.CurrentValue, argument.Value);
                }

                Assert.IsFalse(enumerator.MoveNext());
            }
        }
        public void GetEnumeratorFromNewEnumerator()
        {
            string[]           arguments   = new string[] { "/first", "/second" };
            ArgumentEnumerator enumerator1 = new ArgumentEnumerator(arguments);
            ArgumentEnumerator enumerator2 = enumerator1.GetEnumerator();

            Assert.AreEqual(enumerator1, enumerator2);
        }
Example #4
0
 public override void AssignProperty<TTarget>(ArgumentEnumerator enumerator, TTarget target, Dictionary<string, PropertyDescriptor> properties, PropertyDescriptor property, string argument)
 {
     string name;
     if ((name = CleanArgument(enumerator.Peek())) != null && !properties.ContainsKey(name) && enumerator.MoveNext())
         property.SetValue(target, (string)enumerator.Current);
     else
         RaiseError(Errors.MissingArgumentAfter, argument); // error because there are no more arguments
 }
        public void GetEnumeratorFromEmptyEnumerator()
        {
            ArgumentEnumerator enumerator1 = ArgumentEnumerator.Empty;
            ArgumentEnumerator enumerator2 = enumerator1.GetEnumerator();
            ArgumentEnumerator enumerator3 = enumerator1.GetEnumerator();

            Assert.AreEqual(enumerator1, enumerator3);
            Assert.AreEqual(enumerator2, enumerator3);
        }
Example #6
0
		bool AddSource (ArgumentEnumerator ae, string argument)
		{
			foreach (ArgumentSource source in sources) {
				IEnumerable<string> replacement;
				if (!source.GetArguments (argument, out replacement))
					continue;
				ae.Add (replacement);
				return true;
			}
			return false;
		}
        public void GetEnumeratorFromSecondThread()
        {
            string[]           arguments   = new string[] { "/first", "/second" };
            ArgumentEnumerator enumerator1 = new ArgumentEnumerator(arguments);
            ArgumentEnumerator enumerator2 = null;

            Thread thread = new Thread(() => enumerator2 = enumerator1.GetEnumerator());

            thread.Start();
            thread.Join();

            Assert.AreNotEqual(enumerator1, enumerator2);
        }
Example #8
0
 private bool AddSource(ArgumentEnumerator ae, string argument)
 {
     foreach (ArgumentSource source in Sources)
     {
         if (!source.GetArguments(argument, out IEnumerable <string> replacement))
         {
             continue;
         }
         ae.Add(replacement);
         return(true);
     }
     return(false);
 }
        public void ContinueFromCurrent()
        {
            string[]           arguments   = new string[] { "/first", "/second" };
            ArgumentEnumerator enumerator1 = new ArgumentEnumerator(arguments);

            Assert.IsTrue(enumerator1.MoveNext());
            Assert.IsTrue(enumerator1.MoveNext());

            ArgumentEnumerator enumerator2 = enumerator1.ContinueFromCurrent();

            Assert.IsTrue(enumerator2.MoveNext());
            Assert.AreEqual(enumerator1.CurrentName, "second");
            Assert.AreEqual(enumerator1.CurrentName, enumerator2.CurrentName);
            Assert.AreEqual(enumerator1.CurrentValue, enumerator2.CurrentValue);
            Assert.IsFalse(enumerator2.MoveNext());
        }
Example #10
0
        private static IEnumerable <Expression> _createArgumentExpressions(IEnumerable <object> constantArgument,
                                                                           ArgumentEnumerator argumentEnumerator,
                                                                           List <ParameterExpression> parameters,
                                                                           IEnumerable <Type> expectedArguments)
        {
            var calculatedExpressions = argumentEnumerator(parameters);

            var readyArgs = constantArgument
                            .Select(constant => Expression.Constant(constant))
                            .Concat(calculatedExpressions);

            return(expectedArguments.ZipThen(readyArgs,
                                             (type, arg) => arg.EnsureConvert(type),
                                             type => Expression.Constant(type.DefaultValue(), type))
                   .ToList());
        }
Example #11
0
        public override void AssignProperty <TTarget>(ArgumentEnumerator enumerator, TTarget target, Dictionary <string, PropertyDescriptor> properties, PropertyDescriptor property, string argument)
        {
            var    followingArguments = new List <string>();
            string name;

            while ((name = CleanArgument(enumerator.Peek())) != null && !properties.ContainsKey(name) && enumerator.MoveNext())
            {
                followingArguments.Add((string)enumerator.Current);
            }

            if (followingArguments.Count > 0)
            {
                property.SetValue(target, followingArguments.ToArray());
            }
            else
            {
                RaiseError(Errors.MissingArgumentAfter, argument); // error because there are no more arguments
            }
        }
Example #12
0
        public List <string> Parse(IEnumerable <string> arguments)
        {
            if (arguments == null)
            {
                throw new ArgumentNullException(nameof(arguments));
            }
            var c = CreateArgumentContext();

            c.ArgumentIndex = -1;
            var process     = true;
            var unprocessed = new List <string>();
            var def         = Contains("<>") ? this["<>"] : null;
            var ae          = new ArgumentEnumerator(arguments);

            foreach (var argument in ae)
            {
                ++c.ArgumentIndex;
                if (argument == "--")
                {
                    process = false;
                    continue;
                }
                if (!process)
                {
                    Unprocessed(unprocessed, def, c, argument);
                    continue;
                }
                if (AddSource(ae, argument))
                {
                    continue;
                }
                if (!Parse(argument, c))
                {
                    Unprocessed(unprocessed, def, c, argument);
                }
            }
            c.Argument?.Invoke(c);
            return(unprocessed);
        }
Example #13
0
        private static DelegateType _compileTo <DelegateType>(MethodBase mb,
                                                              IEnumerable <object> constants        = null,
                                                              ArgumentEnumerator argumentEnumerator = null)
        {
            constants          = constants ?? Enumerable.Empty <object>();
            argumentEnumerator = argumentEnumerator ?? ArgumentEnumerators.Default;

            var signature  = Signature.Of <DelegateType>();
            var parameters = _createParameterExpressions(signature.ParameterTypes);

            var expectedArgumentTypes = _getMethodExpectedArgumentTypes(mb);
            var callArguments         = _createArgumentExpressions(constants, argumentEnumerator, parameters, expectedArgumentTypes);

            Expression call = null;

            if (mb is MethodInfo mi)
            {
                if (mi.IsStatic)
                {
                    call = Expression.Call(mi, callArguments);
                }
                else
                {
                    call = Expression.Call(callArguments.First(), mi, callArguments.Skip(1));
                }
            }
            else if (mb is ConstructorInfo ci)
            {
                call = Expression.New(ci, callArguments);
            }

            call = call.EnsureConvert(signature.ReturnType);
            return(Expression
                   .Lambda <DelegateType>(call, parameters)
                   .Compile());
        }
Example #14
0
 public static DelegateType CompileTo <DelegateType>(this MethodBase mb, IEnumerable <object> constants, ArgumentEnumerator argumentEnumerator)
 {
     return(_compileTo <DelegateType>(mb,
                                      constants ?? Enumerable.Empty <object>(),
                                      argumentEnumerator ?? ArgumentEnumerators.Default));
 }
Example #15
0
 public abstract void AssignProperty <TTarget>(ArgumentEnumerator enumerator, TTarget target, Dictionary <string, PropertyDescriptor> properties, PropertyDescriptor property, string argument);
Example #16
0
        static void Main(string[] args)
        {
            // Set the default settings.
            string outputDir = "Services";
            var flags = GeneratorFlags.CompileLibrary;

            if (args.Length == 0) // If no argument is specified, display the usage.
            {
                args = new[] { "--help" };
            }

            // Run the application.
            try
            {
                // Parse arguments.
                string type = null;
                string source = null;
                var enumerator = new ArgumentEnumerator(args);
                while (enumerator.MoveNext())
                {
                    string arg = enumerator.Current.ToLower();

                    if (enumerator.IsParameter)
                    {
                        switch (arg)
                        {
                            case "--help":
                            case "-h":
                                Console.WriteLine("SYNTAX:  ServiceGenerator.exe [<arguments>] <Type> <Source>");
                                Console.WriteLine(" Types can be:");
                                Console.WriteLine("   'repository' -- Generate a whole discovery repository");
                                Console.WriteLine("   'url'        -- Generate a service of an uri");
                                Console.WriteLine("   'service'    -- Generate a named google service");
                                Console.WriteLine(" Source is:");
                                Console.WriteLine("   URI (http:// .. or file:/// ..) for 'repository'/'url'");
                                Console.WriteLine("   serviceName:version for 'service'");
                                Console.WriteLine(" Optional arguments:");
                                Console.WriteLine("   --help, -h           Displays this help screen");
                                Console.WriteLine("   --no-compile, -nc    Will not generate a .dll");
                                Console.WriteLine("   --google             Will add a Google prefix to the service");
                                Console.WriteLine("   --output, -o <dir>   Changes the output directory");
                                return;

                            case "--no-compile":
                            case "-nc":
                                flags &= ~GeneratorFlags.CompileLibrary;
                                break;

                            case "--google":
                                flags |= GeneratorFlags.GoogleService;
                                break;

                            case "--output":
                            case "-o":
                                enumerator.MoveNext();
                                outputDir = enumerator.GetParameterValue("--output");
                                break;

                            default:
                                throw new ArgumentException("Unknown argument: " + arg);
                        }
                    }
                    else
                    {
                        if (type == null)
                        {
                            type = enumerator.GetMandatory("type").ToLower();
                        }
                        else if (source == null)
                        {
                            source = enumerator.Current;
                        }
                        else
                        {
                            Console.Error.WriteLine("Unexpected argument: "+enumerator.Current);
                        }
                    }
                }

                type.ThrowIfNullOrEmpty("type");

                // Create the generator, and run it.
                Generator generator = new Generator(flags) { OutputDir = outputDir};
                switch (type)
                {
                    case "repository":
                        var apis = (source == null)
                                       ? DiscoveryRepository.RetrieveGoogleDiscovery()
                                       : DiscoveryRepository.RetrieveDiscovery(new Uri(source));
                        generator.GenerateServices(apis);
                        break;

                    case "url":
                        source.ThrowIfNull("source");
                        generator.GenerateService(new Uri(source));
                        break;

                    case "service":
                        source.ThrowIfNull("source");
                        var api =
                            (from a in DiscoveryRepository.RetrieveGoogleDiscovery()
                             where a.Id == source
                             select a).SingleOrDefault();

                        if (api == null)
                        {
                            throw new ArgumentException("The api '" + source + "' was not found in the repository.");
                        }

                        generator.GenerateService(api);
                        break;

                    default:
                        throw new ArgumentException("Unknown type: " + type);
                }
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("ERROR: " + exception.Message);
                Console.Error.WriteLine(exception.StackTrace);
                Environment.Exit(1);
            }
        }
Example #17
0
 public abstract void Execute(ArgumentEnumerator args);
Example #18
0
 public override void AssignProperty <TTarget>(ArgumentEnumerator enumerator, TTarget target, Dictionary <string, PropertyDescriptor> properties, PropertyDescriptor property, string argument)
 {
     property.SetValue(target, true);
 }
Example #19
0
 public static DelegateType CompileTo <DelegateType>(this MethodBase mb, ArgumentEnumerator argumentEnumerator)
 {
     return(_compileTo <DelegateType>(mb, argumentEnumerator: argumentEnumerator));
 }
 public override void Execute(ArgumentEnumerator args);