Search in sources :

Example 16 with ValidationException

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

the class GitMirrorContext method merge.

@StarlarkMethod(name = "merge", doc = "Merge one or more commits into a local branch.", parameters = { @Param(name = "branch", named = true), @Param(name = "commits", allowedTypes = { @ParamType(type = Sequence.class, generic1 = String.class) }, named = true), @Param(name = "msg", named = true, defaultValue = "None") })
public MergeResult merge(String branch, Sequence<?> commits, Object msg) throws RepoException, ValidationException, EvalException, IOException {
    ValidationException.checkCondition(!commits.isEmpty(), "At least one commit should be passed to merge");
    GitRepository withWorktree = this.repo.withWorkTree(dirFactory.newTempDir("mirror"));
    try {
        withWorktree.forceCheckout(branch);
    } catch (RepoException e) {
        throw new ValidationException("Cannot merge commits " + commits + " into branch " + branch + " because of failure during merge checkout", e);
    }
    String strMsg = SkylarkUtil.convertFromNoneable(msg, null);
    // Clean everything before the merge
    withWorktree.simpleCommand("reset", "--hard");
    withWorktree.forceClean();
    List<String> cmd = Lists.newArrayList("merge");
    if (strMsg != null) {
        cmd.add("-m");
        cmd.add(strMsg);
    }
    cmd.addAll(SkylarkUtil.convertStringList(commits, "commits"));
    try {
        withWorktree.simpleCommand(cmd);
    } catch (RepoException e) {
        logger.atWarning().withCause(e).log("Error running merge in action %s for branch %s and commits %s", getActionName(), branch, commits);
        return MergeResult.error(e.getMessage());
    }
    return MergeResult.success();
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) RepoException(com.google.copybara.exception.RepoException) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Example 17 with ValidationException

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

the class Mirror method run.

@Override
public void run(Path workdir, ImmutableList<String> sourceRefs) throws RepoException, IOException, ValidationException {
    try (ProfilerTask ignore = generalOptions.profiler().start("run/" + name)) {
        GitRepository repo = gitOptions.cachedBareRepoForUrl(origin);
        if (Iterables.isEmpty(actions)) {
            defaultMirror(repo);
        } else {
            ImmutableList.Builder<ActionResult> allResultsBuilder = ImmutableList.builder();
            for (Action action : actions) {
                GitMirrorContext context = new GitMirrorContext(action, new SkylarkConsole(generalOptions.console()), sourceRefs, refspec, origin, destination, generalOptions.isForced(), repo, generalOptions.getDirFactory(), Dict.empty());
                try {
                    action.run(context);
                    ActionResult actionResult = context.getActionResult();
                    allResultsBuilder.add(actionResult);
                    // First error aborts the execution of the other actions unless --force is used
                    ValidationException.checkCondition(generalOptions.isForced() || actionResult.getResult() != Result.ERROR, "Feedback migration '%s' action '%s' returned error: %s. Aborting execution.", name, action.getName(), actionResult.getMsg());
                } catch (NonFastForwardRepositoryException e) {
                    allResultsBuilder.add(ActionResult.error(action.getName() + ": " + e.getMessage()));
                    if (!generalOptions.isForced()) {
                        throw e;
                    }
                    logger.atWarning().withCause(e).log();
                } finally {
                    generalOptions.eventMonitors().dispatchEvent(m -> m.onChangeMigrationFinished(new ChangeMigrationFinishedEvent(ImmutableList.copyOf(context.getNewDestinationEffects()), getOriginDescription(), getDestinationDescription())));
                }
            }
            ImmutableList<ActionResult> allResults = allResultsBuilder.build();
            if (allResults.stream().anyMatch(a -> a.getResult() == Result.ERROR)) {
                String errors = allResults.stream().filter(a -> a.getResult() == Result.ERROR).map(ActionResult::getMsg).collect(Collectors.joining("\n - "));
                throw new ValidationException("One or more errors happened during the migration:\n" + " - " + errors);
            }
            // This check also returns true if there are no actions
            if (allResults.stream().allMatch(a -> a.getResult() == Result.NO_OP)) {
                String detailedMessage = allResults.isEmpty() ? "actions field is empty" : allResults.stream().map(ActionResult::getMsg).collect(ImmutableList.toImmutableList()).toString();
                throw new EmptyChangeException(String.format("git.mirror migration '%s' was noop. Detailed messages: %s", name, detailedMessage));
            }
        }
    }
    // More fine grain events based on the references created/updated/deleted:
    ChangeMigrationFinishedEvent event = new ChangeMigrationFinishedEvent(ImmutableList.of(new DestinationEffect(generalOptions.dryRunMode ? DestinationEffect.Type.NOOP : DestinationEffect.Type.UPDATED, generalOptions.dryRunMode ? "Refspecs " + refspec + " can be mirrored" : "Refspecs " + refspec + " mirrored successfully", // TODO(danielromero): Populate OriginRef here
    ImmutableList.of(), new DestinationRef(getOriginDestinationRef(destination), "mirror", /*url=*/
    null))), getOriginDescription(), getDestinationDescription());
    generalOptions.eventMonitors().dispatchEvent(m -> m.onChangeMigrationFinished(event));
}
Also used : Action(com.google.copybara.action.Action) ValidationException(com.google.copybara.exception.ValidationException) ChangeMigrationFinishedEvent(com.google.copybara.monitor.EventMonitor.ChangeMigrationFinishedEvent) ImmutableList(com.google.common.collect.ImmutableList) SkylarkConsole(com.google.copybara.transform.SkylarkConsole) ActionResult(com.google.copybara.action.ActionResult) DestinationRef(com.google.copybara.DestinationEffect.DestinationRef) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) DestinationEffect(com.google.copybara.DestinationEffect) EmptyChangeException(com.google.copybara.exception.EmptyChangeException)

Example 18 with ValidationException

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

the class HgRepository method pull.

public void pull(String url, boolean force, @Nullable String ref) throws RepoException, ValidationException {
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    builder.add("pull", validateNotHttp(url));
    if (force) {
        builder.add("--force");
    }
    if (!Strings.isNullOrEmpty(ref)) {
        builder.add("--rev", ref);
    }
    try {
        hg(hgDir, builder.build(), fetchTimeout);
    } catch (RepoException e) {
        if (INVALID_HG_REPOSITORY.matcher(e.getMessage()).find()) {
            throw new ValidationException("Repository not found: " + e.getMessage());
        }
        if (UNKNOWN_REVISION.matcher(e.getMessage()).find()) {
            throw new ValidationException("Unknown revision: " + e.getMessage());
        }
        throw e;
    }
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) ImmutableList(com.google.common.collect.ImmutableList) RepoException(com.google.copybara.exception.RepoException)

Example 19 with ValidationException

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

the class HgVisitorUtil method visitChanges.

/**
 * Visits Hg changes, up to the termination point specified by the visitor.
 */
static void visitChanges(HgRevision start, ChangesVisitor visitor, ChangeReader.Builder queryChanges, GeneralOptions generalOptions, String type, int visitChangePageSize) throws RepoException {
    Preconditions.checkNotNull(start);
    int offset = 0;
    boolean finished = false;
    try (ProfilerTask ignore = generalOptions.profiler().start(type + "/visit_changes")) {
        while (!finished) {
            ImmutableList<Change<HgRevision>> result;
            try (ProfilerTask ignore2 = generalOptions.profiler().start(String.format("hg_log_%d_%d", offset, visitChangePageSize))) {
                try {
                    result = queryChanges.setSkip(offset).setLimit(visitChangePageSize).build().run(start.getGlobalId()).reverse();
                } catch (ValidationException e) {
                    throw new RepoException(String.format("Error querying changes: %s", e.getMessage()), e.getCause());
                }
            }
            if (result.isEmpty()) {
                break;
            }
            offset += result.size();
            for (Change<HgRevision> current : result) {
                if (visitor.visit(current) == VisitResult.TERMINATE) {
                    finished = true;
                    break;
                }
            }
        }
    }
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) Change(com.google.copybara.Change) RepoException(com.google.copybara.exception.RepoException)

Example 20 with ValidationException

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

the class RemoteFileModule method gitHubTarball.

@SuppressWarnings("unused")
@StarlarkMethod(name = "github_archive", doc = "A tarball for a specific SHA1 on GitHub. Experimental.", documented = false, parameters = { @Param(name = "project", named = true, defaultValue = "[]", doc = "The GitHub project from which to load the file, e.g. google/copybara"), @Param(name = "revision", named = true, defaultValue = "[]", doc = "The revision to download from the project, typically a commit SHA1."), @Param(name = "type", named = true, defaultValue = "'TARBALL'", doc = "Archive type to download, options are 'TARBALL' or 'ZIP'.") })
@UsesFlags(RemoteFileOptions.class)
public GithubArchive gitHubTarball(String project, String revision, String type) throws EvalException {
    GeneralOptions generalOptions = options.get(GeneralOptions.class);
    RemoteFileOptions remoteFileOptions = options.get(RemoteFileOptions.class);
    try {
        return new GithubArchive(project, revision, Enums.getIfPresent(GithubArchive.Type.class, type).toJavaUtil().orElseThrow(() -> errorf("Unsupported archive type: '%s'. " + "Supported values: %s", type, Arrays.asList(GithubArchive.Type.values()))), remoteFileOptions.getTransport(), generalOptions.profiler(), generalOptions.console());
    } catch (ValidationException e) {
        throw Starlark.errorf("Error setting up remote http file: %s", e.getMessage());
    }
}
Also used : GeneralOptions(com.google.copybara.GeneralOptions) ValidationException(com.google.copybara.exception.ValidationException) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) UsesFlags(com.google.copybara.doc.annotations.UsesFlags)

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