1 /* 2 * Copyright (C) 2017 The Dagger Authors. 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 dagger.internal.codegen.base; 18 19 import java.util.regex.Matcher; 20 import java.util.regex.Pattern; 21 22 /** 23 * Utility methods for formatting diagnostics to the {@link javax.annotation.processing.Messager}. 24 */ 25 public final class DiagnosticFormatting { 26 27 /** 28 * A regular expression to match a small list of specific packages deemed to be unhelpful to 29 * display in fully qualified types in error messages. 30 * 31 * <p>Note: This should never be applied to messages themselves. 32 */ 33 private static final Pattern COMMON_PACKAGE_PATTERN = 34 Pattern.compile( 35 "(?:^|[^.a-z_])" // What we want to match on but not capture. 36 + "((?:" // Start a group with a non-capturing or part 37 + "java[.]lang" 38 + "|java[.]util" 39 + "|javax[.]inject" 40 + "|dagger" 41 + "|dagger[.]multibindings" 42 + "|com[.]google[.]common[.]base" 43 + "|com[.]google[.]common[.]collect" 44 + ")[.])" // Always end with a literal . 45 + "[A-Z]"); // What we want to match on but not capture. 46 47 /** 48 * A method to strip out common packages and a few rare type prefixes from types' string 49 * representation before being used in error messages. 50 * 51 * <p>This type assumes a String value that is a valid fully qualified (and possibly 52 * parameterized) type, and should NOT be used with arbitrary text, especially prose error 53 * messages. 54 * 55 * <p>TODO(user): Tighten these to take type representations (mirrors and elements) to avoid 56 * accidental mis-use by running errors through this method. 57 */ stripCommonTypePrefixes(String type)58 public static String stripCommonTypePrefixes(String type) { 59 // Do regex magic to remove common packages we care to shorten. 60 Matcher matcher = COMMON_PACKAGE_PATTERN.matcher(type); 61 StringBuilder result = new StringBuilder(); 62 int index = 0; 63 while (matcher.find()) { 64 result.append(type.subSequence(index, matcher.start(1))); 65 index = matcher.end(1); // Skip the matched pattern content. 66 } 67 result.append(type.subSequence(index, type.length())); 68 return result.toString(); 69 } 70 DiagnosticFormatting()71 private DiagnosticFormatting() {} 72 } 73