1 package org.apache.rat.mp.util.ignore;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.plugin.logging.Log;
23
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileReader;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Optional;
34
35 public class GlobIgnoreMatcher implements IgnoreMatcher {
36
37 final List<String> exclusionLines = new ArrayList<>();
38
39 private static final List<String> COMMENT_PREFIXES = Arrays.asList("#", "##", "//", "/**", "/*");
40
41 public GlobIgnoreMatcher() {
42
43 }
44
45 public GlobIgnoreMatcher(final Log log, final File scmIgnore) {
46 loadFile(log, scmIgnore);
47 }
48
49
50
51
52
53 public void addRule(final String rule) {
54 if (!exclusionLines.contains(rule)) {
55 exclusionLines.add(rule);
56 }
57 }
58
59
60
61
62
63 public void addRules(final Collection<String> rules) {
64 for (String rule : rules) {
65 if (!exclusionLines.contains(rule)) {
66 exclusionLines.add(rule);
67 }
68 }
69 }
70
71
72
73
74
75
76
77 public void loadFile(final Log log, final File scmIgnore) {
78 if (scmIgnore != null && scmIgnore.exists() && scmIgnore.isFile()) {
79 log.debug("Parsing exclusions from " + scmIgnore);
80
81 try (BufferedReader reader = new BufferedReader(new FileReader(scmIgnore))) {
82 String line;
83 while ((line = reader.readLine()) != null) {
84 if (!isComment(line)) {
85 exclusionLines.add(line);
86 log.debug("Added " + line);
87 }
88 }
89 } catch (final IOException e) {
90 log.warn("Cannot parse " + scmIgnore + " for exclusions. Will skip this file.");
91 log.debug("Skip parsing " + scmIgnore + " due to " + e.getMessage());
92 }
93 }
94 }
95
96
97
98
99
100
101
102
103
104 public static boolean isComment(final String line) {
105 if (line == null || line.length() <= 0) {
106 return false;
107 }
108
109 final String trimLine = line.trim();
110 for (String prefix : COMMENT_PREFIXES) {
111 if (trimLine.startsWith(prefix)) {
112 return true;
113 }
114 }
115 return false;
116 }
117
118 public List<String> getExclusionLines() {
119 return Collections.unmodifiableList(exclusionLines);
120 }
121
122 @Override
123 public boolean isEmpty() {
124 return exclusionLines.isEmpty();
125 }
126
127 @Override
128 public Optional<Boolean> isIgnoredFile(String filename) {
129
130
131 return Optional.empty() ;
132 }
133 }