Search in sources :

Example 1 with Violation

use of com.puppycrawl.tools.checkstyle.api.Violation in project checkstyle by checkstyle.

the class Main method main.

/**
 * Loops over the files specified checking them for errors. The exit code
 * is the number of errors found in all the files.
 *
 * @param args the command line arguments.
 * @throws IOException if there is a problem with files access
 * @noinspection UseOfSystemOutOrSystemErr, CallToPrintStackTrace, CallToSystemExit
 */
public static void main(String... args) throws IOException {
    final CliOptions cliOptions = new CliOptions();
    final CommandLine commandLine = new CommandLine(cliOptions);
    commandLine.setUsageHelpWidth(CliOptions.HELP_WIDTH);
    commandLine.setCaseInsensitiveEnumValuesAllowed(true);
    // provide proper exit code based on results.
    int exitStatus = 0;
    int errorCounter = 0;
    try {
        final ParseResult parseResult = commandLine.parseArgs(args);
        if (parseResult.isVersionHelpRequested()) {
            System.out.println(getVersionString());
        } else if (parseResult.isUsageHelpRequested()) {
            commandLine.usage(System.out);
        } else {
            exitStatus = execute(parseResult, cliOptions);
            errorCounter = exitStatus;
        }
    } catch (ParameterException ex) {
        exitStatus = EXIT_WITH_INVALID_USER_INPUT_CODE;
        System.err.println(ex.getMessage());
        System.err.println("Usage: checkstyle [OPTIONS]... FILES...");
        System.err.println("Try 'checkstyle --help' for more information.");
    } catch (CheckstyleException ex) {
        exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE;
        errorCounter = 1;
        ex.printStackTrace();
    } finally {
        // return exit code base on validation of Checker
        if (errorCounter > 0) {
            final Violation errorCounterViolation = new Violation(1, Definitions.CHECKSTYLE_BUNDLE, ERROR_COUNTER, new String[] { String.valueOf(errorCounter) }, null, Main.class, null);
            // print error count statistic to error output stream,
            // output stream might be used by validation report content
            System.err.println(errorCounterViolation.getViolation());
        }
    }
    Runtime.getRuntime().exit(exitStatus);
}
Also used : Violation(com.puppycrawl.tools.checkstyle.api.Violation) CommandLine(picocli.CommandLine) ParseResult(picocli.CommandLine.ParseResult) ParameterException(picocli.CommandLine.ParameterException) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException)

Example 2 with Violation

use of com.puppycrawl.tools.checkstyle.api.Violation in project checkstyle by checkstyle.

the class PackageObjectFactory method createObjectFromFullModuleNames.

/**
 * Create Object from optional full module names.
 * In most case, there should be only one element in {@code fullModuleName}, otherwise
 * an exception would be thrown.
 *
 * @param name name of module
 * @param fullModuleNames the supplied full module names set
 * @return instance of module if there is only one element in {@code fullModuleName}
 * @throws CheckstyleException if the class fails to instantiate or there are more than one
 *      element in {@code fullModuleName}
 */
private Object createObjectFromFullModuleNames(String name, Set<String> fullModuleNames) throws CheckstyleException {
    final Object returnValue;
    if (fullModuleNames.size() == 1) {
        returnValue = createObject(fullModuleNames.iterator().next());
    } else {
        final String optionalNames = fullModuleNames.stream().sorted().collect(Collectors.joining(STRING_SEPARATOR));
        final Violation exceptionMessage = new Violation(1, Definitions.CHECKSTYLE_BUNDLE, AMBIGUOUS_MODULE_NAME_EXCEPTION_MESSAGE, new String[] { name, optionalNames }, null, getClass(), null);
        throw new CheckstyleException(exceptionMessage.getViolation());
    }
    return returnValue;
}
Also used : Violation(com.puppycrawl.tools.checkstyle.api.Violation) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException)

Example 3 with Violation

use of com.puppycrawl.tools.checkstyle.api.Violation in project checkstyle by checkstyle.

the class PackageObjectFactory method createModule.

/**
 * Creates a new instance of a class from a given name, or that name
 * concatenated with &quot;Check&quot;. If the name is
 * a class name, creates an instance of the named class. Otherwise, creates
 * an instance of a class name obtained by concatenating the given name
 * to a package name from a given list of package names.
 *
 * @param name the name of a class.
 * @return the {@code Object} created by loader.
 * @throws CheckstyleException if an error occurs.
 */
@Override
public Object createModule(String name) throws CheckstyleException {
    Object instance = null;
    // if the name is a simple class name, try to find it in maps at first
    if (!name.contains(PACKAGE_SEPARATOR)) {
        instance = createFromStandardCheckSet(name);
        // find the name in third party map
        if (instance == null) {
            if (thirdPartyNameToFullModuleNames == null) {
                thirdPartyNameToFullModuleNames = generateThirdPartyNameToFullModuleName(moduleClassLoader);
            }
            instance = createObjectFromMap(name, thirdPartyNameToFullModuleNames);
        }
    }
    if (instance == null) {
        instance = createObject(name);
    }
    if (instance == null && moduleLoadOption == ModuleLoadOption.TRY_IN_ALL_REGISTERED_PACKAGES) {
        instance = createModuleByTryInEachPackage(name);
    }
    if (instance == null) {
        String attemptedNames = null;
        if (!name.contains(PACKAGE_SEPARATOR)) {
            final String nameCheck = name + CHECK_SUFFIX;
            attemptedNames = joinPackageNamesWithClassName(name, packages) + STRING_SEPARATOR + nameCheck + STRING_SEPARATOR + joinPackageNamesWithClassName(nameCheck, packages);
        }
        final Violation exceptionMessage = new Violation(1, Definitions.CHECKSTYLE_BUNDLE, UNABLE_TO_INSTANTIATE_EXCEPTION_MESSAGE, new String[] { name, attemptedNames }, null, getClass(), null);
        throw new CheckstyleException(exceptionMessage.getViolation());
    }
    return instance;
}
Also used : Violation(com.puppycrawl.tools.checkstyle.api.Violation) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException)

Example 4 with Violation

use of com.puppycrawl.tools.checkstyle.api.Violation in project checkstyle by checkstyle.

the class Checker method fireErrors.

/**
 * Notify all listeners about the errors in a file.
 *
 * @param fileName the audited file
 * @param errors the audit errors from the file
 */
@Override
public void fireErrors(String fileName, SortedSet<Violation> errors) {
    final String stripped = CommonUtil.relativizeAndNormalizePath(basedir, fileName);
    boolean hasNonFilteredViolations = false;
    for (final Violation element : errors) {
        final AuditEvent event = new AuditEvent(this, stripped, element);
        if (filters.accept(event)) {
            hasNonFilteredViolations = true;
            for (final AuditListener listener : listeners) {
                listener.addError(event);
            }
        }
    }
    if (hasNonFilteredViolations && cacheFile != null) {
        cacheFile.remove(fileName);
    }
}
Also used : Violation(com.puppycrawl.tools.checkstyle.api.Violation) AuditEvent(com.puppycrawl.tools.checkstyle.api.AuditEvent) AuditListener(com.puppycrawl.tools.checkstyle.api.AuditListener)

Example 5 with Violation

use of com.puppycrawl.tools.checkstyle.api.Violation in project checkstyle by checkstyle.

the class XpathFileGeneratorAstFilterTest method testClearState.

/**
 * We cannot reproduce situation when {@code finishLocalSetup} is called
 * twice. So, we have to use reflection to be sure that even in such
 * situation state of the field will be cleared.
 *
 * @throws Exception when code tested throws exception
 */
@Test
@SuppressWarnings("unchecked")
public void testClearState() throws Exception {
    final Violation violation = new Violation(3, 47, TokenTypes.LCURLY, "messages.properties", null, null, SeverityLevel.ERROR, null, LeftCurlyCheck.class, null);
    final TreeWalkerAuditEvent event = createTreeWalkerAuditEvent("InputXpathFileGeneratorAstFilter.java", violation);
    final XpathFileGeneratorAstFilter filter = new XpathFileGeneratorAstFilter();
    assertWithMessage("State is not cleared on finishLocalSetup").that(TestUtil.isStatefulFieldClearedDuringLocalSetup(filter, event, "MESSAGE_QUERY_MAP", variableStack -> ((Map<Violation, String>) variableStack).isEmpty())).isTrue();
}
Also used : Violation(com.puppycrawl.tools.checkstyle.api.Violation) Test(org.junit.jupiter.api.Test)

Aggregations

Violation (com.puppycrawl.tools.checkstyle.api.Violation)109 Test (org.junit.jupiter.api.Test)98 AuditEvent (com.puppycrawl.tools.checkstyle.api.AuditEvent)51 TreeWalkerAuditEvent (com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent)17 File (java.io.File)14 TreeWalkerTest (com.puppycrawl.tools.checkstyle.TreeWalkerTest)13 CheckstyleException (com.puppycrawl.tools.checkstyle.api.CheckstyleException)10 DefaultConfiguration (com.puppycrawl.tools.checkstyle.DefaultConfiguration)8 FileContents (com.puppycrawl.tools.checkstyle.api.FileContents)7 FileText (com.puppycrawl.tools.checkstyle.api.FileText)7 TreeSet (java.util.TreeSet)6 DetailAstImpl (com.puppycrawl.tools.checkstyle.DetailAstImpl)5 ParseErrorMessage (com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.ParseErrorMessage)3 SeverityLevel (com.puppycrawl.tools.checkstyle.api.SeverityLevel)3 DebugAuditAdapter (com.puppycrawl.tools.checkstyle.internal.testmodules.DebugAuditAdapter)3 DebugFilter (com.puppycrawl.tools.checkstyle.internal.testmodules.DebugFilter)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 OutputStream (java.io.OutputStream)3 Method (java.lang.reflect.Method)3 Checker (com.puppycrawl.tools.checkstyle.Checker)2