aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tools/mass test client/Parsing.cs
blob: 371c3cd9aa91d609ce8a5f293a61dc33c5d42dc7 (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
using System;
using System.Collections.Generic;
using System.Text;

namespace libsecondlife.TestClient {
    class Parsing {
        public static string[] ParseArguments(string str) {
            List<string> list = new List<string>();
            string current = "";
            string trimmed = null;
            bool withinQuote = false;
            bool escaped = false;
            foreach (char c in str) {
                if (c == '"') {
                    if (escaped) {
                        current += '"';
                        escaped = false;
                    } else {
                        current += '"';
                        withinQuote = !withinQuote;
                    }
                } else if (c == ' ' || c == '\t') {
                    if (escaped || withinQuote) {
                        current += c;
                        escaped = false;
                    } else {
                        trimmed = current.Trim();
                        if (trimmed.StartsWith("\"") && trimmed.EndsWith("\"")) {
                            trimmed = trimmed.Remove(0, 1);
                            trimmed = trimmed.Remove(trimmed.Length - 1);
                            trimmed = trimmed.Trim();
                        }
                        if (trimmed.Length > 0)
                            list.Add(trimmed);
                        current = "";
                    }
                } else if (c == '\\') {
                    if (escaped) {
                        current += '\\';
                        escaped = false;
                    } else {
                        escaped = true;
                    }
                } else {
                    if (escaped)
                        throw new FormatException(c.ToString() + " is not an escapable character.");
                    current += c;
                }
            }
            trimmed = current.Trim();
            if (trimmed.StartsWith("\"") && trimmed.EndsWith("\"")) {
                trimmed = trimmed.Remove(0, 1);
                trimmed = trimmed.Remove(trimmed.Length - 1);
                trimmed = trimmed.Trim();
            }
            if (trimmed.Length > 0)
                list.Add(trimmed);
            return list.ToArray();
        }
    }
}