Search in sources :

Example 21 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class SkylarkTransformation method transform.

@Override
public TransformationStatus transform(TransformWork work) throws IOException, ValidationException, RepoException {
    SkylarkConsole skylarkConsole = new SkylarkConsole(work.getConsole());
    TransformWork skylarkWork = work.withConsole(skylarkConsole).withParams(params);
    TransformationStatus status = TransformationStatus.success();
    try (Mutability mu = Mutability.create("dynamic_transform")) {
        StarlarkThread thread = new StarlarkThread(mu, StarlarkSemantics.DEFAULT);
        thread.setPrintHandler(printHandler);
        Object result = Starlark.call(thread, function, ImmutableList.of(skylarkWork), /*kwargs=*/
        ImmutableMap.of());
        result = result == Starlark.NONE ? TransformationStatus.success() : result;
        checkCondition(result instanceof TransformationStatus, "Dynamic transforms functions should return nothing or objects of type %s, but '%s'" + " returned: %s", TransformationStatus.STARLARK_TYPE_NAME, describe(), result);
        status = (TransformationStatus) result;
    } catch (EvalException e) {
        if (e.getCause() instanceof EmptyChangeException) {
            throw ((EmptyChangeException) e.getCause());
        }
        if (e.getCause() instanceof RepoException) {
            throw new RepoException(String.format("Error while executing the skylark transformation %s: %s", describe(), e.getMessageWithStack()), e);
        }
        throw new ValidationException(String.format("Error while executing the skylark transformation %s: %s", describe(), e.getMessageWithStack()), e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("This should not happen.", e);
    } finally {
        work.updateFrom(skylarkWork);
    }
    checkCondition(skylarkConsole.getErrorCount() == 0, "%d error(s) while executing %s", skylarkConsole.getErrorCount(), describe());
    return status;
}
Also used : TransformationStatus(com.google.copybara.TransformationStatus) ValidationException(com.google.copybara.exception.ValidationException) NonReversibleValidationException(com.google.copybara.exception.NonReversibleValidationException) StarlarkThread(net.starlark.java.eval.StarlarkThread) TransformWork(com.google.copybara.TransformWork) Mutability(net.starlark.java.eval.Mutability) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) EvalException(net.starlark.java.eval.EvalException) RepoException(com.google.copybara.exception.RepoException)

Example 22 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class SkylarkTestExecutor method evalWithConfigFilePathAndModuleSet.

@SuppressWarnings({ "TypeParameterUnusedInFormals" })
public <T> T evalWithConfigFilePathAndModuleSet(String var, String config, String configPath, ModuleSet moduleSet) throws ValidationException {
    try {
        Module module = skylarkParser.executeSkylark(createConfigFile(configPath, config), moduleSet, options.general.console());
        // the cast below is wildly unsound
        @SuppressWarnings("unchecked") T t = (T) module.getGlobal(var);
        Preconditions.checkNotNull(t, "Config %s evaluates to null '%s' var.", config, var);
        return t;
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException(String.format("Should not happen: %s.\n %s", e.getMessage(), getLogErrors()), e);
    } catch (ValidationException ve) {
        throw new ValidationException(ve.getMessage() + getLogErrors(), ve);
    }
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) IOException(java.io.IOException) Module(net.starlark.java.eval.Module)

Example 23 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class TransformDebug method transform.

@Override
public TransformationStatus transform(TransformWork work) throws IOException, ValidationException, RepoException {
    Console console = work.getConsole();
    boolean fileDebug = false;
    if (debugOptions.getDebugFileBreak() != null) {
        fileDebug = true;
    }
    boolean metadataDebug = false;
    if (debugOptions.debugMetadataBreak) {
        metadataDebug = true;
    }
    Pattern debugTransformBreak = debugOptions.getDebugTransformBreak();
    boolean transformMatch = false;
    if (debugTransformBreak != null && debugTransformBreak.matcher(this.delegate.describe()).find()) {
        transformMatch = true;
    }
    if (!fileDebug && !metadataDebug && !transformMatch) {
        // Nothing to debug!
        return delegate.transform(work);
    }
    TreeMap<String, byte[]> before = readState(work, fileDebug || transformMatch, work.getTreeState());
    TransformationStatus status = delegate.transform(work);
    work.validateTreeStateCache();
    TreeMap<String, byte[]> after = readState(work, fileDebug || transformMatch, work.getTreeState());
    MapDifference<String, byte[]> difference = Maps.difference(before, after, new Equivalence<byte[]>() {

        @Override
        protected boolean doEquivalent(byte[] one, byte[] other) {
            return Arrays.equals(one, other);
        }

        @Override
        protected int doHash(byte[] bytes) {
            return Arrays.hashCode(bytes);
        }
    });
    boolean stop = transformMatch;
    if (fileDebug) {
        PathMatcher debugFileBreak = debugOptions.getDebugFileBreak().relativeTo(Paths.get("/"));
        for (String path : Iterables.concat(difference.entriesOnlyOnLeft().keySet(), difference.entriesOnlyOnRight().keySet(), difference.entriesDiffering().keySet())) {
            if (path.equals(COPYBARA_METADATA_FAKE_FILE)) {
                continue;
            }
            if (debugFileBreak.matches(Paths.get("/" + path))) {
                stop = true;
                console.infoFmt("File '%s' change matched. Stopping", path);
                break;
            }
        }
    } else if (metadataDebug && !Arrays.equals(before.get(COPYBARA_METADATA_FAKE_FILE), after.get(COPYBARA_METADATA_FAKE_FILE))) {
        stop = true;
        console.infoFmt("Message, author and/or labels changed");
    }
    if (!stop) {
        return status;
    }
    if (!transformMatch) {
        // Stopped because of file/metadata change. Show the diff directly
        showDiff(console, difference);
    }
    while (true) {
        String answer = console.ask("Debugger stopped after '" + delegate.describe() + "' " + console.colorize(AnsiColor.PURPLE, delegate.location().toString()) + ".\n" + "      Current file state can be checked at " + work.getCheckoutDir() + "\n" + "Diff (d), Continue (c), Stop (s): ", "d", input -> ImmutableSet.of("d", "c", "s").contains(input));
        switch(answer) {
            case "d":
                {
                    showDiff(console, difference);
                    break;
                }
            case "c":
                return status;
            case "s":
                throw new ValidationException("Stopped by user");
        }
    }
}
Also used : Pattern(com.google.re2j.Pattern) TransformationStatus(com.google.copybara.TransformationStatus) PathMatcher(java.nio.file.PathMatcher) ValidationException(com.google.copybara.exception.ValidationException) NonReversibleValidationException(com.google.copybara.exception.NonReversibleValidationException) Console(com.google.copybara.util.console.Console)

Example 24 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class ReferenceMigrator method transform.

@Override
public TransformationStatus transform(TransformWork work) throws ValidationException {
    AtomicReference<ValidationException> thrown = new AtomicReference<>();
    Replacer replacer = before.callbackReplacer(after, (groupValues, template) -> {
        if (groupValues.get(0) != null) {
            try {
                String destinationRef = findChange(groupValues.get(1), work.getMigrationInfo().getOriginLabel(), work.getMigrationInfo().destinationVisitable());
                if (destinationRef != null) {
                    // issue, a non-naive implementation might be required.
                    return Pattern.compile("[$]1").matcher(template).replaceAll(destinationRef);
                } else {
                    return groupValues.get(0);
                }
            } catch (ValidationException exception) {
                thrown.compareAndSet(null, exception);
                return groupValues.get(0);
            }
        }
        return template;
    }, false, false, null);
    String replaced = replacer.replace(work.getMessage());
    if (thrown.get() != null) {
        throw thrown.get();
    }
    if (!replaced.equals(work.getMessage())) {
        work.setMessage(replaced);
    }
    return TransformationStatus.success();
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Replacer(com.google.copybara.transform.RegexTemplateTokens.Replacer)

Example 25 with ValidationException

use of com.google.copybara.exception.ValidationException in project copybara by google.

the class TemplateMessage method transform.

@Override
public TransformationStatus transform(TransformWork work) throws IOException, ValidationException {
    String newMsg;
    try {
        newMsg = labelTemplate.resolve(work::getLabel);
    } catch (LabelNotFoundException e) {
        if (ignoreIfLabelNotFound) {
            return TransformationStatus.success();
        }
        throw new ValidationException(String.format("Cannot find label '%s' in message:\n %s\nor any of the original commit messages", e.getLabel(), work.getMessage()));
    }
    if (!replaceMessage) {
        newMsg += (newLine ? "\n" : "") + work.getMessage();
    }
    work.setMessage(newMsg);
    return TransformationStatus.success();
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) LabelNotFoundException(com.google.copybara.templatetoken.LabelTemplate.LabelNotFoundException)

Aggregations

ValidationException (com.google.copybara.exception.ValidationException)178 Test (org.junit.Test)125 Path (java.nio.file.Path)33 RepoException (com.google.copybara.exception.RepoException)29 NonReversibleValidationException (com.google.copybara.exception.NonReversibleValidationException)26 ImmutableList (com.google.common.collect.ImmutableList)21 IOException (java.io.IOException)19 Console (com.google.copybara.util.console.Console)16 EmptyChangeException (com.google.copybara.exception.EmptyChangeException)14 DummyRevision (com.google.copybara.testing.DummyRevision)14 Glob (com.google.copybara.util.Glob)14 ProfilerTask (com.google.copybara.profiler.Profiler.ProfilerTask)13 Nullable (javax.annotation.Nullable)13 Migration (com.google.copybara.config.Migration)11 TestingConsole (com.google.copybara.util.console.testing.TestingConsole)11 Iterables (com.google.common.collect.Iterables)10 Change (com.google.copybara.Change)10 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)10 Collectors (java.util.stream.Collectors)10 WriterContext (com.google.copybara.WriterContext)9