This repository was archived by the owner on Apr 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathArgParse.java
More file actions
83 lines (71 loc) · 2.76 KB
/
ArgParse.java
File metadata and controls
83 lines (71 loc) · 2.76 KB
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
package uk.co.uwcs.choob.util;
import com.google.common.collect.Lists;
import uk.co.uwcs.choob.exceptions.UnmatchedBracketException;
import java.util.EnumSet;
import java.util.List;
/**
* Utility class for parsing arguments to Choob commands.
* @author rayhaan
*/
public class ArgParse {
/**
* Tweak how commands are parsed.
*/
public enum ParseMode {
// Convert any spaces between quotes to underscores.
SPACE_IN_QUOTE_TO_UNDERSCORE;
}
private ArgParse() {}
private static boolean isQuotationCharacter(char c) {
return (c == '"') || (c == '\'') || (c == '«') || (c == '»');
}
public static List<String> split(String message, EnumSet<ParseMode> modes) throws UnmatchedBracketException {
final char[] chars = message.toCharArray();
List<String> result = Lists.newArrayList();
StringBuilder currentWord = new StringBuilder();
boolean containsNonEmpty = false;
boolean modeInQuote = false;
for (int pos = 0; pos < chars.length; pos++) {
boolean quoteChar = isQuotationCharacter(chars[pos]);
if (quoteChar && !modeInQuote) {
// We are now entering a quotation, everything in here is a new string
modeInQuote = true;
continue;
}
if (quoteChar && modeInQuote) {
// Exit the quote and move on to the next word.
modeInQuote = false;
result.add(currentWord.toString());
currentWord = new StringBuilder();
containsNonEmpty = false;
continue;
}
if (chars[pos] == '\\' && isQuotationCharacter(chars[pos + 1])) {
// skip over the next character
pos++;
continue;
}
// If we are in quote mode then convert spaces to underscores.
if (modes.contains(ParseMode.SPACE_IN_QUOTE_TO_UNDERSCORE) && modeInQuote && chars[pos] == ' ') {
currentWord.append('_');
continue;
}
if (chars[pos] == ' ' && !modeInQuote && containsNonEmpty) {
result.add(currentWord.toString());
currentWord = new StringBuilder();
containsNonEmpty = false;
continue;
}
if (chars[pos] != ' ') containsNonEmpty = true;
if (chars[pos] == ' ' && !containsNonEmpty) continue;
currentWord.append(chars[pos]);
}
// If we are still in a quote at the end something has gone wrong.
if (modeInQuote) {
throw new UnmatchedBracketException();
}
// Append the last word.
result.add(currentWord.toString());
return result;
}
}