com.android.tools.lint.client.api.IssueRegistry Java Examples

The following examples show how to use com.android.tools.lint.client.api.IssueRegistry. 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: Lint.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs lint on the given variant and returns the set of warnings
 */
@Nullable
private List<Warning> runLint(@NonNull AndroidProject modelProject, @NonNull String variantName, boolean report) {
    IssueRegistry registry = createIssueRegistry();
    LintCliFlags flags = new LintCliFlags();
    LintGradleClient client = new LintGradleClient(registry, flags, getProject(), modelProject, mSdkHome, variantName);
    if (mFatalOnly) {
        if (!mLintOptions.isCheckReleaseBuilds()) {
            return null;

        }

        flags.setFatalOnly(true);
    }

    syncOptions(mLintOptions, client, flags, variantName, getProject(), report, mFatalOnly);
    if (!report || mFatalOnly) {
        flags.setQuiet(true);
    }


    List<Warning> warnings;
    try {
        warnings = client.run(registry);
    } catch (IOException e) {
        throw new GradleException("Invalid arguments.", e);
    }


    if (report && client.haveErrors() && flags.isSetExitCode()) {
        abort();
    }


    return warnings;
}
 
Example #2
Source File: LintGradleClient.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public LintGradleClient(
        @NonNull IssueRegistry registry,
        @NonNull LintCliFlags flags,
        @NonNull org.gradle.api.Project gradleProject,
        @NonNull AndroidProject modelProject,
        @Nullable File sdkHome,
        @Nullable String variantName) {
    super(flags);
    mGradleProject = gradleProject;
    mModelProject = modelProject;
    mVariantName = variantName;
    mSdkHome = sdkHome;
    mRegistry = registry;
}
 
Example #3
Source File: ApiDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void beforeCheckProject(@NonNull Context context) {
    mApiDatabase = ApiLookup.get(context.getClient());
    // We can't look up the minimum API required by the project here:
    // The manifest file hasn't been processed yet in the -before- project hook.
    // For now it's initialized lazily in getMinSdk(Context), but the
    // lint infrastructure should be fixed to parse manifest file up front.

    if (mApiDatabase == null && !mWarnedMissingDb) {
        mWarnedMissingDb = true;
        context.report(IssueRegistry.LINT_ERROR, Location.create(context.file),
                    "Can't find API database; API check not performed");
    }
}
 
Example #4
Source File: LintDetectorTest.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
protected boolean isEnabled(Issue issue) {
    Class<? extends Detector> detectorClass = getDetectorInstance().getClass();
    if (issue.getImplementation().getDetectorClass() == detectorClass) {
        return true;
    }

    if (issue == IssueRegistry.LINT_ERROR || issue == IssueRegistry.PARSER_ERROR) {
        return !ignoreSystemErrors();
    }

    return false;
}
 
Example #5
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 #6
Source File: LintCliClient.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs the static analysis command line driver. You need to add at least one error reporter
 * to the command line flags.
 */
public int run(@NonNull IssueRegistry registry, @NonNull List<File> files) throws IOException {
    assert !mFlags.getReporters().isEmpty();
    mRegistry = registry;
    mDriver = new LintDriver(registry, this);

    mDriver.setAbbreviating(!mFlags.isShowEverything());
    addProgressPrinter();
    mDriver.addLintListener(new LintListener() {
        @Override
        public void update(@NonNull LintDriver driver, @NonNull EventType type,
                @Nullable Context context) {
            if (type == EventType.SCANNING_PROJECT && !mValidatedIds) {
                // Make sure all the id's are valid once the driver is all set up and
                // ready to run (such that custom rules are available in the registry etc)
                validateIssueIds(context != null ? context.getProject() : null);
            }
        }
    });

    mDriver.analyze(createLintRequest(files));

    Collections.sort(mWarnings);

    boolean hasConsoleOutput = false;
    for (Reporter reporter : mFlags.getReporters()) {
        reporter.write(mErrorCount, mWarningCount, mWarnings);
        if (reporter instanceof TextReporter && ((TextReporter)reporter).isWriteToConsole()) {
            hasConsoleOutput = true;
        }
    }

    if (!mFlags.isQuiet() && !hasConsoleOutput) {
        System.out.println(String.format(
                "Lint found %1$d errors and %2$d warnings", mErrorCount, mWarningCount));
    }

    return mFlags.isSetExitCode() ? (mHasErrors ? ERRNO_ERRORS : ERRNO_SUCCESS) : ERRNO_SUCCESS;
}
 
Example #7
Source File: LintCliClient.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks that any id's specified by id refer to valid, known, issues. This
 * typically can't be done right away (in for example the Gradle code which
 * handles DSL references to strings, or in the command line parser for the
 * lint command) because the full set of valid id's is not known until lint
 * actually starts running and for example gathers custom rules from all
 * AAR dependencies reachable from libraries, etc.
 */
private void validateIssueIds(@Nullable Project project) {
    if (mDriver != null) {
        IssueRegistry registry = mDriver.getRegistry();
        if (!registry.isIssueId(HardcodedValuesDetector.ISSUE.getId())) {
            // This should not be necessary, but there have been some strange
            // reports where lint has reported some well known builtin issues
            // to not exist:
            //
            //   Error: Unknown issue id "DuplicateDefinition" [LintError]
            //   Error: Unknown issue id "GradleIdeError" [LintError]
            //   Error: Unknown issue id "InvalidPackage" [LintError]
            //   Error: Unknown issue id "JavascriptInterface" [LintError]
            //   ...
            //
            // It's not clear how this can happen, though it's probably related
            // to using 3rd party lint rules (where lint will create new composite
            // issue registries to wrap the various additional issues) - but
            // we definitely don't want to validate issue id's if we can't find
            // well known issues.
            return;
        }
        mValidatedIds = true;
        validateIssueIds(project, registry, mFlags.getExactCheckedIds());
        validateIssueIds(project, registry, mFlags.getEnabledIds());
        validateIssueIds(project, registry, mFlags.getSuppressedIds());
        validateIssueIds(project, registry, mFlags.getSeverityOverrides().keySet());
    }
}
 
Example #8
Source File: LintCliClient.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void validateIssueIds(@Nullable Project project, @NonNull IssueRegistry registry,
        @Nullable Collection<String> ids) {
    if (ids != null) {
        for (String id : ids) {
            if (registry.getIssue(id) == null) {
                reportNonExistingIssueId(project, id);
            }
        }
    }
}
 
Example #9
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 #10
Source File: Main.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private IssueRegistry getGlobalRegistry(LintCliClient client) {
    if (mGlobalRegistry == null) {
        mGlobalRegistry = client.addCustomLintRules(new BuiltinIssueRegistry());
    }

    return mGlobalRegistry;
}
 
Example #11
Source File: Main.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void displayValidIds(IssueRegistry registry, PrintStream out) {
    List<Category> categories = registry.getCategories();
    out.println("Valid issue categories:");
    for (Category category : categories) {
        out.println("    " + category.getFullName());
    }
    out.println();
    List<Issue> issues = registry.getIssues();
    out.println("Valid issue id's:");
    for (Issue issue : issues) {
        listIssue(out, issue);
    }
}
 
Example #12
Source File: Main.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void showIssues(IssueRegistry registry) {
    List<Issue> issues = registry.getIssues();
    List<Issue> sorted = new ArrayList<Issue>(issues);
    Collections.sort(sorted, new Comparator<Issue>() {
        @Override
        public int compare(Issue issue1, Issue issue2) {
            int d = issue1.getCategory().compareTo(issue2.getCategory());
            if (d != 0) {
                return d;
            }
            d = issue2.getPriority() - issue1.getPriority();
            if (d != 0) {
                return d;
            }

            return issue1.getId().compareTo(issue2.getId());
        }
    });

    System.out.println("Available issues:\n");
    Category previousCategory = null;
    for (Issue issue : sorted) {
        Category category = issue.getCategory();
        if (!category.equals(previousCategory)) {
            String name = category.getFullName();
            System.out.println(name);
            for (int i = 0, n = name.length(); i < n; i++) {
                System.out.print('=');
            }
            System.out.println('\n');
            previousCategory = category;
        }

        describeIssue(issue);
        System.out.println();
    }
}
 
Example #13
Source File: LintGradleClient.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Run lint with the given registry and return the resulting warnings
 */
@NonNull
public List<Warning> run(@NonNull IssueRegistry registry) throws IOException {
    run(registry, Collections.<File>emptyList());
    return mWarnings;
}
 
Example #14
Source File: AnnotationDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
private boolean checkId(Annotation node, String id) {
    IssueRegistry registry = mContext.getDriver().getRegistry();
    Issue issue = registry.getIssue(id);
    // Special-case the ApiDetector issue, since it does both source file analysis
    // only on field references, and class file analysis on the rest, so we allow
    // annotations outside of methods only on fields
    if (issue != null && !issue.getImplementation().getScope().contains(Scope.JAVA_FILE)
            || issue == ApiDetector.UNSUPPORTED) {
        // Ensure that this isn't a field
        Node parent = node.getParent();
        while (parent != null) {
            if (parent instanceof MethodDeclaration
                    || parent instanceof ConstructorDeclaration
                    || parent instanceof Block) {
                break;
            } else if (parent instanceof TypeBody) { // It's a field
                return true;
            } else if (issue == ApiDetector.UNSUPPORTED
                    && parent instanceof VariableDefinition) {
                VariableDefinition definition = (VariableDefinition) parent;
                for (VariableDefinitionEntry entry : definition.astVariables()) {
                    Expression initializer = entry.astInitializer();
                    if (initializer instanceof Select) {
                        return true;
                    }
                }
            }
            parent = parent.getParent();
            if (parent == null) {
                return true;
            }
        }

        // This issue doesn't have AST access: annotations are not
        // available for local variables or parameters
        Node scope = getAnnotationScope(node);
        mContext.report(INSIDE_METHOD, scope, mContext.getLocation(node), String.format(
            "The `@SuppressLint` annotation cannot be used on a local " +
            "variable with the lint check '%1$s': move out to the " +
            "surrounding method", id));
        return false;
    }

    return true;
}
 
Example #15
Source File: LintCliClient.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/** Returns the issue registry used by this client */
IssueRegistry getRegistry() {
    return mRegistry;
}
 
Example #16
Source File: BuiltinIssueRegistry.java    From javaide with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Reset the registry such that it recomputes its available issues.
 * <p>
 * NOTE: This is only intended for testing purposes.
 */
@VisibleForTesting
public static void reset() {
    IssueRegistry.reset();
}