• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2007 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.tonicsystems.jarjar;
18 
19 import java.io.*;
20 import java.util.*;
21 
22 class RulesFileParser
23 {
RulesFileParser()24     private RulesFileParser() {
25     }
26 
parse(File file)27     public static List<PatternElement> parse(File file) throws IOException {
28         return parse(new FileReader(file));
29     }
30 
parse(String value)31     public static List<PatternElement> parse(String value) throws IOException {
32         return parse(new java.io.StringReader(value));
33     }
34 
stripComment(String in)35     private static String stripComment(String in) {
36       int p = in.indexOf("#");
37       return p < 0 ? in : in.substring(0, p);
38     }
39 
parse(Reader r)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.isEmpty())
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 
error(int line, String[] parts)78     private static void error(int line, String[] parts) {
79       throw new IllegalArgumentException("Error on line " + line + ": " + Arrays.asList(parts));
80     }
81 }
82