Search in sources :

Example 1 with ImportOrganizer

use of com.google.errorprone.apply.ImportOrganizer in project error-prone by google.

the class RefactoringCollection method refactor.

static RefactoringCollection refactor(PatchingOptions patchingOptions) {
    Path rootPath = buildRootPath();
    FileDestination fileDestination;
    Function<URI, RefactoringResult> postProcess;
    if (patchingOptions.inPlace()) {
        fileDestination = new FsFileDestination(rootPath);
        postProcess = uri -> RefactoringResult.create(String.format("Refactoring changes were successfully applied to %s," + " please check the refactored code and recompile.", uri), RefactoringResultType.CHANGED);
    } else {
        Path baseDir = rootPath.resolve(patchingOptions.baseDirectory());
        Path patchFilePath = baseDir.resolve("error-prone.patch");
        PatchFileDestination patchFileDestination = new PatchFileDestination(baseDir, rootPath);
        postProcess = new Function<URI, RefactoringResult>() {

            private final AtomicBoolean first = new AtomicBoolean(true);

            @Override
            public RefactoringResult apply(URI uri) {
                try {
                    writePatchFile(first, uri, patchFileDestination, patchFilePath);
                    return RefactoringResult.create("Changes were written to " + patchFilePath + ". Please inspect the file and apply with: " + "patch -p0 -u -i error-prone.patch", RefactoringResultType.CHANGED);
                } catch (IOException e) {
                    throw new RuntimeException("Failed to emit patch file!", e);
                }
            }
        };
        fileDestination = patchFileDestination;
    }
    ImportOrganizer importOrganizer = patchingOptions.importOrganizer();
    return new RefactoringCollection(rootPath, fileDestination, postProcess, importOrganizer);
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) URI(java.net.URI) ImportOrganizer(com.google.errorprone.apply.ImportOrganizer) FsFileDestination(com.google.errorprone.apply.FsFileDestination) FileDestination(com.google.errorprone.apply.FileDestination) PatchFileDestination(com.google.errorprone.apply.PatchFileDestination) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FsFileDestination(com.google.errorprone.apply.FsFileDestination) PatchFileDestination(com.google.errorprone.apply.PatchFileDestination)

Example 2 with ImportOrganizer

use of com.google.errorprone.apply.ImportOrganizer in project error-prone by google.

the class ErrorProneOptions method processArgs.

/**
 * Given a list of command-line arguments, produce the corresponding {@link ErrorProneOptions}
 * instance.
 *
 * @param args command-line arguments
 * @return an {@link ErrorProneOptions} instance encapsulating the given arguments
 * @throws InvalidCommandLineOptionException if an error-prone option is invalid
 */
public static ErrorProneOptions processArgs(Iterable<String> args) {
    Preconditions.checkNotNull(args);
    ImmutableList.Builder<String> remainingArgs = ImmutableList.builder();
    /* By default, we throw an error when an unknown option is passed in, if for example you
     * try to disable a check that doesn't match any of the known checks.  This catches typos from
     * the command line.
     *
     * You can pass the IGNORE_UNKNOWN_CHECKS_FLAG to opt-out of that checking.  This allows you to
     * use command lines from different versions of error-prone interchangeably.
     */
    Builder builder = new Builder();
    for (String arg : args) {
        switch(arg) {
            case IGNORE_UNKNOWN_CHECKS_FLAG:
                builder.setIgnoreUnknownChecks(true);
                break;
            case DISABLE_WARNINGS_IN_GENERATED_CODE_FLAG:
                builder.setDisableWarningsInGeneratedCode(true);
                break;
            case ERRORS_AS_WARNINGS_FLAG:
                builder.setDropErrorsToWarnings(true);
                break;
            case ENABLE_ALL_CHECKS:
                builder.setEnableAllChecksAsWarnings(true);
                break;
            case DISABLE_ALL_CHECKS:
                builder.setDisableAllChecks(true);
                break;
            case COMPILING_TEST_ONLY_CODE:
                builder.setTestOnlyTarget(true);
                break;
            default:
                if (arg.startsWith(SEVERITY_PREFIX)) {
                    builder.parseSeverity(arg);
                } else if (arg.startsWith(ErrorProneFlags.PREFIX)) {
                    builder.parseFlag(arg);
                } else if (arg.startsWith(PATCH_OUTPUT_LOCATION)) {
                    String remaining = arg.substring(PATCH_OUTPUT_LOCATION.length());
                    if (remaining.equals("IN_PLACE")) {
                        builder.patchingOptionsBuilder().inPlace(true);
                    } else {
                        if (remaining.isEmpty()) {
                            throw new InvalidCommandLineOptionException("invalid flag: " + arg);
                        }
                        builder.patchingOptionsBuilder().baseDirectory(remaining);
                    }
                } else if (arg.startsWith(PATCH_CHECKS_PREFIX)) {
                    String remaining = arg.substring(PATCH_CHECKS_PREFIX.length());
                    if (remaining.startsWith("refaster:")) {
                        // Refaster rule, load from InputStream at file
                        builder.patchingOptionsBuilder().customRefactorer(() -> {
                            String path = remaining.substring("refaster:".length());
                            try (InputStream in = Files.newInputStream(FileSystems.getDefault().getPath(path));
                                ObjectInputStream ois = new ObjectInputStream(in)) {
                                return (CodeTransformer) ois.readObject();
                            } catch (IOException | ClassNotFoundException e) {
                                throw new RuntimeException("Can't load Refaster rule from " + path, e);
                            }
                        });
                    } else {
                        Iterable<String> checks = Splitter.on(',').trimResults().split(remaining);
                        builder.patchingOptionsBuilder().namedCheckers(ImmutableSet.copyOf(checks));
                    }
                } else if (arg.startsWith(PATCH_IMPORT_ORDER_PREFIX)) {
                    String remaining = arg.substring(PATCH_IMPORT_ORDER_PREFIX.length());
                    ImportOrganizer importOrganizer = ImportOrderParser.getImportOrganizer(remaining);
                    builder.patchingOptionsBuilder().importOrganizer(importOrganizer);
                } else if (arg.startsWith(EXCLUDED_PATHS_PREFIX)) {
                    String pathRegex = arg.substring(EXCLUDED_PATHS_PREFIX.length());
                    builder.setExcludedPattern(Pattern.compile(pathRegex));
                } else {
                    remainingArgs.add(arg);
                }
        }
    }
    return builder.build(remainingArgs.build());
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) ImportOrganizer(com.google.errorprone.apply.ImportOrganizer) ObjectInputStream(java.io.ObjectInputStream)

Example 3 with ImportOrganizer

use of com.google.errorprone.apply.ImportOrganizer in project error-prone by google.

the class BugCheckerRefactoringTestHelper method applyDiff.

private JavaFileObject applyDiff(JavaFileObject sourceFileObject, Context context, JCCompilationUnit tree) throws IOException {
    ImportOrganizer importOrganizer = ImportOrderParser.getImportOrganizer(importOrder);
    final DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree, importOrganizer);
    transformer(refactoringBugChecker).apply(new TreePath(tree), context, new DescriptionListener() {

        @Override
        public void onDescribed(Description description) {
            if (!description.fixes.isEmpty()) {
                diff.handleFix(fixChooser.choose(description.fixes));
            }
        }
    });
    SourceFile sourceFile = SourceFile.create(sourceFileObject);
    diff.applyDifferences(sourceFile);
    JavaFileObject transformed = JavaFileObjects.forSourceString(getFullyQualifiedName(tree), sourceFile.getSourceText());
    return transformed;
}
Also used : DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) JavaFileObject(javax.tools.JavaFileObject) Description(com.google.errorprone.matchers.Description) TreePath(com.sun.source.util.TreePath) SourceFile(com.google.errorprone.apply.SourceFile) ImportOrganizer(com.google.errorprone.apply.ImportOrganizer)

Aggregations

ImportOrganizer (com.google.errorprone.apply.ImportOrganizer)3 ImmutableList (com.google.common.collect.ImmutableList)1 DescriptionBasedDiff (com.google.errorprone.apply.DescriptionBasedDiff)1 FileDestination (com.google.errorprone.apply.FileDestination)1 FsFileDestination (com.google.errorprone.apply.FsFileDestination)1 PatchFileDestination (com.google.errorprone.apply.PatchFileDestination)1 SourceFile (com.google.errorprone.apply.SourceFile)1 Description (com.google.errorprone.matchers.Description)1 TreePath (com.sun.source.util.TreePath)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 ObjectInputStream (java.io.ObjectInputStream)1 URI (java.net.URI)1 Path (java.nio.file.Path)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 JavaFileObject (javax.tools.JavaFileObject)1