This object represents the definition of a long option in the C# port of GNU getopt. An array of LongOpt objects is passed to the Getopt object to define the list of valid long options for a given parsing session. Refer to the Getopt documentation for details on the format of long options.
Esempio n. 1
0
        public static string digest(LongOpt[] longOpts)
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < longOpts.Length; i++)
            {
                LongOpt longOpt = longOpts[i];
                stringBuilder.Append((char)longOpt.Val);
                if (longOpt.HasArg == Argument.Optional)
                {
                    stringBuilder.Append("::");
                }
                if (longOpt.HasArg == Argument.Required)
                {
                    stringBuilder.Append(":");
                }
            }
            return(stringBuilder.ToString());
        }
Esempio n. 2
0
        /// <summary>
        /// Construct a Getopt instance with given input data that is capable
        /// of parsing long options and short options.  Contrary to what you
        /// might think, the flag <paramref name="longOnly"/> does not
        /// determine whether or not we scan for only long arguments. Instead,
        /// a value of true here allows long arguments to start with a
        /// '<c>-</c>' instead of "<c>--</c>" unless there is a conflict with
        /// a short option name.
        /// </summary>
        /// <param name="progname">
        /// The name to display as the program name when printing errors
        /// </param>
        /// <param name="argv">
        /// The string array passed as the command ilne to the program.
        /// </param>
        /// <param name="optstring">
        /// A string containing a description of the valid short args for this
        /// program.
        /// </param>
        /// <param name="longOptions">
        /// An array of <see cref="LongOpt"/> objects that describes the valid
        /// long args for this program.
        /// </param>
        /// <param name="longOnly">
        /// true if long options that do not conflict with short options can
        /// start with a '<c>-</c>' as well as "<c>--</c>".
        /// </param>
        public Getopt(string progname, string[] argv, string optstring,
            LongOpt[] longOptions, bool longOnly)
        {
            if (optstring.Length == 0)
                optstring = " ";

            // This function is essentially _getopt_initialize from GNU getopt
            this.progname = progname;
            this.argv = argv;
            this.optstring = optstring;
            this.longOptions = longOptions;
            this.longOnly = longOnly;

            // Check for application setting "Gnu.PosixlyCorrect" to determine
            // whether to strictly follow the POSIX standard. This replaces the
            // "POSIXLY_CORRECT" environment variable in the C version
            try
            {
                if((bool) new AppSettingsReader().GetValue(
                    "Gnu.PosixlyCorrect", typeof(bool)))
                {
                    this.posixlyCorrect = true;
                    this.cultureInfo = new CultureInfo("en-US");
                }
                else
                    this.posixlyCorrect = false;
            }
            catch(Exception)
            {
                this.posixlyCorrect = false;
            }

            // Determine how to handle the ordering of options and non-options
            if (optstring[0] == '-')
            {
                this.ordering = Order.ReturnInOrder;
                if (optstring.Length > 1)
                    this.optstring = optstring.Substring(1);
            }
            else if (optstring[0] == '+')
            {
                this.ordering = Order.RequireOrder;
                if (optstring.Length > 1)
                    this.optstring = optstring.Substring(1);
            }
            else if (this.posixlyCorrect)
            {
                this.ordering = Order.RequireOrder;
            }
            else
            {
                this.ordering = Order.Permute; // The normal default case
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Construct a Getopt instance with given input data that is capable
        /// of parsing long options as well as short.
        /// </summary>
        /// <param name="progname">
        /// The name to display as the program name when printing errors.
        /// </param>
        /// <param name="argv">
        /// The string array passed as the command ilne to the program.
        /// </param>
        /// <param name="optstring">
        /// A string containing a description of the valid short args for this
        /// program.
        /// </param>
        /// <param name="longOptions">
        /// An array of <see cref="LongOpt"/> objects that describes the valid
        /// long args for this program.
        /// </param>
        public Getopt(string progname, string[] argv, string optstring,
            LongOpt[] longOptions)
            : this(progname, argv, optstring,
			longOptions, false)
        {
        }
Esempio n. 4
0
        private int checkLongOption()
        {
            LongOpt longOpt = null;

            this.longoptHandled = true;
            bool flag  = false;
            bool flag2 = false;

            this.longind = -1;
            int num = this.nextchar.IndexOf("=");

            if (num == -1)
            {
                num = this.nextchar.Length;
            }
            for (int i = 0; i < this.longOptions.Length; i++)
            {
                if (this.longOptions[i].Name.StartsWith(this.nextchar.Substring(0, num)))
                {
                    if (this.longOptions[i].Name.Equals(this.nextchar.Substring(0, num)))
                    {
                        longOpt      = this.longOptions[i];
                        this.longind = i;
                        flag2        = true;
                        break;
                    }
                    if (longOpt == null)
                    {
                        longOpt      = this.longOptions[i];
                        this.longind = i;
                    }
                    else
                    {
                        flag = true;
                    }
                }
            }
            if (flag && !flag2)
            {
                if (this.opterr)
                {
                    object[] arg = new object[]
                    {
                        this.progname,
                        this.argv[this.optind]
                    };
                    Console.Error.WriteLine("{0}: option ''{1}'' is ambiguous", arg);
                }
                this.nextchar = "";
                this.optopt   = 0;
                this.optind++;
                return(63);
            }
            if (longOpt == null)
            {
                this.longoptHandled = false;
                return(0);
            }
            this.optind++;
            if (num != this.nextchar.Length)
            {
                if (longOpt.HasArg == Argument.No)
                {
                    if (this.opterr)
                    {
                        if (this.argv[this.optind - 1].StartsWith("--"))
                        {
                            object[] arg2 = new object[]
                            {
                                this.progname,
                                longOpt.Name
                            };
                            Console.Error.WriteLine("{0}: option ''--{1}'' doesn't allow an argument", arg2);
                        }
                        else
                        {
                            object[] arg3 = new object[]
                            {
                                this.progname,
                                this.argv[this.optind - 1][0],
                                longOpt.Name
                            };
                            Console.Error.WriteLine("{0}: option ''{1}{2}'' doesn't allow an argument", arg3);
                        }
                    }
                    this.nextchar = "";
                    this.optopt   = longOpt.Val;
                    return(63);
                }
                if (this.nextchar.Substring(num).Length > 1)
                {
                    this.optarg = this.nextchar.Substring(num + 1);
                }
                else
                {
                    this.optarg = "";
                }
            }
            else
            {
                if (longOpt.HasArg == Argument.Required)
                {
                    if (this.optind < this.argv.Length)
                    {
                        this.optarg = this.argv[this.optind];
                        this.optind++;
                    }
                    else
                    {
                        if (this.opterr)
                        {
                            object[] arg4 = new object[]
                            {
                                this.progname,
                                this.argv[this.optind - 1]
                            };
                            Console.Error.WriteLine("{0}: option ''{1}'' requires an argument", arg4);
                        }
                        this.nextchar = "";
                        this.optopt   = longOpt.Val;
                        if (this.optstring[0] == ':')
                        {
                            return(58);
                        }
                        return(63);
                    }
                }
            }
            this.nextchar = "";
            if (longOpt.Flag != null)
            {
                longOpt.Flag.Length = 0;
                longOpt.Flag.Append(longOpt.Val);
                return(0);
            }
            return(longOpt.Val);
        }
Esempio n. 5
0
        public static void Main(string[] args)
        {
            int c;
            MainClass main = new MainClass();

            LongOpt[] longopts = new LongOpt[] {
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("verbose", Argument.No, null, 'v'),
                new LongOpt("conf", Argument.Required, null, 'c'),
                new LongOpt("tag", Argument.No, null, 2),
                new LongOpt("parse", Argument.No, null, 3),
                new LongOpt("knows", Argument.No, null, 4),
                new LongOpt("spell", Argument.No, null, 'z')
            };
            Getopt g = new Getopt("DataTemple", args, "hvszc:I:P:O:T:i:p:t:", longopts);

            bool acted = false;
            List<PatternTemplateSource> dicta = new List<PatternTemplateSource>();

            string input = null;
            string output = null;
            string template = null;
            while ((c = g.getopt()) != -1)
                switch (c) {
                case 1: {
                    Console.WriteLine("I see you have return in order set and that " +
                        "a non-option argv element was just found " +
                        "with the value '" + g.Optarg + "'");
                    break;
                }
                case 2: {
                    acted = true;
                    if (main.tagger == null) {
                        Console.WriteLine("Use the -c option before --tag or --parse");
                        continue;
                    }
                    List<KeyValuePair<string, string>> tokens = main.tagger.TagString(input);
                    foreach (KeyValuePair<string, string> token in tokens)
                        Console.Write(token.Key + "/" + token.Value + " ");
                    Console.WriteLine("");
                    break;
                }
                case 3: {
                    acted = true;
                    if (main.parser == null) {
                        Console.WriteLine("Use the -c option before --tag or --parse");
                        continue;
                    }
                    Console.WriteLine(main.parser.Parse(input));
                    break;
                }
                case 4: {
                    DictumMaker maker = new DictumMaker(main.basectx, "testing");
                    dicta.Add(maker.MakeDictum("%sentence %noun %is %adj", "@know %noun @HasProperty %adj @SubjectTense %is"));
                    dicta.Add(maker.MakeDictum("%sentence %event %attime", "@know %event @AtTime %attime"));
                    dicta.Add(maker.MakeDictum("%sentence %event %inall", "@know %event @InLocation %inall"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %inall", "@know %noun @InLocation %inall"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %is a %noun", "@know %noun1 @IsA %noun2 @SubjectTense %is"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %will %verb1 * to %verb2 *", "@know %verbx1 @Subject %noun @SubjectTense %will %verb1 @ActiveObjects *1 @know %verbx2 @Subject %noun @SubjectTense %verb2 @ActiveObjects *2 @know %verbx2 @Condition %verbx1"));
                    break;
                }
                case 'v': {
                    main.verbose++;
                    break;
                }
                case 'h': {
                    Console.WriteLine("The documentation is currently at \n" + DOCS_URL);
                    break;
                }
                case 's': {
                    main.serialmode = true;
                    break;
                }
                case 'z': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -z");
                        continue;
                    }

                    SpellingBeeWordComparer wordComparer = new SpellingBeeWordComparer(main.plugenv.GetConfigDirectory("datadirectory"));
                    main.basectx.Map["$Compare"] = wordComparer;
                    main.tryToRescueMatch = new CorrectSpellingsRescueMatch(main.tryToRescueMatch, wordComparer, main.parser, 100);
                    break;
                }
                case 'c': {
                    main.Initialize(g.Optarg);
                    break;
                }
                case 'I': {
                    input = g.Optarg;
                    break;
                }
                case 'i': {
                    StreamReader file = new StreamReader(g.Optarg);
                    input = file.ReadToEnd();
                    break;
                }
                case 'P': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -P");
                        continue;
                    }
                    Context context = Interpreter.ParseCommands(main.basectx, g.Optarg);
                    IContinuation cont = new Evaluator(100.0, ArgumentMode.ManyArguments, main, new NopCallable(), true);
                    cont.Continue(context, new NopCallable());

                    main.RunToEnd();
                    break;
                }
                case 'p': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -p");
                        continue;
                    }
                    foreach (string line in File.ReadAllLines(g.Optarg)) {
                        if (line.Trim().Length == 0 || line.Trim().StartsWith("#"))
                            continue;
                        Context context = Interpreter.ParseCommands(main.basectx, line);
                        IContinuation cont = new Evaluator(100.0, ArgumentMode.ManyArguments, main, new NopCallable(), true);
                        cont.Continue(context, new NopCallable());

                        main.RunToEnd();
                    }
                    break;
                }
                case 'T': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -T");
                        continue;
                    }
                    template = g.Optarg;
                    if (template != null && output != null) {
                        DictumMaker maker = new DictumMaker(main.basectx, "testing");
                        dicta.Add(maker.MakeDictum(template, output));

                        template = output = null;
                    }
                    break;
                }
                case 'O': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -O");
                        continue;
                    }

                    output = g.Optarg;
                    if (template != null && output != null) {
                        DictumMaker maker = new DictumMaker(main.basectx, "testing");
                        dicta.Add(maker.MakeDictum(template, output));

                        template = output = null;
                    }
                    break;
                }
                case 't': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -t");
                        continue;
                    }

                    bool nextTemplate = true;
                    foreach (string line in File.ReadAllLines(g.Optarg)) {
                        string trimline = line.Trim();
                        if (trimline.Length == 0 || trimline.StartsWith("#"))
                            continue;

                        if (nextTemplate) {
                            template = trimline;
                            nextTemplate = false;
                        } else {
                            output = trimline;
                            DictumMaker maker = new DictumMaker(main.basectx, "testing");
                            dicta.Add(maker.MakeDictum(template, output));
                            nextTemplate = true;
                        }
                    }

                    template = output = null;
                    break;
                }
            }

            if (dicta.Count != 0)
                main.DoMatching(dicta, input);
            else if (!acted)
                Console.WriteLine("Nothing to do.  Add -tag, -parse, or -t or -T and -O");
        }
Esempio n. 6
0
 /// <summary>
 /// Produce an optstring suitable for the Getopt constructor
 /// given an array of LongOpts suitable for the Getopt
 /// constructor
 /// </summary>
 public static string digest(LongOpt[] longOpts)
 {
     StringBuilder sb = new StringBuilder();
       foreach (LongOpt o in longOpts) {
     sb.Append((char)o.Val);
     if (o.HasArg == Argument.Optional) sb.Append("::");
     if (o.HasArg == Argument.Required) sb.Append(":");
       }
       return sb.ToString();
 }
        static void Main(string[] args)
        {
            int c;
            LongOpt[] longopts = new LongOpt[4];
            string param0placeholder = "@Name";
            string param1placeholder = "@BinArray";
            string dsn = System.Environment.GetEnvironmentVariable("DSN");
            string sql = System.Environment.GetEnvironmentVariable("SQL");
            string file = null;
            string name = null;
            byte[] fileArray;

            longopts[0] = new LongOpt("help", Argument.No, null, '?');
            longopts[1] = new LongOpt("dsn", Argument.Required, null, 'd');
            longopts[1] = new LongOpt("sql", Argument.Required, null, 's');
            longopts[2] = new LongOpt("file", Argument.Required, null, 'f');
            longopts[3] = new LongOpt("name", Argument.Required, null, 'n');

            Getopt g = new Getopt(System.AppDomain.CurrentDomain.FriendlyName, args, "?d:s:f:n:", longopts);

            while ((c = g.getopt()) != -1) {
                switch (c) {
                    case '?':
                        Help();
                        return;
                    case 'd':
                        dsn = g.Optarg;
                        break;
                    case 's':
                        sql = g.Optarg;
                        break;
                    case 'f':
                        file = g.Optarg;
                        break;
                    case 'n':
                        name = g.Optarg;
                        break;
                }
            }

            if ((dsn == null) || (sql == null) || (file == null)) {
                Help();
                return;
            }
            if (name == null) {
                name = Path.GetFileNameWithoutExtension(file);
            }

            try {
                fileArray = GetFileArray(file);
            } catch {
                Help();
                return;
            }

            sql = String.Format(sql, param0placeholder, param1placeholder);

            try {
                Save(dsn, sql, fileArray, name, param0placeholder, param1placeholder);
            } catch {
                Help();
                Debug(dsn, sql, file, fileArray);
            }
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            #if true	// Getopt sample
            Getopt g = new Getopt("testprog", args, "ab:c::d");

            int c;
            string arg;
            while ((c = g.getopt()) != -1)
            {
                switch(c)
                {
                    case 'a':
                    case 'd':
                        Console.WriteLine("You picked " + (char)c );
                        break;

                    case 'b':
                    case 'c':
                        arg = g.Optarg;
                        Console.WriteLine("You picked " + (char)c +
                            " with an argument of " +
                            ((arg != null) ? arg : "null") );
                        break;

                    case '?':
                        break; // getopt() already printed an error

                    default:
                        Console.WriteLine("getopt() returned " + c);
                        break;
                }
            }

            #else		// Getopt/LongOpt docu sample
            int c;
            String arg;
            LongOpt[] longopts = new LongOpt[3];

            StringBuilder sb = new StringBuilder();
            longopts[0] = new LongOpt("help", Argument.No, null, 'h');
            longopts[1] = new LongOpt("outputdir", Argument.Required, sb, 'o');
            longopts[2] = new LongOpt("maximum", Argument.Optional, null, 2);

            Getopt g = new Getopt("testprog", args, "-:bc::d:hW;", longopts);
            g.Opterr = false; // We'll do our own error handling

            while ((c = g.getopt()) != -1)
                switch (c)
                {
                    case 0:
                        arg = g.Optarg;
                        Console.WriteLine("Got long option with value '" +
                            (char)int.Parse(sb.ToString())
                            + "' with argument " +
                            ((arg != null) ? arg : "null"));
                        break;

                    case 1:
                        Console.WriteLine("I see you have return in order set and that " +
                            "a non-option argv element was just found " +
                            "with the value '" + g.Optarg + "'");
                        break;

                    case 2:
                        arg = g.Optarg;
                        Console.WriteLine("I know this, but pretend I didn't");
                        Console.WriteLine("We picked option " +
                            longopts[g.Longind].Name +
                            " with value " +
                            ((arg != null) ? arg : "null"));
                        break;

                    case 'b':
                        Console.WriteLine("You picked plain old option " + (char)c);
                        break;

                    case 'c':
                    case 'd':
                        arg = g.Optarg;
                        Console.WriteLine("You picked option '" + (char)c +
                            "' with argument " +
                            ((arg != null) ? arg : "null"));
                        break;

                    case 'h':
                        Console.WriteLine("I see you asked for help");
                        break;

                    case 'W':
                        Console.WriteLine("Hmmm. You tried a -W with an incorrect long " +
                            "option name");
                        break;

                    case ':':
                        Console.WriteLine("Doh! You need an argument for option " +
                            (char)g.Optopt);
                        break;

                    case '?':
                        Console.WriteLine("The option '" + (char)g.Optopt +
                            "' is not valid");
                        break;

                    default:
                        Console.WriteLine("getopt() returned " + c);
                        break;
                }

            for (int i = g.Optind; i < args.Length ; i++)
                Console.WriteLine("Non option argv element: " + args[i] + "\n");
            #endif
        }