com.android.tools.lint.detector.api.TextFormat Java Examples

The following examples show how to use com.android.tools.lint.detector.api.TextFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TodoDetector.java    From Android-Lint-Checks with Apache License 2.0 6 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    String source = context.getContents();

    // Check validity of source
    if (source == null) {
        return null;
    }

    // Check for uses of to-dos
    int index = source.indexOf(TODO_MATCHER_STRING);
    for (int i = index; i >= 0; i = source.indexOf(TODO_MATCHER_STRING, i + 1)) {
        Location location = Location.create(context.file, source, i, i + TODO_MATCHER_STRING.length());
        context.report(ISSUE, location, ISSUE.getBriefDescription(TextFormat.TEXT));
    }
    return null;
}
 
Example #2
Source File: GridLayoutDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Given an error message produced by this lint detector,
 * returns the old value to be replaced in the source code.
 * <p>
 * Intended for IDE quickfix implementations.
 *
 * @param errorMessage the error message associated with the error
 * @param format the format of the error message
 * @return the corresponding old value, or null if not recognized
 */
@Nullable
public static String getOldValue(@NonNull String errorMessage,
        @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);
    String attribute = LintUtils.findSubstring(errorMessage, " should use ", " ");
    if (attribute == null) {
        attribute = LintUtils.findSubstring(errorMessage, " should use ", null);
    }
    if (attribute != null) {
        int index = attribute.indexOf(':');
        if (index != -1) {
            return ANDROID_NS_NAME + attribute.substring(index);
        }
    }

    return null;
}
 
Example #3
Source File: TodoDetectorTest.java    From Android-Lint-Checks with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a java file with a to-do has a warning.
 */
public void testTodoCase() throws Exception {
    String file = "TodoTestCase.java";
    String warningMessage = file
            + ":5: Warning: "
            + TodoDetector.ISSUE.getBriefDescription(TextFormat.TEXT)
            + " ["
            + TodoDetector.ISSUE.getId()
            + "]\n"
            + "    // TODO\n"
            + "       ~~~~\n"
            + "0 errors, 1 warnings\n";
    assertEquals(
            warningMessage,
            lintFiles(file)
    );
}
 
Example #4
Source File: TodoDetector.java    From linette with Apache License 2.0 6 votes vote down vote up
@Override
public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
    String source = context.getContents();

    // Check validity of source
    if (source == null) {
        return null;
    }

    // Check for uses of to-dos
    int index = source.indexOf(TODO_MATCHER_STRING);
    for (int i = index; i >= 0; i = source.indexOf(TODO_MATCHER_STRING, i + 1)) {
        Location location = Location.create(context.file, source, i, i + TODO_MATCHER_STRING.length());
        context.report(ISSUE, location, ISSUE.getBriefDescription(TextFormat.TEXT));
    }
    return null;
}
 
Example #5
Source File: MinSdkDetectorTest.java    From linette with Apache License 2.0 6 votes vote down vote up
/**
 * Test that an invalid AndroidManifest.xml has a warning.
 */
public void testInvalidManifest() throws Exception {
    String warningMessage = MinSdkDetectorTest.class.getSimpleName()
            + "_"
            + Thread.currentThread().getStackTrace()[1].getMethodName()
            + ": Warning: "
            + MinSdkDetector.ISSUE.getBriefDescription(TextFormat.TEXT)
            + " ["
            + MinSdkDetector.ISSUE.getId()
            + "]\n"
            + "0 errors, 1 warnings\n";
    assertEquals(
            warningMessage,
            lintFiles("InvalidAndroidManifest.xml=>AndroidManifest.xml")
    );
}
 
Example #6
Source File: TodoDetectorTest.java    From linette with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a java file with a to-do has a warning.
 */
public void testTodoCase() throws Exception {
    String file = "TodoTestCase.java";
    String warningMessage = file
            + ":5: Warning: "
            + TodoDetector.ISSUE.getBriefDescription(TextFormat.TEXT)
            + " ["
            + TodoDetector.ISSUE.getId()
            + "]\n"
            + "    // TODO\n"
            + "       ~~~~\n"
            + "0 errors, 1 warnings\n";
    assertEquals(
            warningMessage,
            lintFiles(file)
    );
}
 
Example #7
Source File: MinSdkDetector.java    From linette with Apache License 2.0 5 votes vote down vote up
@Override
public void afterCheckProject(Context context) {
    super.afterCheckProject(context);
    int minSdk = context.getProject().getMinSdk();
    if (minSdk != -1 && minSdk < SUGGESTED_MIN_SDK_VERSION) {
        context.report(ISSUE, Location.create(context.file), ISSUE.getBriefDescription(TextFormat.TEXT));
    }
}
 
Example #8
Source File: EnumDetectorTest.java    From linette with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a java file with an enum has a warning.
 */
public void testEnumCase() throws Exception {
    String file = "EnumTestCase.java";
    String warningMessage = file
            + ": Warning: "
            + EnumDetector.ISSUE.getBriefDescription(TextFormat.TEXT)
            + " ["
            + EnumDetector.ISSUE.getId()
            + "]\n"
            + "0 errors, 1 warnings\n";
    assertEquals(
            warningMessage,
            lintFiles(file)
    );
}
 
Example #9
Source File: FromMethodVisitor.java    From HighLite with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visitCallExpression(UCallExpression node) {
    if (!METHOD_NAME.equals(node.getMethodName())) return false;

    final JavaUCompositeQualifiedExpression exp =
            (JavaUCompositeQualifiedExpression) node.getUastParent();
    if (exp == null
            || !CLASS_SQLITE_OPERATOR.equals(exp.receiver.toString())
            || node.getValueArgumentCount() != 2) return false;

    final JavaUClassLiteralExpression classLiteral =
            (JavaUClassLiteralExpression) node.getValueArguments().get(PARAM_INDEX);

    if (classLiteral == null) return false;

    final PsiClass psiClass = mContext.getEvaluator().findClass(classLiteral.toString());

    if (psiClass == null
            || psiClass.getModifierList() == null) return false;

    boolean found = false;
    for (final PsiAnnotation annotation : psiClass.getModifierList().getAnnotations()) {
        if (!ANNOTATION_TYPE_LONG.equals(annotation.getQualifiedName())) continue;

        found = true;
        break;
    }

    if (!found) {
        mContext.report(ISSUE, mContext.getLocation(classLiteral),
                String.format(ISSUE.getExplanation(TextFormat.TEXT), classLiteral));
        return true;
    }

    return false;
}
 
Example #10
Source File: ConfigAttributeAnnotationOnNonConfigFieldDetector.java    From aircon with MIT License 5 votes vote down vote up
@Override
public void visit(final UAnnotation node) {
	if (!ConfigElementsUtils.isConfigAttributeAnnotation(node)) {
		return;
	}
	final PsiField field = (PsiField) node.getUastParent()
	                                      .getJavaPsi();
	if (!ConfigElementsUtils.isConfigField(field) || ConfigElementsUtils.isConfigGroupField(field)) {
		report(node, "**@" + getSimpleName(node) + "** " + ISSUE.getExplanation(TextFormat.TEXT));
	}
}
 
Example #11
Source File: HtmlReporter.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void writeSuppressInfo() throws IOException {
    //getSuppressHelp
    mWriter.write("\n<a name=\"SuppressInfo\"></a>\n");      //$NON-NLS-1$
    mWriter.write("<div class=\"category\">");               //$NON-NLS-1$
    mWriter.write("Suppressing Warnings and Errors");
    mWriter.write("<div class=\"categorySeparator\"></div>\n");//$NON-NLS-1$
    mWriter.write("</div>\n");                               //$NON-NLS-1$
    mWriter.write(TextFormat.RAW.convertTo(Main.getSuppressHelp(), TextFormat.HTML));
    mWriter.write('\n');
}
 
Example #12
Source File: LintCliClient.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
protected void reportNonExistingIssueId(@Nullable Project project, @NonNull String id) {
    String message = String.format("Unknown issue id \"%1$s\"", id);

    if (mDriver != null && project != null) {
        Location location = Location.create(project.getDir());
        if (!isSuppressed(IssueRegistry.LINT_ERROR)) {
            report(new Context(mDriver, project, project, project.getDir()),
                    IssueRegistry.LINT_ERROR,
                    project.getConfiguration(mDriver).getSeverity(IssueRegistry.LINT_ERROR),
                    location, message, TextFormat.RAW);
        }
    } else {
        log(Severity.ERROR, null, "Lint: %1$s", message);
    }
}
 
Example #13
Source File: TextReporter.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void explainIssue(@NonNull StringBuilder output, @Nullable Issue issue)
        throws IOException {
    if (issue == null || !mFlags.isExplainIssues() || issue == IssueRegistry.LINT_ERROR) {
        return;
    }

    String explanation = issue.getExplanation(TextFormat.TEXT);
    if (explanation.trim().isEmpty()) {
        return;
    }

    String indent = "   ";
    String formatted = SdkUtils.wrap(explanation, Main.MAX_LINE_WIDTH - indent.length(), null);
    output.append('\n');
    output.append(indent);
    output.append("Explanation for issues of type \"").append(issue.getId()).append("\":\n");
    for (String line : Splitter.on('\n').split(formatted)) {
        if (!line.isEmpty()) {
            output.append(indent);
            output.append(line);
        }
        output.append('\n');
    }
    List<String> moreInfo = issue.getMoreInfo();
    if (!moreInfo.isEmpty()) {
        for (String url : moreInfo) {
            if (formatted.contains(url)) {
                continue;
            }
            output.append(indent);
            output.append(url);
            output.append('\n');
        }
        output.append('\n');
    }
}
 
Example #14
Source File: LintCliXmlParserTest.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void report(
        @NonNull Context context,
        @NonNull Issue issue,
        @NonNull Severity severity,
        @Nullable Location location,
        @NonNull String message,
        @NonNull TextFormat format) {
    System.out.println(location + ":" + message);
}
 
Example #15
Source File: AppCompatCallDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private static String getMessagePart(@NonNull String errorMessage, int group,
        @NonNull TextFormat format) {
    List<String> parameters = LintUtils.getFormattedParameters(
            RAW.convertTo(ERROR_MESSAGE_FORMAT, format),
            errorMessage);
    if (parameters.size() == 2 && group <= 2) {
        return parameters.get(group - 1);
    }

    return null;
}
 
Example #16
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * For an error message for an {@link #USE_VALUE_OF} issue reported by this detector,
 * returns the type being replaced. Intended to use for IDE quickfix implementations.
 */
@Nullable
public static String getReplacedType(@NonNull String message, @NonNull TextFormat format) {
    message = format.toText(message);
    int index = message.indexOf('.');
    if (index != -1 && message.startsWith("Use ")) {
        return message.substring(4, index);
    }
    return null;
}
 
Example #17
Source File: GridLayoutDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Given an error message produced by this lint detector,
 * returns the new value to be put into the source code.
 * <p>
 * Intended for IDE quickfix implementations.
 *
 * @param errorMessage the error message associated with the error
 * @param format the format of the error message
 * @return the corresponding new value, or null if not recognized
 */
@Nullable
public static String getNewValue(@NonNull String errorMessage,
        @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);
    String attribute = LintUtils.findSubstring(errorMessage, " should use ", " ");
    if (attribute == null) {
        attribute = LintUtils.findSubstring(errorMessage, " should use ", null);
    }
    return attribute;
}
 
Example #18
Source File: ConfigFieldReferenceDetector.java    From aircon with MIT License 5 votes vote down vote up
private void visitFieldReference(final @NotNull UQualifiedReferenceExpression node, final PsiField field) {
	final PsiClass containingClass = ElementUtils.getContainingClass(node);
	if (!ConfigElementsUtils.hasFeatureRemoteConfigAnnotation(containingClass)) {
		final boolean remoteConfigField = ConfigElementsUtils.hasConfigAnnotation(field);
		if (remoteConfigField) {
			report(node, ISSUE.getExplanation(TextFormat.TEXT) + " **" + CommonNamingUtils.getProviderClassName(field.getContainingClass()
			                                                                                                         .getName()) + "**");
		}
	}
}
 
Example #19
Source File: DefaultConfiguration.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void formatError(String message, Object... args) {
    if (args != null && args.length > 0) {
        message = String.format(message, args);
    }
    message = "Failed to parse `lint.xml` configuration file: " + message;
    LintDriver driver = new LintDriver(new IssueRegistry() {
        @Override @NonNull public List<Issue> getIssues() {
            return Collections.emptyList();
        }
    }, mClient);
    mClient.report(new Context(driver, mProject, mProject, mConfigFile),
            IssueRegistry.LINT_ERROR,
            mProject.getConfiguration(driver).getSeverity(IssueRegistry.LINT_ERROR),
            Location.create(mConfigFile), message, TextFormat.RAW);
}
 
Example #20
Source File: ApiDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public static int getRequiredVersion(@NonNull Issue issue, @NonNull String errorMessage,
        @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);

    if (issue == UNSUPPORTED || issue == INLINED) {
        Pattern pattern = Pattern.compile("\\s(\\d+)\\s"); //$NON-NLS-1$
        Matcher matcher = pattern.matcher(errorMessage);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        }
    }

    return -1;
}
 
Example #21
Source File: LintDriver.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void report(
        @NonNull Context context,
        @NonNull Issue issue,
        @NonNull Severity severity,
        @Nullable Location location,
        @NonNull String message,
        @NonNull TextFormat format) {
    assert mCurrentProject != null;
    if (!mCurrentProject.getReportIssues()) {
        return;
    }

    Configuration configuration = context.getConfiguration();
    if (!configuration.isEnabled(issue)) {
        if (issue != IssueRegistry.PARSER_ERROR && issue != IssueRegistry.LINT_ERROR) {
            mDelegate.log(null, "Incorrect detector reported disabled issue %1$s",
                    issue.toString());
        }
        return;
    }

    if (configuration.isIgnored(context, issue, location, message)) {
        return;
    }

    if (severity == Severity.IGNORE) {
        return;
    }

    mDelegate.report(context, issue, severity, location, message, format);
}
 
Example #22
Source File: TypoDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Returns the suggested replacements, if any, for the given typo. The error
 * message <b>must</b> be one supplied by lint.
 *
 * @param errorMessage the error message
 * @param format the format of the error message
 * @return a list of replacement words suggested by the error message
 */
@Nullable
public static List<String> getSuggestions(@NonNull String errorMessage,
        @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);

    // The words are all in quotes; the first word is the misspelling,
    // the other words are the suggested replacements
    List<String> words = new ArrayList<String>();
    // Skip the typo
    int index = errorMessage.indexOf('"');
    index = errorMessage.indexOf('"', index + 1);
    index++;

    while (true) {
        index = errorMessage.indexOf('"', index);
        if (index == -1) {
            break;
        }
        index++;
        int start = index;
        index = errorMessage.indexOf('"', index);
        if (index == -1) {
            index = errorMessage.length();
        }
        words.add(errorMessage.substring(start, index));
        index++;
    }

    return words;
}
 
Example #23
Source File: TypoDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the typo word in the error message from this detector
 *
 * @param errorMessage the error message produced earlier by this detector
 * @param format the format of the error message
 * @return the typo
 */
@Nullable
public static String getTypo(@NonNull String errorMessage, @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);
    // The words are all in quotes
    int index = errorMessage.indexOf('"');
    int start = index + 1;
    index = errorMessage.indexOf('"', start);
    if (index != -1) {
        return errorMessage.substring(start, index);
    }

    return null;
}
 
Example #24
Source File: GradleDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Given an error message produced by this lint detector for the given issue type,
 * returns the old value to be replaced in the source code.
 * <p>
 * Intended for IDE quickfix implementations.
 *
 * @param issue the corresponding issue
 * @param errorMessage the error message associated with the error
 * @param format the format of the error message
 * @return the corresponding old value, or null if not recognized
 */
@Nullable
public static String getOldValue(@NonNull Issue issue, @NonNull String errorMessage,
        @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);

    // Consider extracting all the error strings as constants and handling this
    // using the LintUtils#getFormattedParameters() method to pull back out the information
    if (issue == DEPENDENCY) {
        // "A newer version of com.google.guava:guava than 11.0.2 is available: 17.0.0"
        if (errorMessage.startsWith("A newer ")) {
            return findSubstring(errorMessage, " than ", " ");
        }
        if (errorMessage.startsWith("Old buildToolsVersion ")) {
            return findSubstring(errorMessage, "Old buildToolsVersion ", ";");
        }
        // "The targetSdkVersion (20) should not be higher than the compileSdkVersion (19)"
        return findSubstring(errorMessage, "targetSdkVersion (", ")");
    } else if (issue == STRING_INTEGER) {
        return findSubstring(errorMessage, "replace ", " with ");
    } else if (issue == DEPRECATED) {
        if (errorMessage.contains(GradleDetector.APP_PLUGIN_ID) &&
                errorMessage.contains(GradleDetector.OLD_APP_PLUGIN_ID)) {
            return GradleDetector.OLD_APP_PLUGIN_ID;
        } else if (errorMessage.contains(GradleDetector.LIB_PLUGIN_ID) &&
                errorMessage.contains(GradleDetector.OLD_LIB_PLUGIN_ID)) {
            return GradleDetector.OLD_LIB_PLUGIN_ID;
        }
        // "Deprecated: Replace 'packageNameSuffix' with 'applicationIdSuffix'"
        return findSubstring(errorMessage, "Replace '", "'");
    } else if (issue == PLUS) {
      return findSubstring(errorMessage, "(", ")");
    } else if (issue == COMPATIBILITY) {
        if (errorMessage.startsWith("Version 5.2.08")) {
            return "5.2.08";
        }
    }

    return null;
}
 
Example #25
Source File: GradleDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Given an error message produced by this lint detector for the given issue type,
 * returns the new value to be put into the source code.
 * <p>
 * Intended for IDE quickfix implementations.
 *
 * @param issue the corresponding issue
 * @param errorMessage the error message associated with the error
 * @param format the format of the error message
 * @return the corresponding new value, or null if not recognized
 */
@Nullable
public static String getNewValue(@NonNull Issue issue, @NonNull String errorMessage,
        @NonNull TextFormat format) {
    errorMessage = format.toText(errorMessage);

    if (issue == DEPENDENCY) {
        // "A newer version of com.google.guava:guava than 11.0.2 is available: 17.0.0"
        if (errorMessage.startsWith("A newer ")) {
            return findSubstring(errorMessage, " is available: ", null);
        }
        if (errorMessage.startsWith("Old buildToolsVersion ")) {
            return findSubstring(errorMessage, " version is ", " ");
        }
        // "The targetSdkVersion (20) should not be higher than the compileSdkVersion (19)"
        return findSubstring(errorMessage, "compileSdkVersion (", ")");
    } else if (issue == STRING_INTEGER) {
        return findSubstring(errorMessage, " just ", ")");
    } else if (issue == DEPRECATED) {
        if (errorMessage.contains(GradleDetector.APP_PLUGIN_ID) &&
                errorMessage.contains(GradleDetector.OLD_APP_PLUGIN_ID)) {
            return GradleDetector.APP_PLUGIN_ID;
        } else if (errorMessage.contains(GradleDetector.LIB_PLUGIN_ID) &&
                errorMessage.contains(GradleDetector.OLD_LIB_PLUGIN_ID)) {
            return GradleDetector.LIB_PLUGIN_ID;
        }
        // "Deprecated: Replace 'packageNameSuffix' with 'applicationIdSuffix'"
        return findSubstring(errorMessage, " with '", "'");
    } else if (issue == COMPATIBILITY) {
        if (errorMessage.startsWith("Version 5.2.08")) {
            return findSubstring(errorMessage, "Use version ", " ");
        }
    }

    return null;
}
 
Example #26
Source File: EnumDetector.java    From linette with Apache License 2.0 4 votes vote down vote up
@Override
public boolean visitEnumDeclaration(EnumDeclaration node) {
    mContext.report(ISSUE, Location.create(mContext.file), ISSUE.getBriefDescription(TextFormat.TEXT));
    return super.visitEnumDeclaration(node);
}
 
Example #27
Source File: IssueDetector.java    From aircon with MIT License 4 votes vote down vote up
protected void report(final UElement node, LintFix lintFix) {
	report(node, mIssue.getExplanation(TextFormat.RAW), lintFix);
}
 
Example #28
Source File: IssueDetector.java    From aircon with MIT License 4 votes vote down vote up
protected void reportPsi(final PsiElement node) {
	reportPsi(node, mIssue.getExplanation(TextFormat.RAW));
}
 
Example #29
Source File: IssueDetector.java    From aircon with MIT License 4 votes vote down vote up
protected void reportPsi(final PsiElement node, LintFix lintFix) {
	reportPsi(node, mIssue.getExplanation(TextFormat.RAW), lintFix);
}
 
Example #30
Source File: IssueDetector.java    From aircon with MIT License 4 votes vote down vote up
protected String getIssueExplanation() {
	return mIssue.getExplanation(TextFormat.TEXT);
}