Esempio n. 1
0
        private void GetCommandLineConfiguration(string[] args)
        {
            var docopt = new Docopt();

            IDictionary <string, ValueObject> res = docopt.Apply(Usage, args, help: true, exit: true);

            _ocdmModelExportPath = res["--modelExport"] == null ? _ocdmModelExportPath : res["--modelExport"].ToString();

            _readerName = res["--reader"] == null ? _readerName : res["--reader"].ToString();

            _writerName = res["--writer"] == null ? _writerName : res["--writer"].ToString();

            if (res["--outputPath"] == null)
            {
                // do nothing, rely on default
            }
            else if (res["--outputPath"].ToString() == String.Empty)
            {
                _outputPath = @".\";  // current working directory
            }
            else
            {
                _outputPath = res["--outputPath"].ToString();
            }

            _metadataPath = res["<inputFile>"] == null ? _metadataPath : res["<inputFile>"].ToString();
        }
 public void Test_issue_40_help()
 {
     var message = "";
     var d = new Docopt();
     d.PrintExit += (s, e) => message = e.Message;
     d.Apply("usage: prog --help-commands | --help", "--help");
     StringAssert.StartsWith("usage", message);
 }
Esempio n. 3
0
        public void Test_issue_40_help()
        {
            var message = "";
            var d       = new Docopt();

            d.PrintExit += (s, e) => message = e.Message;
            d.Apply("usage: prog --help-commands | --help", "--help");
            StringAssert.StartsWith("usage", message);
        }
Esempio n. 4
0
        /// <summary>
        /// Run a command.
        /// </summary>
        /// <param name="backend">The server backend environment</param>
        /// <param name="commandname">The command name</param>
        /// <param name="args">The tokenized arguments for the command</param>
        /// <param name="session">The user ID of the caller</param>
        /// <param name="stdin">The standard input stream</param>
        /// <param name="stdout">The standard output stream</param>
        /// <returns>Whether the command was found</returns>
        public bool RunCommand(Backend backend, string commandname, string[] args, string session, StreamReader stdin, StreamWriter stdout)
        {
            if (backend == null)
            {
                throw new ArgumentNullException(nameof(backend));
            }
            if (string.IsNullOrWhiteSpace(commandname))
            {
                return(false);
            }
            if (args == null)
            {
                args = new string[] { }
            }
            ;
            var cmd = _commands.FirstOrDefault(x => x.Name == commandname);

            if (cmd == null)
            {
                return(false);
            }
            string man = GetManpage(commandname);
            var    ctx = new ConsoleContext(stdout, stdin);

            //Validate and run the command.
            try
            {
                Dictionary <string, object> argss = new Dictionary <string, object>();
                var docopt = new Docopt();
                var argsv  = docopt.Apply(man, args, version: commandname, exit: false);
                foreach (var arg in argsv)
                {
                    if (arg.Value != null)
                    {
                        argss.Add(arg.Key, arg.Value.Value);
                    }
                    else
                    {
                        argss.Add(arg.Key, null);
                    }
                }
                cmd.Run(backend, ctx, session, argss);
            }
            catch (Exception ex)
            {
                ctx.SetColors(Plex.Objects.ConsoleColor.Black, Plex.Objects.ConsoleColor.Red);
                ctx.WriteLine($"{commandname}: Error");
                ctx.SetColors(Plex.Objects.ConsoleColor.Black, Plex.Objects.ConsoleColor.Gray);
                ctx.WriteLine(ex.StackTrace);
                ctx.WriteLine(ex.Message);
            }
            return(true);
        }
Esempio n. 5
0
        // ^ important to keep at least two spaces between a) the end of the option spec and b) its description text

        internal static void Execute(ICollection <string> args, ILogger logger)
        {
            try
            {
                var docopt  = new Docopt();
                var parseOk = true;
                docopt.PrintExit += (_, exitArgs) =>
                {
                    logger.Error(exitArgs.Message);
                    parseOk = false;
                };

                var parsed = docopt.Apply(k_Usage, args, version: $"{k_Name} {k_Version}", exit: true);
                if (!parseOk)
                {
                    return;
                }

                if (parsed["format"].IsTrue)
                {
                    var paths = parsed["PATH"].AsList.Cast <ValueObject>();

                    var context = new FormatContext {
                        Logger = logger
                    };
                    if (parsed["--dry-run"].IsTrue)
                    {
                        context.Options |= FormatOptions.DryRun;
                    }

                    var packageRoot = ((string)parsed["--package-root"]?.Value)?.ToNPath();
                    if (packageRoot != null)
                    {
                        try
                        {
                            context.ThisPackageRoot = packageRoot;
                        }
                        catch (Exception x)
                        {
                            logger.Error($"Invalid package root; {x.Message}");
                            return;
                        }
                    }

                    Formatter.Process(paths.Select(p => p.ToString().ToNPath()), context);
                }
            }
            catch (Exception x)
            {
                logger.Error($"Fatal: unexpected {x.GetType().Name}: {x.Message}\n{x.StackTrace}");
            }
        }
Esempio n. 6
0
        public static IDictionary <string, ValueObject> Apply(this Docopt docopt,
                                                              string doc, string cmdLine,
                                                              bool help         = true,
                                                              object version    = null,
                                                              bool optionsFirst = false,
                                                              bool exit         = false)
        {
            // A very naive way to split a command line into individual
            // arguments but good enough for the test cases so far:
            var argv = cmdLine.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

            return(docopt.Apply(doc, argv, help, version, optionsFirst, exit));
        }
Esempio n. 7
0
        public static int Main(string[] args)
        {
            // call scanner and process all files with selected command
            var cmd_map = new Dictionary <string, Type>
            {
                {
                    "validate",
                    typeof(Validator)
                },
                {
                    "info",
                    typeof(Info)
                },
                {
                    "elfinfo",
                    typeof(ElfInfo)
                },
                {
                    "relocate",
                    typeof(Relocate)
                },
                {
                    "signatures",
                    typeof(SignatureGenerator)
                }
            };

            var docopt  = new Docopt();
            var options = docopt.Apply(Program.options, args);
            var cmd     = options["<command>"].Value.ToString();

            if (!cmd_map.ContainsKey(cmd))
            {
                Console.WriteLine("INVALID COMMAND:", cmd);
                Console.WriteLine("valid commands are:");
                foreach (var a in cmd_map)
                {
                    Console.WriteLine("  ", a);
                }
                return(1);
            }
            var cmd_cls = cmd_map[cmd];
            // execute command
            var cmdInst = (HunkCommand)Activator.CreateInstance(cmd_cls, options);

            cmdInst.Output = System.Console.Out;
            var res = cmdInst.run();

            return(res ? 0 : 1);
        }
Esempio n. 8
0
        public void Display_help()
        {
            var message   = "";
            var errorCode = 0;
            var d         = new Docopt();

            d.PrintExit += (s, e) =>
            {
                message   = e.Message;
                errorCode = e.ErrorCode;
            };
            d.Apply(DOC, "--help");
            StringAssert.StartsWith("Usage", message);
            Assert.AreEqual(0, errorCode);
        }
Esempio n. 9
0
        public void Should_exit_error_code_1()
        {
            var message   = "";
            var errorCode = 0;
            var d         = new Docopt();

            d.PrintExit += (s, e) =>
            {
                message   = e.Message;
                errorCode = e.ErrorCode;
            };
            d.Apply(DOC, "--fake", exit: true);
            StringAssert.StartsWith("Usage", message);
            Assert.AreEqual(1, errorCode, "Should exit with error code 1 when exit=true and invalid args provided");
        }
Esempio n. 10
0
        public MainArgs(
            ICollection <string> argv,
            bool help         = true,
            object?version    = null,
            bool optionsFirst = false)
        {
            var docOpt = new Docopt();

            docOpt.PrintExit += (sender, args) =>
            {
                Failed        = true;
                FailMessage   = args.Message;
                FailErrorCode = args.ErrorCode;
            };
            _args = docOpt.Apply(Usage, argv, help, version, optionsFirst, true);
        }
Esempio n. 11
0
        public static Configuration Parse(string [] clargs)
        {
            var docopt = new Docopt();
            var args   = docopt.Apply(
                doc: USAGE,
                argv: clargs,
                help: true,
                exit: false
                );

            return(new Configuration {
                Docopt = docopt,
                Repl = args ["repl"]?.IsTrue ?? false,
                Help = args ["help"]?.IsTrue ?? false,
                Check = args ["check"]?.IsTrue ?? false,
                Version = args ["version"]?.IsTrue ?? false,
                UsePowerlines = args ["--powerlines"]?.IsTrue ?? false,
                SuppressCache = args ["--no-cache"]?.IsTrue ?? false,
                SuppressOptimizer = args ["--no-optimize"]?.IsTrue ?? false,
                File = args ["<FILE>"]?.Value as string,
            });
        }
Esempio n. 12
0
        public int Execute(string [] args)
        {
            TextReader input   = Console.In;
            TextWriter output  = Console.Out;
            var        sc      = new ServiceContainer();
            var        rekoCfg = RekoConfigurationService.Load();

            sc.AddService <IConfigurationService>(rekoCfg);

            var docopt = new Docopt();
            IDictionary <string, ValueObject> options;

            try {
                options = docopt.Apply(usage, args);
            } catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return(1);
            }
            var arch = rekoCfg.GetArchitecture(options["-a"].ToString());

            if (arch == null)
            {
                Console.WriteLine(
                    "c2xml: unknown architecture '{0}'. Check the c2xml config file for supported architectures.",
                    options["-a"]);
                return(-1);
            }
            var envElem = rekoCfg.GetEnvironment(options["-e"].ToString());

            if (envElem == null)
            {
                Console.WriteLine(
                    "c2xml: unknown environment '{0}'. Check the c2xml config file for supported architectures.",
                    options["-e"]);
                return(-1);
            }

            var platform = envElem.Load(sc, arch);

            try
            {
                input = new StreamReader(options["<inputfile>"].ToString());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("c2xml: unable to open file {0} for reading. {1}", options["<inputfile>"], ex.Message);
                return(1);
            }

            if (options.ContainsKey("<outputfile>") &&
                options["<outputfile>"] != null)
            {
                try
                {
                    output = new StreamWriter(options["<outputfile>"].ToString());
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("c2xml: unable to open file {0} for writing. {1}", options["<outputfile>"], ex.Message);
                    return(1);
                }
            }
            var xWriter = new XmlTextWriter(output)
            {
                Formatting = Formatting.Indented
            };

            XmlConverter c = new XmlConverter(input, xWriter, platform);

            c.Convert();
            output.Flush();
            return(0);
        }
Esempio n. 13
0
        public int Execute(string [] args)
        {
            TextReader input;
            Stream     output = Console.OpenStandardOutput();
            var        sc     = new ServiceContainer();

            sc.AddService(typeof(IPluginLoaderService), new PluginLoaderService());
            var rekoCfg = RekoConfigurationService.Load(sc);

            sc.AddService <IConfigurationService>(rekoCfg);

            var docopt = new Docopt();
            IDictionary <string, ValueObject> options;

            try {
                options = docopt.Apply(usage, args);
            } catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return(1);
            }

            var arch = rekoCfg.GetArchitecture(options["-a"].ToString());

            if (arch == null)
            {
                Console.WriteLine(
                    "c2xml: unknown architecture '{0}'. Check the c2xml config file for supported architectures.",
                    options["-a"]);
                return(-1);
            }

            var envElem = rekoCfg.GetEnvironment(options["-e"].ToString());

            if (envElem == null)
            {
                Console.WriteLine(
                    "c2xml: unknown environment '{0}'. Check the c2xml config file for supported architectures.",
                    options["-e"]);
                return(-1);
            }
            var platform = envElem.Load(sc, arch);

            try
            {
                input = new StreamReader(options["<inputfile>"].ToString());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("c2xml: unable to open file {0} for reading. {1}", options["<inputfile>"], ex.Message);
                return(1);
            }

            if (options.ContainsKey("<outputfile>") && options["<outputfile>"] != null)
            {
                try
                {
                    output = new FileStream(options["<outputfile>"].ToString(), FileMode.Create, FileAccess.Write);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("c2xml: unable to open file {0} for writing. {1}", options["<outputfile>"], ex.Message);
                    return(1);
                }
            }
            string dialect = null;

            if (options.TryGetValue("-d", out var optDialect) && optDialect != null)
            {
                dialect = (string)optDialect.Value;
            }
            var xWriter = new XmlTextWriter(output, new UTF8Encoding(false))
            {
                Formatting = Formatting.Indented
            };

            XmlConverter c = new XmlConverter(input, xWriter, platform, dialect);

            c.Convert();
            output.Flush();
            output.Close();
            return(0);
        }
Esempio n. 14
0
 public void Display_help()
 {
     var message = "";
     var errorCode = 0;
     var d = new Docopt();
     d.PrintExit += (s, e) =>
     {
         message = e.Message;
         errorCode = e.ErrorCode;
     };
     d.Apply(DOC, "--help");
     StringAssert.StartsWith("Usage", message);
     Assert.AreEqual(0, errorCode);
 }
Esempio n. 15
0
 public void Should_exit_error_code_1()
 {
     var message = "";
     var errorCode = 0;
     var d = new Docopt();
     d.PrintExit += (s, e) =>
         {
             message = e.Message;
             errorCode = e.ErrorCode;
         };
     d.Apply(DOC, "--fake", exit:true);
     StringAssert.StartsWith("Usage", message);
     Assert.AreEqual(1, errorCode);
 }
Esempio n. 16
0
 public void Should_exit_error_code_1()
 {
     var message = "";
     var errorCode = 0;
     var d = new Docopt();
     d.PrintExit += (s, e) =>
         {
             message = e.Message;
             errorCode = e.ErrorCode;
         };
     d.Apply(DOC, "--fake", exit:true);
     StringAssert.StartsWith("Usage", message);
     Assert.AreEqual(1, errorCode, "Should exit with error code 1 when exit=true and invalid args provided");
 }