72 lines
2.4 KiB
Java
72 lines
2.4 KiB
Java
package io.gitlab.jfronny.inceptum.launcher.util.gitignore;
|
|
|
|
import java.util.List;
|
|
import java.util.function.Predicate;
|
|
import java.util.regex.Pattern;
|
|
|
|
public class IgnoreRule {
|
|
private static final List<Replacer> REPLACERS = List.of(
|
|
Replacers.TRAILING_SPACES,
|
|
Replacers.ESCAPED_SPACES,
|
|
Replacers.LITERAL_DOT,
|
|
Replacers.LITERAL_PLUS,
|
|
|
|
// probably not needed
|
|
// Replacers.METACHARACTERS,
|
|
Replacers.QUESTION_MARK,
|
|
Replacers.NON_LEADING_SINGLE_STAR,
|
|
Replacers.LEADING_SINGLE_STAR,
|
|
Replacers.LEADING_DOUBLE_STAR,
|
|
|
|
// probably not needed
|
|
// Replacers.METACHARACTER_SLASH_AFTER_LEADING_SLASH,
|
|
Replacers.MIDDLE_DOUBLE_STAR,
|
|
Replacers.LEADING_SLASH,
|
|
Replacers.TRAILING_DOUBLE_STAR,
|
|
Replacers.OTHER_DOUBLE_STAR,
|
|
Replacers.MIDDLE_SLASH,
|
|
Replacers.TRAILING_SLASH,
|
|
Replacers.NO_SLASH,
|
|
Replacers.NO_TRAILING_SLASH,
|
|
Replacers.ENDING
|
|
);
|
|
|
|
private final Predicate<String> parsedRegex;
|
|
public final boolean negate;
|
|
|
|
/**
|
|
* Initializes a new instance of the IgnoreRule class.
|
|
* Parses the given pattern as per .gitignore spec.
|
|
*
|
|
* @param pattern Pattern to parse
|
|
*/
|
|
public IgnoreRule(String pattern) {
|
|
if (pattern == null || pattern.isBlank() || pattern.startsWith("#")) { // Ignore comments and empty lines
|
|
parsedRegex = s -> false;
|
|
negate = false;
|
|
return;
|
|
}
|
|
boolean isNegate = false;
|
|
if (pattern.startsWith("\\!") || pattern.startsWith("\\#")) {
|
|
pattern = pattern.substring(1);
|
|
} else if (pattern.startsWith("!")) {
|
|
isNegate = true;
|
|
pattern = pattern.substring(1);
|
|
}
|
|
negate = isNegate;
|
|
for (Replacer replacer : REPLACERS) {
|
|
try {
|
|
pattern = replacer.invoke(pattern);
|
|
} catch (Throwable t) {
|
|
throw new RuntimeException("Could not execute replacer " + replacer.getName() + " (" + replacer.getRegex() + ") on " + pattern, t);
|
|
}
|
|
}
|
|
|
|
parsedRegex = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).asMatchPredicate();
|
|
}
|
|
|
|
public boolean isMatch(String input) {
|
|
return parsedRegex.test(input);
|
|
}
|
|
}
|