Search in sources :

Example 6 with ValidationException

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

the class MigrateCmd method loadConfig.

private Config loadConfig(Options options, ConfigLoader configLoader, String migrationName) throws IOException, ValidationException {
    GeneralOptions generalOptions = options.get(GeneralOptions.class);
    Console console = generalOptions.console();
    Config config = configLoader.load(console);
    console.progress("Validating configuration");
    ValidationResult result = configValidator.validate(config, migrationName);
    if (!result.hasErrors()) {
        return config;
    }
    result.getErrors().forEach(console::error);
    console.error("Configuration is invalid.");
    throw new ValidationException("Error validating configuration: Configuration is invalid.");
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) Config(com.google.copybara.config.Config) Console(com.google.copybara.util.console.Console) ValidationResult(com.google.copybara.config.ValidationResult)

Example 7 with ValidationException

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

the class ValidateCmd method validate.

/**
 * Validates that the configuration is correct and that there is a valid migration specified by
 * {@code migrationName}.
 *
 * <p>Note that, besides validating the specific migration, all the configuration will be
 * validated syntactically.
 *
 * Returns true iff this configuration is valid.
 */
private ValidationResult validate(Options options, ConfigLoader configLoader, String migrationName) throws IOException {
    Console console = options.get(GeneralOptions.class).console();
    ValidationResult.Builder resultBuilder = new ValidationResult.Builder();
    try {
        Config config = configLoader.load(console);
        resultBuilder.append(configValidator.validate(config, migrationName));
    } catch (ValidationException e) {
        // The validate subcommand should not throw Validation exceptions but log a result
        StringBuilder error = new StringBuilder(e.getMessage()).append("\n");
        Throwable cause = e.getCause();
        while (cause != null) {
            error.append("  CAUSED BY: ").append(cause.getMessage()).append("\n");
            cause = cause.getCause();
        }
        resultBuilder.error(error.toString());
    }
    return resultBuilder.build();
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) Config(com.google.copybara.config.Config) Console(com.google.copybara.util.console.Console) ValidationResult(com.google.copybara.config.ValidationResult)

Example 8 with ValidationException

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

the class GitHubEndPoint method getPullRequests.

@StarlarkMethod(name = "get_pull_requests", doc = "Get Pull Requests for a repo", parameters = { @Param(name = "head_prefix", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Only return PRs wher the branch name has head_prefix", defaultValue = "None"), @Param(name = "base_prefix", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Only return PRs where the destination branch name has base_prefix", defaultValue = "None"), @Param(name = "state", doc = "State of the Pull Request. Can be `\"OPEN\"`, `\"CLOSED\"` or `\"ALL\"`", defaultValue = "\"OPEN\"", named = true), @Param(name = "sort", doc = "Sort filter for retrieving the Pull Requests. Can be `\"CREATED\"`," + " `\"UPDATED\"` or `\"POPULARITY\"`", named = true, defaultValue = "\"CREATED\""), @Param(name = "direction", doc = "Direction of the filter. Can be `\"ASC\"` or `\"DESC\"`", defaultValue = "\"ASC\"", named = true) }, allowReturnNones = true)
@Nullable
public ImmutableList<PullRequest> getPullRequests(Object headPrefixParam, Object basePrefixParam, String state, String sort, String direction) throws EvalException, RepoException {
    try {
        String project = ghHost.getProjectNameFromUrl(url);
        PullRequestListParams request = PullRequestListParams.DEFAULT;
        String headPrefix = convertFromNoneable(headPrefixParam, null);
        String basePrefix = convertFromNoneable(basePrefixParam, null);
        if (!Strings.isNullOrEmpty(headPrefix)) {
            checkCondition(SAFE_BRANCH_NAME_PREFIX.matches(headPrefix), "'%s' is not a valid head_prefix (%s is used for validation)", headPrefix, SAFE_BRANCH_NAME_PREFIX.pattern());
            request = request.withHead(headPrefix);
        }
        if (!Strings.isNullOrEmpty(basePrefix)) {
            checkCondition(SAFE_BRANCH_NAME_PREFIX.matches(basePrefix), "'%s' is not a valid base_prefix (%s is used for validation)", basePrefix, SAFE_BRANCH_NAME_PREFIX.pattern());
            request = request.withHead(basePrefix);
        }
        return apiSupplier.load(console).getPullRequests(project, request.withState(stringToEnum("state", state, StateFilter.class)).withDirection(stringToEnum("direction", direction, DirectionFilter.class)).withSort(stringToEnum("sort", sort, SortFilter.class)));
    } catch (GitHubApiException e) {
        return returnNullOnNotFound(e);
    } catch (ValidationException | RuntimeException e) {
        throw Starlark.errorf("Error calling get_pull_requests: %s", e.getMessage());
    }
}
Also used : DirectionFilter(com.google.copybara.git.github.api.GitHubApi.PullRequestListParams.DirectionFilter) ValidationException(com.google.copybara.exception.ValidationException) GitHubApiException(com.google.copybara.git.github.api.GitHubApiException) PullRequestListParams(com.google.copybara.git.github.api.GitHubApi.PullRequestListParams) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) Nullable(javax.annotation.Nullable)

Example 9 with ValidationException

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

the class GitHubEndPoint method updateReference.

@StarlarkMethod(name = "update_reference", doc = "Update a reference to point to a new commit. Returns the info of the reference.", parameters = { @Param(name = "ref", named = true, doc = "The name of the reference."), @Param(name = "sha", doc = "The id for the commit" + " status.", named = true), @Param(name = "force", named = true, doc = "Indicates whether to force the update or to make sure the update is a" + " fast-forward update. Leaving this out or setting it to false will make" + " sure you're not overwriting work. Default: false") })
public Ref updateReference(String sha, String ref, boolean force) throws EvalException, RepoException {
    try {
        checkCondition(GitRevision.COMPLETE_SHA1_PATTERN.matcher(sha).matches(), "Not a valid complete SHA-1: %s", sha);
        checkCondition(!Strings.isNullOrEmpty(ref), "ref cannot be empty");
        if (!ref.startsWith("refs/")) {
            // TODO(malcon): Remove this functionality and use a check once library migrated.
            console.warnFmt("Non-complete ref passed to update_reference '%s'. Assuming refs/heads/%s", ref, ref);
            ref = "refs/heads/" + ref;
        }
        String project = ghHost.getProjectNameFromUrl(url);
        return apiSupplier.load(console).updateReference(project, ref, new UpdateReferenceRequest(sha, force));
    } catch (ValidationException | RuntimeException e) {
        throw Starlark.errorf("Error calling update_reference: %s", e.getMessage());
    }
}
Also used : UpdateReferenceRequest(com.google.copybara.git.github.api.UpdateReferenceRequest) ValidationException(com.google.copybara.exception.ValidationException) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Example 10 with ValidationException

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

the class GitHubPrOrigin method checkRequiredCheckRuns.

/**
 * Check that the PR has a conclusion of "success" for each check_run whose name is in the list
 * provided in the `required_check_runs` param
 */
private void checkRequiredCheckRuns(GitHubApi api, String project, PullRequest prData) throws ValidationException, RepoException {
    Set<String> requiredCheckRuns = getRequiredCheckRuns();
    if (forceImport() || requiredCheckRuns.isEmpty()) {
        return;
    }
    try (ProfilerTask ignore = generalOptions.profiler().start("github_api_get_combined_status")) {
        CheckRuns checkRuns = api.getCheckRuns(project, prData.getHead().getSha());
        Set<String> requiredButNotPresent = Sets.newHashSet(requiredCheckRuns);
        List<CheckRun> passedCheckRuns = checkRuns.getCheckRuns().stream().filter(e -> e.getConclusion().equals("success")).collect(Collectors.toList());
        requiredButNotPresent.removeAll(Collections2.transform(passedCheckRuns, CheckRun::getName));
        if (!requiredButNotPresent.isEmpty()) {
            throw new EmptyChangeException(String.format("Cannot migrate http://github.com/%s/pull/%d because the following check runs " + "have not been passed: %s", project, prData.getNumber(), requiredButNotPresent));
        }
    }
}
Also used : GitHubUtil.asHeadRef(com.google.copybara.git.github.util.GitHubUtil.asHeadRef) Origin(com.google.copybara.Origin) CombinedStatus(com.google.copybara.git.github.api.CombinedStatus) Collections2(com.google.common.collect.Collections2) Review(com.google.copybara.git.github.api.Review) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) Matcher(java.util.regex.Matcher) Change(com.google.copybara.Change) BaselinesWithoutLabelVisitor(com.google.copybara.BaselinesWithoutLabelVisitor) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException) Endpoint(com.google.copybara.Endpoint) Splitter(com.google.common.base.Splitter) GeneralOptions(com.google.copybara.GeneralOptions) Path(java.nio.file.Path) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) User(com.google.copybara.git.github.api.User) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) List(java.util.List) GitHubApi(com.google.copybara.git.github.api.GitHubApi) PullRequest(com.google.copybara.git.github.api.PullRequest) GitHubUtil.asMergeRef(com.google.copybara.git.github.util.GitHubUtil.asMergeRef) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) AutoValue(com.google.auto.value.AutoValue) Optional(java.util.Optional) Joiner(com.google.common.base.Joiner) AuthorAssociation(com.google.copybara.git.github.api.AuthorAssociation) Iterables(com.google.common.collect.Iterables) CheckRuns(com.google.copybara.git.github.api.CheckRuns) ValidationException.checkCondition(com.google.copybara.exception.ValidationException.checkCondition) RepoException(com.google.copybara.exception.RepoException) SubmoduleStrategy(com.google.copybara.git.GitOrigin.SubmoduleStrategy) HashSet(java.util.HashSet) GitHubUtil(com.google.copybara.git.github.util.GitHubUtil) Label(com.google.copybara.git.github.api.Label) State(com.google.copybara.git.github.api.Status.State) ImmutableList(com.google.common.collect.ImmutableList) Issue(com.google.copybara.git.github.api.Issue) Nullable(javax.annotation.Nullable) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) CharMatcher(com.google.common.base.CharMatcher) ValidationException(com.google.copybara.exception.ValidationException) ReaderImpl(com.google.copybara.git.GitOrigin.ReaderImpl) PatchTransformation(com.google.copybara.transform.patch.PatchTransformation) Console(com.google.copybara.util.console.Console) TimeUnit(java.util.concurrent.TimeUnit) Authoring(com.google.copybara.authoring.Authoring) Checker(com.google.copybara.checks.Checker) Glob(com.google.copybara.util.Glob) CheckRun(com.google.copybara.git.github.api.CheckRun) Preconditions(com.google.common.base.Preconditions) Status(com.google.copybara.git.github.api.Status) GitHubHost(com.google.copybara.git.github.util.GitHubHost) GitHubPrUrl(com.google.copybara.git.github.util.GitHubHost.GitHubPrUrl) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) CheckRuns(com.google.copybara.git.github.api.CheckRuns) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) CheckRun(com.google.copybara.git.github.api.CheckRun) EmptyChangeException(com.google.copybara.exception.EmptyChangeException)

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