1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.tonicsystems.jarjar;
18
19 import java.io.*;
20 import java.util.*;
21
22 class RulesFileParser
23 {
24 private RulesFileParser() {
25 }
26
27 public static List<PatternElement> parse(File file) throws IOException {
28 return parse(new FileReader(file));
29 }
30
31 public static List<PatternElement> parse(String value) throws IOException {
32 return parse(new java.io.StringReader(value));
33 }
34
35 private static String stripComment(String in) {
36 int p = in.indexOf("#");
37 return p < 0 ? in : in.substring(0, p);
38 }
39
40 private static List<PatternElement> parse(Reader r) throws IOException {
41 try {
42 List<PatternElement> patterns = new ArrayList<PatternElement>();
43 BufferedReader br = new BufferedReader(r);
44 int c = 1;
45 String line;
46 while ((line = br.readLine()) != null) {
47 line = stripComment(line);
48 if (line.length()==0)
49 continue;
50 String[] parts = line.split("\\s+");
51 if (parts.length < 2)
52 error(c, parts);
53 String type = parts[0];
54 PatternElement element = null;
55 if (type.equals("rule")) {
56 if (parts.length < 3)
57 error(c, parts);
58 Rule rule = new Rule();
59 rule.setResult(parts[2]);
60 element = rule;
61 } else if (type.equals("zap")) {
62 element = new Zap();
63 } else if (type.equals("keep")) {
64 element = new Keep();
65 } else {
66 error(c, parts);
67 }
68 element.setPattern(parts[1]);
69 patterns.add(element);
70 c++;
71 }
72 return patterns;
73 } finally {
74 r.close();
75 }
76 }
77
78 private static void error(int line, String[] parts) {
79 throw new IllegalArgumentException("Error on line " + line + ": " + Arrays.asList(parts));
80 }
81 }