summaryrefslogtreecommitdiff
path: root/getopt/GetOpt.cs
blob: a158073c96fbe336f278bb7dcdd62438e5a502b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace Gnu
{
	/// <summary>
	/// An implementation of the getopt standard, as used by Gnu GetOpt
	/// </summary>
	public class GetOpt
	{
		StringCollection m_params = new StringCollection();
		StringCollection m_extras = new StringCollection();
        List<Arg> m_args = new List<Arg>();

		public GetOpt(string[] CommandLineArgs, string ParametersDescription)
		{
			// Import the string array into the collection
			foreach(string s in CommandLineArgs)
			{
				m_params.Add(s);
			}

			// Parse the params description
			for(int i = 0; i < ParametersDescription.Length; i++)
			{
				Arg a = new Arg();
				a.Flag = ParametersDescription[i];
				if((ParametersDescription.Length > i + 1) && (ParametersDescription[i + 1] == ':'))
				{
					a.TakesParameter = true;
					i++;
				}

				m_args.Add(a);
			}
		}

		public Arg NextArg()
		{
			SnarfExtras();

			if(m_params.Count == 0)
				return null;			

			foreach(Arg a in m_args)
			{
				if(a.Flag == m_params[0][1] && m_params[0][0] == '-' )
				{
					Arg matched = a;
					try
					{
						if(a.TakesParameter)
						{
							matched.Parameter = m_params[1];
							m_params.RemoveAt(1);
						}
					}
					catch(Exception)
					{
					}

					m_params.RemoveAt(0);
					return matched;
				}
			}

			if(m_params[0][0] == '-')
			{
				Arg tempa = new Arg();
				tempa.Flag = m_params[0][1];
				tempa.TakesParameter = false;
				return tempa;
			}
			return null;
		}

		public StringCollection Extras
		{
            get
            {
                SnarfExtras();

                return m_extras;
            }
		}

		private void SnarfExtras()
		{
			// Parameters must start with a hyphen
			while((m_params.Count > 0) && (m_params[0][0] != '-'))
			{
				m_extras.Add(m_params[0]);
				m_params.RemoveAt(0);
			}
		}
	}
}